Split a vector into chunks

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

    Simple function for splitting a vector by simply using indexes - no need to over complicate this

    vsplit <- function(v, n) {
        l = length(v)
        r = l/n
        return(lapply(1:n, function(i) {
            s = max(1, round(r*(i-1))+1)
            e = min(l, round(r*i))
            return(v[s:e])
        }))
    }
    

提交回复
热议问题