nathan
nathan

Reputation: 191

How to swap the values in two columns in R?

V1    V2
 5     6
 4     4
 2     5

How would I swap the values in these two column vectors. So that the outcome would be:

V1    V2
 6     5
 4     4
 5     2

Upvotes: 3

Views: 4506

Answers (3)

Andrei
Andrei

Reputation: 1

I work with data.table, say, dt. In my case,

dt[1:2] <- dt[2:1]

swaps the first and second rows, while

dt[,1:2] <- dt[,2:1]

swaps the values of the first and second columns leaving the same names.

Upvotes: 0

s_baldur
s_baldur

Reputation: 33613

The easiest way to do this is probably:

df[1:2] <- df[2:1]

That is, it swaps the values but not the column names.

More programmatically:

c2swap <- c("V1", "V2")
df[c2swap] <- df[rev(c2swap)]

Upvotes: 6

Ivan Zatinatscky
Ivan Zatinatscky

Reputation: 26

the easiest way to do this:

tmp <- df[1]
df[1] <- df[2]
df[2] <- tmp

Upvotes: 1

Related Questions