tags:

views:

108

answers:

2

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

?

+4  A: 

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