Split a vector into chunks

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

    Using base R's rep_len:

    x <- 1:10
    n <- 3
    
    split(x, rep_len(1:n, length(x)))
    # $`1`
    # [1]  1  4  7 10
    # 
    # $`2`
    # [1] 2 5 8
    # 
    # $`3`
    # [1] 3 6 9
    

    And as already mentioned if you want sorted indices, simply:

    split(x, sort(rep_len(1:n, length(x))))
    # $`1`
    # [1] 1 2 3 4
    # 
    # $`2`
    # [1] 5 6 7
    # 
    # $`3`
    # [1]  8  9 10
    

提交回复
热议问题