Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join two dataframes in R which only share some similar rows R

I have the following two similar dataframes:

d1<-data.frame(TNR=c(1,2,3,4,5,6,7),EP=c(0,3,1,2,NA,NA,NA))
d2<-data.frame(TNR=c("E",1,3,5,100), EP=c(NA,NA,NA,NA,NA))

In d2 the vector "EP" is empty and i want to fill it with the data from d1$EP, where the vectors TNR overlap with each other. Where they don’t overlap I want to keep d2 and not d1.

The result should look something like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

d3<-data.frame(TNR=c("E",1,3,5,100),EP=c(NA,0,1,NA,NA))

I tried the following approach with ifelse and %in%:

d3<-data.frame(TNR=ifelse(test=d1$TNR %in% d2$TNR, yes=d2$EP, no=NA),
               EP=ifelse(test=d1$TNR %in% d2$TNR, yes=d1$EP, no="")) 
#remove rows where TNR is NA

d4=d3[!is.na(d1$baumnummer),]

However, the result is that EP is inserted in the wrong order and it seems to delete more rows than I anticipated because the resulting dataframe is shorter than d2

>Solution :

Is that OK?

d2$EP <- d1[match(x = d2$TNR, table = d1$TNR), ]$EP
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading