简体   繁体   中英

Compare a logical data frame and a numeric data frame

I have 2 data frames:

> df1
  a   b  c
1 1a 11 21
2 2a 12 22
3 3b 13 23
4 4b 14 24
5 5b 15 25
> df2
  a      b     c
1 1a  TRUE  TRUE
2 2a FALSE FALSE
3 3b  TRUE FALSE
4 4b  TRUE  TRUE
5 5b FALSE FALSE

I need to keep only the TRUE values of df1 and replace the FALSE values with NA like this:

> df3
  a     b     c
1 1a   11    21
2 2a   NA    NA
3 3b   13    NA
4 4b   14    24
5 5b   NA    NA

I've been thinking to use a for loop to check each positions of the data frames (only b and c columns) but I wonder if there's a base function or package that I could use.

PS. I need column a to be present all the time in the process in order to not get lost. Thank you all.

If you know that both data.frames have the same values of a in the same order, you can do

if(all(df1$a==df2$a)) {
    is.na(df1[,-1]) <-!df2[,-1]
    # alternatively
    # df1[,-1][!as.matrix(df2[,-1])] <- NA
}

The is.na function allows reassignment and will place NA values wherever the right hand side is TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM