[英]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. 我有一个data.frame,其值从1到7。我想将1更改为7(反之亦然),将2更改为6(反之亦然),将3更改为5(反之亦然),再将4更改为将保持为4。 Ie 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? 我曾考虑过要编写一个for循环来遍历每个列中的每个值并使用
ifelse
语句,但是我如何才能同时将7从1更改为1?
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
: 考虑到要切换的所有数字对的总和为8,可以从
8
减去原始数据帧,并且所有值都应根据需要还原,因此只需执行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
match
is the right generic way to do this - it will work even when you can't find a nice simple mathematical operation: match
是执行此操作的正确通用方法-即使您找不到很好的简单数学运算,它也将起作用:
First set up key
and value
vectors, where the ith entry of key
you want to replace with the corresponding entry of value
: 首先设置
key
和value
向量,其中要用相应的value
项替换key
的第i个条目:
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. 当然,您可以直接覆盖
X
和Y
我将它们都保留在此处以证明它有效。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.