S2her
S2her

Reputation: 61

How to switch every two elements in a vector in R?

For example I have a vector as follows:

FOL.2. FOL TAL.2. TAL BOR.2. BOR HAD.2. HAD ITA.2. ITA NOR.2. NOR

I need the vector to be as follows:

FOL FOL.2. TAL TAL.2. BOR BOR.2. HAD HAD.2. ITA ITA.2. NOR NOR.2.

I tried sort(myvector) but it doesn't work. Basically I need to switch the positions of every two elements in the vector.Any advice is appreciated.

Upvotes: 2

Views: 132

Answers (2)

Darren Tsai
Darren Tsai

Reputation: 35604

Another solution

x[1:length(x) + c(1, -1)]

The operation in [] converts 1, 2, 3, 4, 5, 6 to 2, 1, 4, 3, 6, 5.

Upvotes: 4

akrun
akrun

Reputation: 887891

One option is to create a matrix and then coerce

c(matrix(v1, nrow = 2)[2:1,])
#[1] "FOL"    "FOL.2." "TAL"    "TAL.2." "BOR"    "BOR.2." "HAD"    "HAD.2." "ITA"    "ITA.2." "NOR"    "NOR.2."

data

v1 <- scan(text = "FOL.2. FOL TAL.2. TAL BOR.2. BOR HAD.2. HAD ITA.2. ITA NOR.2. NOR", what = "")

Upvotes: 1

Related Questions