Reputation: 9793
> 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?
Upvotes: 1
Views: 555
Reputation: 145755
match
is the right generic way to do this - it will work even when you can't find a nice simple mathematical operation:
First set up key
and value
vectors, where the ith entry of key
you want to replace with the corresponding entry of value
:
key = 1:7 # key to look up (current value)
value = 7:1 # desired value corresponding to key
dummy$newX = value[match(dummy$X, key)]
dummy$newY = value[match(dummy$Y, key)]
# X Y newX newY
# 1 1 3 7 5
# 2 2 2 6 6
# 3 3 1 5 7
# 4 4 4 4 4
# 5 5 5 3 3
# 6 5 6 3 2
# 7 2 7 6 1
# 8 6 3 2 5
# 9 7 4 1 4
# 10 2 2 6 6
You could, of course, directly overwrite X
and Y
- I keep them both here to demonstrate that it worked.
Upvotes: 3
Reputation: 23101
Making a little more generic:
max(dummy) + min(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
Upvotes: 2
Reputation: 214927
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
Upvotes: 10