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

前端 未结 3 1683
礼貌的吻别
礼貌的吻别 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:39

    Could you use column indices to refer only to the new columns, as with left_join they'll all be on the right of the resulting data.frame? Here it would be in dplyr:

    dt1 <- data.frame(x = c('a', 'b', 'c', 'd', 'e'),
                      y = c(NA, 'w', NA, 'y', 'z'),
                      stringsAsFactors = FALSE)
    dt2 <- data.frame(x = c('a', 'b', 'c'),
                      new_col = c(1,2,3),
                      stringsAsFactors = FALSE)
    
    merged <- left_join(dt1, dt2)
    index_new_col <- (ncol(dt1) + 1):ncol(merged)
    merged[, index_new_col][is.na(merged[, index_new_col])] <- 0
    
    > merged
      x    y new_col
    1 a        1
    2 b    w       2
    3 c        3
    4 d    y       0
    5 e    z       0
    

提交回复
热议问题