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 tryin
There are several alternatives. Here are three:
df[ df$X1 == "a" , "X1" ] <- df[ df$X1 == "a", "X2" ]
with
:df$X1 <- with( df, ifelse( X1 == "a", X2, X1 ) )
library(data.table) ## >= 1.9.0
setDT(df) ## converts to data.table by reference, no need for `<-`
df[ X1 == "a", X1 := X2 ]
Here's another approach if you have more than one condition (swap "a"
for a vector of values).
> find.a <- df$X1 %in% "a"
> df[find.a, "X1"] <- df[find.a, "X2"]
> df
X1 X2
1 D D
2 3 W
3 Q E
4 F F
5 U P
6 B B