Split a vector into chunks

后端 未结 20 2254
时光说笑
时光说笑 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:53

    A one-liner splitting d into chunks of size 20:

    split(d, ceiling(seq_along(d)/20))
    

    More details: I think all you need is seq_along(), split() and ceiling():

    > d <- rpois(73,5)
    > d
     [1]  3  1 11  4  1  2  3  2  4 10 10  2  7  4  6  6  2  1  1  2  3  8  3 10  7  4
    [27]  3  4  4  1  1  7  2  4  6  0  5  7  4  6  8  4  7 12  4  6  8  4  2  7  6  5
    [53]  4  5  4  5  5  8  7  7  7  6  2  4  3  3  8 11  6  6  1  8  4
    > max <- 20
    > x <- seq_along(d)
    > d1 <- split(d, ceiling(x/max))
    > d1
    $`1`
     [1]  3  1 11  4  1  2  3  2  4 10 10  2  7  4  6  6  2  1  1  2
    
    $`2`
     [1]  3  8  3 10  7  4  3  4  4  1  1  7  2  4  6  0  5  7  4  6
    
    $`3`
     [1]  8  4  7 12  4  6  8  4  2  7  6  5  4  5  4  5  5  8  7  7
    
    $`4`
     [1]  7  6  2  4  3  3  8 11  6  6  1  8  4
    

提交回复
热议问题