Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active August 9, 2016 14:47
Show Gist options
  • Save alekrutkowski/c0cb05c0c1b758578c8fd7ea2c3f7a0d to your computer and use it in GitHub Desktop.
Save alekrutkowski/c0cb05c0c1b758578c8fd7ea2c3f7a0d to your computer and use it in GitHub Desktop.
A wrapper for base::split taking as an argument the expected number of sub-elements
library(magrittr)
split_into <- function(x, n, sorted=TRUE)
## x -- a vector (atomic or list)
## n -- the number of elements (groups)
## returns a list with n elements
## each containing some of the elements of x
n %>%
seq_len %>%
rep.int(x %>%
length %>%
divide_by(n) %>%
ceiling) %>%
`if`(sorted, sort(.), .) %>%
extract(seq_along(x)) %>%
split(x,.)
## Examples:
## Unlike simple `split(letters[1:7], 1:3)`
## `split_into(letters[1:7], 3, TRUE)` does not
## produce the warning "data length is not a multiple
## of split variable" and allows sorting (i.e. putting
## original nearby elements in the same subgroups):
# split_into(letters[1:7], 3, TRUE)
## $`1`
## [1] "a" "b" "c"
##
## $`2`
## [1] "d" "e" "f"
##
## $`3`
## [1] "g"
#
# split_into(letters[1:7], 3, FALSE)
## $`1`
## [1] "a" "d" "g"
##
## $`2`
## [1] "b" "e"
##
## $`3`
## [1] "c" "f"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment