Nick Knauer
Nick Knauer

Reputation: 4243

Replace Values with NA by same position in another df

I have two dataframes:

df1
 Col1     Col2      Col3     Col4
    1        0         3        5 
   NA        1        NA        0
    2        3        NA        5

df2
 Col1     Col2      Col3     Col4
    7        0         5        7 
    0        8         0        0
    9        9         6        2

How do I replace df2 with NA's by same position of df1?

I want my final df3 to look like this:

 Col1     Col2      Col3     Col4
    7        0         5        7 
   NA        8        NA        0
    9        9        NA        2

Upvotes: 1

Views: 41

Answers (2)

Jaap
Jaap

Reputation: 83235

In my opinion base R is better equiped for that compared to the tidyverse:

df2[is.na(df1)] <- NA

which gives:

> df2
  Col1 Col2 Col3 Col4
1    7    0    5    7
2   NA    8   NA    0
3    9    9   NA    2

And if you really need df3:

df3 <- df2
df3[is.na(df1)] <- NA

Upvotes: 3

Onyambu
Onyambu

Reputation: 79238

df3=`is.na<-`(df2,is.na(df1))
df3
  Col1 Col2 Col3 Col4
1    7    0    5    7
2   NA    8   NA    0
3    9    9   NA    2

or even

df3=replace(df2,is.na(df1),NA)
 df3
  Col1 Col2 Col3 Col4
1    7    0    5    7
2   NA    8   NA    0
3    9    9   NA    2

Upvotes: 0

Related Questions