Adrian Adrian - 24 days ago 10
R Question

R: how to change values in a data.frame

> dummy <- data.frame(X = c(1, 2, 3, 4, 5, 5, 2, 6, 7, 2), Y = c(3, 2, 1, 4, 5, 6, 7, 3, 4, 2))
> dummy
X Y
1 1 3
2 2 2
3 3 1
4 4 4
5 5 5
6 5 6
7 2 7
8 6 3
9 7 4
10 2 2


I have a data.frame that consists of values from 1 to 7. I want to change the 1's to 7's (and vice versa), 2's to 6's (and vice versa), 3's to 5's (and vice versa), and the 4's will stay as 4's. I.e. essentially I want to 'reverse' the numbers. I thought about writing a for loop to iterate over each value in each column and use
ifelse
statements, but how can I change, say, the 7's to 1's and the 1's to 7s simultaneously?

Answer

Considering all the pairs of numbers you want to switch have a sum of 8, you can subtract your original data frame from 8 and all the values should be reverted as you want, so you can just do 8 - dummy:

dummy = 8 - dummy
dummy
#   X Y
#1  7 5
#2  6 6
#3  5 7
#4  4 4
#5  3 3
#6  3 2
#7  6 1
#8  2 5
#9  1 4
#10 6 6
Comments