Monday, February 21, 2011

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"))

?

From stackoverflow
  • 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)
    
  • slice<-function(x,n) {
        N<-length(x);
        lapply(seq(1,N,n),function(i) x[i:min(i+n-1,N)])
    }
    
    Karsten W. : Seems to be faster than the split solution...

0 comments:

Post a Comment