Split a vector into chunks

后端 未结 20 1903
时光说笑
时光说笑 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 02:07

    This splits into chunks of size ⌊n/k⌋+1 or ⌊n/k⌋ and does not use the O(n log n) sort.

    get_chunk_id<-function(n, k){
        r <- n %% k
        s <- n %/% k
        i<-seq_len(n)
        1 + ifelse (i <= r * (s+1), (i-1) %/% (s+1), r + ((i - r * (s+1)-1) %/% s))
    }
    
    split(1:10, get_chunk_id(10,3))
    

提交回复
热议问题