[英]Merging 2, 1 row data.tables on column names
我有 2、1 行 data.tables。
dt1 <- data.table(a = 0, b = 0, c = 0)
dt2 <- data.table(a = 1, c = 5)
我的目标是用dt2
的值更新dt1
以便我得到:
desired_dt <- data.table(a = 1, b = 0, c = 5)
我尝试合并,假设它与共享列名匹配,但没有运气。
dt2[dt1]
Error in `[.data.table`(dt2, dt1) :
When i is a data.table (or character vector), the columns to join by must be specified using 'on='
argument (see ?data.table), by keying x (i.e. sorted, and, marked as sorted, see ?setkey), or by
sharing column names between x and i (i.e., a natural join). Keyed joins might have further speed
benefits on very large data due to x being sorted in RAM.
这不被认为是自然加入吗? 对于我所缺少的东西,我将不胜感激!
我们得到intersect
的列名并进行赋值
nm1 <- intersect(names(dt1), names(dt2))
dt1[, (nm1) := dt2]
或者我们可以set
密钥
setkeyv(dt1, intersect(names(dt1), names(dt2)))
out <- dt1[dt2]
for(j in seq_along(out)) set(out, i = which(is.na(out[[j]])), j=j, value = 0)
这是使用rbindlist
+ fcoalesce
的data.table
选项
setcolorder(
rbindlist(
list(dt2, dt1),
fill = TRUE
)[
,
lapply(.SD, function(x) fcoalesce(as.list(x)))
], names(dt1)
)[]
这使
a b c
1: 1 0 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.