Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing NA in dataframe by values in other dataframe

Tags:

dataframe

r

na

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

like image 951
Beertje Avatar asked Oct 22 '25 22:10

Beertje


2 Answers

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)]
like image 163
ThomasIsCoding Avatar answered Oct 25 '25 13:10

ThomasIsCoding


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.) 
like image 31
sindri_baldur Avatar answered Oct 25 '25 13:10

sindri_baldur



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!