开发者

How can I partition a vector?

How can I build a function

slice(x, n) 

which would return a list of vectors where each vector except maybe the last has size n, i.e.

slice(letters, 10)

would return

list(c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"),
     c("k", "l", "m", "n", "o",开发者_开发问答 "p", "q", "r", "s", "t"),
     c("u", "v", "w", "x", "y", "z"))

?


slice<-function(x,n) {
    N<-length(x);
    lapply(seq(1,N,n),function(i) x[i:min(i+n-1,N)])
}


You can use the split function:

split(letters, as.integer((seq_along(letters) - 1) / 10))

If you want to make this into a new function:

slice <- function(x, n) split(x, as.integer((seq_along(x) - 1) / n))
slice(letters, 10)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜