Last active
August 9, 2016 14:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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