How do I recode a column based on values from other columns? Say I have the below data frame and I want to recode df$Col3
so that the value is 0 if df$Col1 == x
and df$Col2 == a
.
> df <- data.frame(a=c(rep("x",3),rep("y",3),rep("x",4)),letters[c(1:5,3,4:1)],1:10)
> names(df)<-c("Col1","Col2","Col3")
> df
Col1 Col2 Col3
1 x a 1
2 x b 2
3 x c 3
4 y d 4
5 y e 5
6 y c 6
7 x d 7
8 x c 8
9 x b 9
10 x a 10
You can use ifelse
> df$Col3 <- with(df, ifelse(Col1=='x' & Col2=='a', 0, Col3))
> df
Col1 Col2 Col3
1 x a 0
2 x b 2
3 x c 3
4 y d 4
5 y e 5
6 y c 6
7 x d 7
8 x c 8
9 x b 9
10 x a 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With