Split a vector into chunks

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

    Here's another variant.

    NOTE: with this sample you're specifying the CHUNK SIZE in the second parameter

    1. all chunks are uniform, except for the last;
    2. the last will at worst be smaller, never bigger than the chunk size.

    chunk <- function(x,n)
    {
        f <- sort(rep(1:(trunc(length(x)/n)+1),n))[1:length(x)]
        return(split(x,f))
    }
    
    #Test
    n<-c(1,2,3,4,5,6,7,8,9,10,11)
    
    c<-chunk(n,5)
    
    q<-lapply(c, function(r) cat(r,sep=",",collapse="|") )
    #output
    1,2,3,4,5,|6,7,8,9,10,|11,|
    

提交回复
热议问题