user3355655
user3355655

Reputation: 485

R dataframe replace value from another dataframe conditional

I have two dataframes. One with nunbers, and one with status (TRUE or FALSE).

df1<-data.frame(A=c(14,25,37),B=c(12,45,23),C=c(65,29,67))
df2<-data.frame(A=c('FALSE','TRUE','TRUE'),B=c('TRUE','FALSE','FALSE'),C=c('TRUE','TRUE','FALSE'))

I would like to copy value from df1 to df2, if df2 is TRUE.

df3<-data.frame(A=c('FALSE',25,37),B=c(12,'FALSE','FALSE'),C=c(65,29,'FALSE'))

Thank you

Upvotes: 0

Views: 43

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Here is one option:

df3 <- df2
df3[df3 == 'TRUE'] <- df1[df3 == 'TRUE']

df3
      A     B     C
1 FALSE    12    65
2    25 FALSE    29
3    37 FALSE FALSE

Demo

Note: For the above code to work verbatim, I had to slightly alter your definition of df2 to use stringsAsFactors=FALSE. With character data only, it is easy to check for 'TRUE'.

Upvotes: 1

Related Questions