Search code examples
rsortingvectordplyrnumeric

How to split integer vector in R


I have a vector of integers that I want to split by 3, then I have to order the splitted parts and put bac into integer vector.

as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))

First step - split like this:

16,9,2
17,10,3
18,11,4
19,12,5
20,13,6
21,14,7
22,15,8

Second step - order:

2,9,16
3,10,17
4,11,18
5,12,19
6,13,20
7,14,21
8,15,22

Third step - put back into integer vector:

2,9,16,3,10,17,4,11,18,5,12,19,6,13,20,7,14,21,8,15,22

Solution

  • No {dplyr} required here.

    x <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))
    spl.x <- split(x, ceiling(seq_along(x)/3)) # split the vector
    spl.x <- lapply(spl.x, sort) # sort each element of the list
    Reduce(c, spl.x) # Reduce list to vector
    

    Second line (splitting) is from this answer: https://stackoverflow.com/a/3321659/2433233

    This also works if the length of your original vector is no multiple of 3. The last list element is shorter in this case.