Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NA values in one dataframe with values from a second

Tags:

dataframe

r

I have two dataframes that look like so:

df1:

     A    B    C    D   E   F.              EMAIL
1   78   46   65   59  NA  NA. [email protected]
2   60   51   64   67  NA  NA. [email protected]
3   72   83   54   72  NA  NA. [email protected]

df2:

     A    B    C    D   E   F.              EMAIL
1   NA   NA   NA   NA  71  99. [email protected]
2   NA   NA   NA   NA  53  74. [email protected]

what I want to end up with is: df3

     A    B    C    D   E   F               EMAIL
1   78   46   65   59  71  99. [email protected]
2   60   51   64   67  53  74. [email protected]
3   72   83   54   72  NA  NA. [email protected]

I have tried merge, coalesce, join, rqdatable all with no success. I am new to R and am running out of ideas on how to make this happen. How can I replace the values of one dataframe with values from a second?

Thanks! -g

like image 899
Gary Avatar asked Dec 09 '25 17:12

Gary


1 Answers

i <- seq(nrow(df2))

df1[i,] <- Map(function(x, y) ifelse(is.na(x), y, x),
               df1[i,], df2)

df1
#    A  B  C  D  E  F
# 1 78 46 65 59 71 99
# 2 60 51 64 67 53 74
# 3 72 83 54 72 NA NA
like image 97
IceCreamToucan Avatar answered Dec 11 '25 12:12

IceCreamToucan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!