Beertje
Beertje

Reputation: 539

Replacing NA in dataframe by values in other dataframe

For my R program I would like to replace empty values in a dataframe with the value at the same position in another dataframe. For instance:

A<- data.frame(matrix(ncol = 5, nrow = 2)) 
A[1,] <- c(1,NA,2,2,4)   
A[2,] <- c(1,NA,NA,2,4) 

B<- data.frame(matrix(ncol = 5, nrow = 2)) 
B[1,] <- c(2,3,4,2,4)   
B[2,] <- c(1,4,7,2,9) 

The new dataframe should then be:

A_updated<- data.frame(matrix(ncol = 5, nrow = 2)) 
A_updated[1,]<-c(c(1,3,2,2,4)   
A_updated[2,]<-c(c(1,4,7,2,4)

Is this possible and if so, could somebody help me.

Many thanks in advance

Upvotes: 4

Views: 711

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

You can do

B*is.na(A) + replace(A,is.na(A),0)

or

replace(A,is.na(A),B[is.na(A)])

or a simpler solution (by @27 ϕ 9 in comments)

A[is.na(A)] <- B[is.na(A)]

Upvotes: 5

akrun
akrun

Reputation: 886938

We can use coalesce from dplyr

library(dplyr)
library(purrr)
map2_dfc(A, B, coalesce)
# A tibble: 2 x 5
#     X1    X2    X3    X4    X5
#  <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     3     2     2     4
#2     1     4     7     2     4

Upvotes: 1

s_baldur
s_baldur

Reputation: 33498

A data.table solution that generalises to more than two data.frames

library(data.table)
A[] <- mapply(fcoalesce, A, B) # You could do mapply(fcoalesce, A, B, C, etc.) 

Upvotes: 3

Related Questions