Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling in a new column based on a condition in a data frame

Tags:

dataframe

r

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.

like image 694
daragh Avatar asked Dec 29 '25 05:12

daragh


1 Answers

If LOC only contains 1 or 2 then this will work

 df$V <- ifelse(df$LOC == 1, df$V1, df$V2)
like image 139
Jacob H Avatar answered Dec 30 '25 20:12

Jacob H