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
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