Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Merging data.frames in the same column containing NAs

Tags:

merge

dataframe

r

I have four data.frames which all have the same columns, being the first the same to all. In the variable columns there are some NAs.

First, I'd like to replace any value (which is not an NA) in each data.frame by the name of the data.frame. Second, I'd like to merge the data.frames. In this case, for each NA, there will be some other data.frame which would have a value for it, so that I'd end with every cell filled with values (or names of the data.frames).

Here's an example with two data.frames:

 >A
 name Q  W  E  R  T
 g1   NA NA 4  NA 0
 g2   3  2  NA 4  5
 g3   NA 1  NA 0  0
 g4   0  NA NA 1  9

 >B
 name Q  W  E  R  T
 g1   2  4  NA 1  NA
 g2   NA NA 5  NA NA
 g3   5  NA 0  NA NA
 g4   NA 6  4  NA NA

 >result
 name Q  W  E  R  T
 g1   B  B  A  B  A
 g2   A  A  B  A  A
 g3   B  A  B  A  A
 g4   A  B  B  A  A

I've tried some merge() and union() options differently. Also, I've tried to adapt answers to similar questions but I can't seem to solve this.

Creating a function to replace NAs from one data.frame with values from another

Merging data frames with missing values in R

Thank you in advance!

like image 647
afrendeiro Avatar asked Jun 21 '26 03:06

afrendeiro


1 Answers

This may not generalize well for you, but for the data provided...

A <- data.frame(Q=c(NA, 3, NA, 0),
                W=c(NA, 2, 1, NA),
                E=c(4, NA, NA, NA),
                R=c(NA, 4, 0, 1),
                T=c(0,5,0,9), row.names=paste0('g', 1:4), stringsAsFactors=FALSE)

B <- data.frame(Q=c(2, NA, 5, NA),
                W=c(4, NA, NA, 6),
                E=c(NA, 5, 0, 4),
                R=c(1, NA, NA, NA),
                T=c(NA, NA, NA, NA), row.names=paste0('g', 1:4), stringsAsFactors=FALSE)

The result will be "A" anywhere that is A is not NA. It will be "B" wherever B is not NA

result <- A
result[!is.na(A)] <- "A" 
result[!is.na(B)] <- "B"

#   Q W E R T
#g1 B B A B A
#g2 A A B A A
#g3 B A B A A
#g4 A B B A A
like image 74
GSee Avatar answered Jun 23 '26 17:06

GSee



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!