user3641630
user3641630

Reputation: 335

Fill in NA with Non-NAs in another dataframe

I have three sets of data with two variables "ID" and "Name". Is there a way to fill in the missing in each dataset from another dataset or create a master dataset with a combination of ID and Name?

setA=data.frame(rbind(
                      c("1","Product A"),
                      c("2",NA),
                      c("3",NA),
                      c("4",NA),
                      c("5","Product E")))
names(setA)=c("ID","Name")

setB=data.frame(rbind(
                      c("1","Product A"),
                      c("2",NA),
                      c("3","Product C"),
                      c("4",NA),
                      c("6","Product F")))
names(setB)=c("ID","Name")

setC=data.frame(rbind(
                      c("1",NA),
                      c("2","Product B"),
                      c("3","Product C"),
                      c("4","Product D"),
                      c("6","Product F")))
names(setC)=c("ID","Name")

I tried this, but it list the ID "3" two times. I want the NA to fill in with "Product C".

merge(setA,setB,by=c("ID","Name"),all=T)

I can merge on just ID and replace NAs with non-NAs but was wondering if there was a more straight forward way to do it?

Thanks!

Upvotes: 1

Views: 114

Answers (1)

teucer
teucer

Reputation: 6238

I don't know if the solution below is generalisable, but based on your example the following code would do the trick (this assumes that the Name exists at least once for each ID and that it is unique):

setM <- rbind(setA,setB,setC)
setM <- unique(na.omit(setM))

Upvotes: 1

Related Questions