I want to add a new column in my data frame so that for each row if LOC == 1 then V is equal to the value given for V1; if LOC==2 then V is equal to the value given for V2. Here is an example:
df <-
LOC V1 V2
1 0.5 0.7
1 0.5 0.7
2 0.5 0.7
1 0.6 0.8
Result should be:
df <-
LOC V1 V2 V
1 0.5 0.7 0.5
1 0.5 0.7 0.5
2 0.5 0.7 0.7
1 0.6 0.8 0.6
I need help on how to do that in R.
If LOC only contains 1 or 2 then this will work
df$V <- ifelse(df$LOC == 1, df$V1, df$V2)
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