Split vector at multiplicity of a number

Viewed 108

I want to split a vector at a multiplicity of a number so giving vector c(1:100) I would like to receive vectors like:

c(1,11,21,31,41,51,61,71,81,91) 
c(2,12,22,32,42,52,62,72,82,92) 
..... 
c(10,20,30,40,50,60,70,80,90,100)

Note that i want the vector c(1,11,21,31,41,51,61,71,81,91) to be the FIRST in the list of new vectors, because I know that split(1:100,1:100 %% 10)[1] is c(10,20,30,40,50,60,70,80,90,100) which is not what I want

EDIT The 1:100 example is just an example. In my app I want to split a vector of 256 numbers (random numbers not from 1 to 256) and divide it to 16 new vectors...

3 Answers

Sounds like you want split(1:100,1:100 %% 10). Some options for ordering include:

x <- split(1:100,1:100 %% 10)
c(tail(x,-1),head(x,1))

or from the comments above,

split(1:100,((1:100 %% 10) -1) %% 10)

This is uglier than joran's answer, but you could also do that in a loop, and use grep() to extract those numbers ending in a particular value:

yourlist <- vector("list", 10)

for (i in 1:10) {
  yourlist[[i]] <- grep(paste0(i %% 10, "$"), 1:100)
}

As in the comment, perfect choice would be to make it like this:

split(1:100,0:99 %% 10) 

In such case we can make it really generic so as:

split(vec, 0:(length(vec)-1) %% X)

where vec is the vector we want to divide and X is your multiplicity

Related