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.
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)
}
The output would be like this;
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!