R Left Outer Join with 0 Fill Instead of NA While Preserving Valid NA's in Left Table

前端 未结 3 1846
礼貌的吻别
礼貌的吻别 2021-02-18 22:53

What is the easiest way to do a left outer join on two data tables (dt1, dt2) with the fill value being 0 (or some other value) instead of NA (default) without overwriting valid

3条回答
  •  没有蜡笔的小新
    2021-02-18 23:36

    I stumbled on the same problem with dplyr and wrote a small function that solved my problem. (the solution requires tidyr and dplyr)

    left_join0 <- function(x, y, fill = 0L){
      z <- left_join(x, y)
      tmp <- setdiff(names(z), names(x))
      z <- replace_na(z, setNames(as.list(rep(fill, length(tmp))), tmp))
      z
    }
    

提交回复
热议问题