假设我有两个数据表,我想按两个变量合并它们,但更新另一列(时间)大于原始值的条目。此外,它应该是一个完全连接,因此如果新数据中有新变量,则应追加它们。这个问题有什么好的解决方案?
例如:
例如:
## Initial data
dt1 <- data.table(user=c('a', 'a', 'b'),
cell=c(1, 2, 1),
expires=as.POSIXct(rep('Jan 25 21:24', 3), format='%b %d %H:%M'))
## New data to update initial
dt2 <- data.table(user=c('a', 'c'),
cell=c(1, 1),
expires=as.POSIXct(rep('Jan 25 21:59', 2), format='%b %d %H:%M'))
## Attempt
merge(dt1, dt2, by=c('user', 'cell'), all=TRUE)[
, expires := pmax(expires.x, expires.y, na.rm=TRUE)][]
## Desired result: user a in cell 1 has been updated, user c has been added
(res <- rbindlist(list(dt2, dt1[2:3,]))[order(user, cell)])
# user cell expires
# 1: a 1 2016-01-25 21:59:00
# 2: a 2 2016-01-25 21:24:00
# 3: b 1 2016-01-25 21:24:00
# 4: c 1 2016-01-25 21:59:00
res1 <- dt1[dt2, expires:= pmax(expires, i.expires) , on =c('user', 'cell'), by = .EACHI];res2 <- dt2[dt1, expires:= pmax(expires, i.expires) , on =c('user', 'cell'), by = .EACHI]; unique(rbindlist(list(res1, res2)))
。 - akrun