Reputation: 325
I have the following column:
ColA ColB
1 f
2 f
1 f
1 f
2 f
How do I switch the 1's to 2's and 2's to 1's in ColA?
Upvotes: 2
Views: 46
Reputation: 2849
Here is another way to solve this using transform
from base r
with an ifelse
.
# Data: (h/t @akrun)
df1 <- structure(list(ColA = c(1L, 2L, 1L, 1L, 2L), ColB = c("f", "f",
"f", "f", "f")), class = "data.frame", row.names = c(NA, -5L))
# Code:
transform(df1, ColA = ifelse(ColA == 1, 2, 1))
# Output:
#> ColA ColB
#> 1 2 f
#> 2 1 f
#> 3 2 f
#> 4 2 f
#> 5 1 f
Created on 2020-11-21 by the reprex package (v0.3.0)
Upvotes: 1
Reputation: 887118
If there are only 1 and 2 values, we can make use of arithmetic to change the values
df1$ColA <- with(df1, 2- ColA + 1)
df1$ColA
#[1] 2 1 2 2 1
Or using match
match(df1$ColA, c(2, 1))
Or using factor
factor(df1$ColA, levels = 1:2, labels = 2:1)
df1 <- structure(list(ColA = c(1L, 2L, 1L, 1L, 2L), ColB = c("f", "f",
"f", "f", "f")), class = "data.frame", row.names = c(NA, -5L))
Upvotes: 3