Split a vector into chunks

后端 未结 20 1895
时光说笑
时光说笑 2020-11-22 01:10

I have to split a vector into n chunks of equal size in R. I couldn\'t find any base function to do that. Also Google didn\'t get me anywhere. Here is what I came up with so

20条回答
  •  终归单人心
    2020-11-22 01:58

    A few more variants to the pile...

    > x <- 1:10
    > n <- 3
    

    Note, that you don't need to use the factor function here, but you still want to sort o/w your first vector would be 1 2 3 10:

    > chunk <- function(x, n) split(x, sort(rank(x) %% n))
    > chunk(x,n)
    $`0`
    [1] 1 2 3
    $`1`
    [1] 4 5 6 7
    $`2`
    [1]  8  9 10
    

    Or you can assign character indices, vice the numbers in left ticks above:

    > my.chunk <- function(x, n) split(x, sort(rep(letters[1:n], each=n, len=length(x))))
    > my.chunk(x, n)
    $a
    [1] 1 2 3 4
    $b
    [1] 5 6 7
    $c
    [1]  8  9 10
    

    Or you can use plainword names stored in a vector. Note that using sort to get consecutive values in x alphabetizes the labels:

    > my.other.chunk <- function(x, n) split(x, sort(rep(c("tom", "dick", "harry"), each=n, len=length(x))))
    > my.other.chunk(x, n)
    $dick
    [1] 1 2 3
    $harry
    [1] 4 5 6
    $tom
    [1]  7  8  9 10
    

提交回复
热议问题