1

Suppose that I have a vector as this:

s <- c(1:30) ## here the numbers are just an example. I just need to split it into the same length subvectors. 

Then, suppose that I have other three vectors:

s1 <- s2 <- s3 <- vector()

I would like to split the first vector s into three subvectors each with 10 elements. Then, I would like to save each 10 elements in the vectors s1:s3. For example,

I would like to have this:

  > s1
 [1]  1  2  3  4  5  6  7  8  9 10

> s2
 [1] 11 12 13 14 15 16 17 18 19 20

> s3
 [1] 21 22 23 24 25 26 27 28 29 30

I would like to do that with lapply because sometimes I need to split the vector to 10, 3 or any arbitrary number of subvectors depends on my data.

1 Answers1

1

We can split the vector 's' with a grouping index created with gl. The output will be a list and it is better to keep it in the list instead of multiple objects in the global environment

lst <- split(s, as.integer(gl(length(s), 10, length(s))))

gl creates a grouping vector

as.integer(gl(length(s), 10, length(s)))
#[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3

and when split the 's' by the output of gl, the first 10 values of 's' are grouped together, then the second 10 and so on. These are stored as list of vectors

akrun
  • 874,273
  • 37
  • 540
  • 662