简体   繁体   English

合并列名上的 2、1 行 data.tables

[英]Merging 2, 1 row data.tables on column names

I have 2, 1 row data.tables.我有 2、1 行 data.tables。

dt1 <- data.table(a = 0, b = 0, c = 0)
dt2 <- data.table(a = 1, c = 5)

My goal is to update dt1 with the values of dt2 so that I get:我的目标是用dt2的值更新dt1以便我得到:

desired_dt <- data.table(a = 1, b = 0, c = 5) 

I tried merging, assuming it'd match on the shared column names, but no luck.我尝试合并,假设它与共享列名匹配,但没有运气。

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.

Wouldn't this be considered a natural join?这不被认为是自然加入吗? I'd appreciate any help on what I'm missing!对于我所缺少的东西,我将不胜感激!

We get the intersect ing column names and do the assignment我们得到intersect的列名并进行赋值

nm1 <- intersect(names(dt1), names(dt2))
dt1[, (nm1) := dt2]

Or we can set the key或者我们可以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)

Here is a data.table option using rbindlist + fcoalesce这是使用rbindlist + fcoalescedata.table选项

setcolorder(
  rbindlist(
    list(dt2, dt1),
    fill = TRUE
  )[
    ,
    lapply(.SD, function(x) fcoalesce(as.list(x)))
  ], names(dt1)
)[]

which gives这使

   a b c
1: 1 0 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM