Split a vector into chunks

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

    If you don't like split() and you don't mind NAs padding out your short tail:

    chunk <- function(x, n) { if((length(x)%%n)==0) {return(matrix(x, nrow=n))} else {return(matrix(append(x, rep(NA, n-(length(x)%%n))), nrow=n))} }
    

    The columns of the returned matrix ([,1:ncol]) are the droids you are looking for.

提交回复
热议问题