1

The length of each sublist is specified to be LEN. All sublists, except possibly the last one, should have exactly LEN elements in the original list.

The input can be a list (of same type elements) or a vector. The output type should correspond.

For instance:

Given c(1, 2, 3, 4, 5) and LEN = 2, the function should return c(c(1, 2), c(3, 4), c(5)).

Given list("", "hi", "world", "R is hard") and LEN = 2, the function should return list(list("", "hi"), list("world", "R is hard").

I am looking for an R-idiomatic way to do this. In other languages a for loop suffices.

Or, since I am a complete newbie to R, the setup of this problem may not be idiomatic in the first place. If so please kindly point it out. However the input is fixed to be a list or a vector.

Thanks!

joran
  • 169,992
  • 32
  • 429
  • 468
Covi
  • 1,331
  • 1
  • 14
  • 17

1 Answers1

5

As @joran mentioned you should have a look at ?split. To solve your specific problem:

a <- 1:5
n <- length(a)
k <- 2 ## your LEN
split(a, rep(1:ceiling(n/k), each=k)[1:n])
#$`1`
#[1] 1 2
#
#$`2`
#[1] 3 4
#
#$`3`
#[1] 5
sgibb
  • 25,396
  • 3
  • 68
  • 74