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
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)]
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With