Home > Net >  Change position of elements 1:2 in a vector
Change position of elements 1:2 in a vector

Time:06-07

I have this vector:

vector_have <- c("A", "B", "C", "A1", "B2", "C3")

[1] "A"  "B"  "C"  "A1" "B2" "C3"

I would like to get:

vector_wanted <- c("A1", "A", "B2", "B", "C3", "C")

[1] "A1" "A"  "B2" "B"  "C3" "C" 

I have tried:

sort(vector_have)

[1] "A"  "A1" "B"  "B2" "C"  "C3"

Now I would like to switch the position of each second element to the preceding one.

I think it must be done with TRUE, FALSE iteratively.

CodePudding user response:

Using mixed_sort does it

gtools::mixedsort(vector_have)
[1] "A1" "A"  "B2" "B"  "C3" "C" 

Or if it is based on the position, another option is matrix

 c(matrix(vector_have, ncol = 3, byrow = TRUE)[2:1,])
[1] "A1" "A"  "B2" "B"  "C3" "C" 
  • Related