Split a vector into chunks

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

    If you don't like split() and you don't like matrix() (with its dangling NAs), there's this:

    chunk <- function(x, n) (mapply(function(a, b) (x[a:b]), seq.int(from=1, to=length(x), by=n), pmin(seq.int(from=1, to=length(x), by=n)+(n-1), length(x)), SIMPLIFY=FALSE))
    

    Like split(), it returns a list, but it doesn't waste time or space with labels, so it may be more performant.

提交回复
热议问题