用相同数据框中的另一列的相应值替换列中的值 [英] Replace value in column with corresponding value from another column in same dataframe
问题描述
我试图匹配一列中的特定值,并将其替换为另一列(同一行)中的相应值。这可能很容易...我一直在试图找到一个解决方案, for循环
, sub
,code>子集, data.table
但我还没有成功。必须有一个整洁的方法。
Im trying to match a specific value in one column and replace it with the corresponding value from another column (same row). This is probably very easy... I have been trying to find a solution with for loop
, sub
, subset
, data.table
but I have not succeeded. There must be a neat way of doing this.
示例数据,我们的目标是在第一个交换 a 列与第二列中的相应值并再次输出列。
Example data, where we aim at swapping a
in the first column with the corresponding value in the second column and outputting the column again.
df <- data.frame(rbind(c('a','D'),c('H','W'),c('Q','E'),c('a','F'),c('U','P'),c('a','B')))
df$X1 <- as.character(df$X1)
df$X2 <- as.character(df$X2)
# not working
for (i in seq_along(df$X1)){
a <- df$X1[i]
b <- df$X2[i]
x <- ifelse(a[i=='a'], a[i]<-b[i], do.nothing )
print(x)
}
输出将是这样的;
X1 X2
1 D a
2 H W
3 Q E
4 F a
5 U P
6 B a
(不需要开关)。这是我感兴趣的第一列。
(The switch isn't necessary). It's the first column Im interested in.
任何指针都不胜感激,谢谢!
Any pointer would be appreciated, thanks!
推荐答案
有几种选择。这里有三个:
There are several alternatives. Here are three:
df[ df$X1 == "a" , "X1" ] <- df[ df$X1 == "a", "X2" ]
更简洁,使用与
:
More Terse, using with
:
df$X1 <- with( df, ifelse( X1 == "a", X2, X1 )
最简洁透明使用data.tables
Most terse and transparent Using data.tables
library(data.table) ## >= 1.9.0
setDT(df) ## converts to data.table by reference, no need for `<-`
df[ X1 == "a", X1 := X2 ]
这篇关于用相同数据框中的另一列的相应值替换列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!