1

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
Jaap
  • 81,064
  • 34
  • 182
  • 193
nak5120
  • 4,089
  • 4
  • 35
  • 94
  • 4
    `df3 <- df2; df3[is.na(df1)] <- NA` – Jaap Jun 12 '18 at 18:48
  • Related / possible duplicate: [*How do I replace NA values with zeros in an R dataframe?*](https://stackoverflow.com/q/8161836/2204410) – Jaap Jun 12 '18 at 18:54

2 Answers2

3

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
Jaap
  • 81,064
  • 34
  • 182
  • 193
0
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
Onyambu
  • 67,392
  • 3
  • 24
  • 53