How do you do conditional "left join" in R? -
i have found myself doing "conditional left join" several times in r. illustrate example; if have 2 data frames such as: > df b 1 1 0 2 2 0 > other.df b 1 2 3 the goal end data frame: > final.df b 1 1 0 2 2 3 the code i've been written far: c <- merge(df, other.df, by=c("a"), all.x = true) c[is.na(c$b.y),]$b.y <- 0 d<-subset(c, select=c("a","b.y")) colnames(d)[2]<-b to arrive result wanted. doing in 4 lines makes code opaque. there better, less cumbersome way this? here 2 ways. in both cases first line left merge returning required columns. in case of merge have set names. final line in both lines replaces na s 0 . merge res1 <- merge(df, other.df, = "a", all.x = true)[-2] names(res1) <- names(df) res1[is.na(res1)] <- 0 sqldf library(sqldf) res2 <- sqldf("select a, o.b df left join 'other.df' o using(a)") res2[is.na(res2)] <- 0