我想根据另一个表中的覆盖更正一个表。当dt_override具有该单位且日期范围与dt_current重叠时,我想更改dt_current中的值。
dt_current <- data.table( unit = c(rep("a",10), rep("b", 10)),
date = seq(as.Date("2015-1-1"), by = "day", length.out = 10),
num = 1:10, key = "unit")
dt_override <- data.table( unit = c("a", "a", "b", "zed" ), start_date = as.Date(c("2015-01-03", "1492-12-25", "2015-01-02", "2015-01-11")),
end_date = as.Date(c("2015-01-05", "1492-12-26", "2015-01-04", "2015-01-14")),
value = NA, key = "unit")
似乎我应该在加入两个数据表时使用某种形式的.EACHI,编码如下所示,认为它不起作用或当然。
dt_current[dt_override,
num := if(i.start_date <= date & i.end_date >= date) i.value,
by = .EACHI]
答案 0 :(得分:6)
使用td {
position: relative;
line-height: 60px; /*a bit hacky but works*/
}
td a, td span {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
text-decoration: none;
}
td a:hover {
background: #c2ceb5;
}
可以做
foverlaps
第一个选项,创建和索引并通过引用更新
dt_current[, date2 := date] # define end date
setkey(dt_current, unit, date, date2) # key by unit, start and end dates
setkey(dt_override, unit, start_date, end_date) # same
Alernatively,您可以反过来运行indx <- foverlaps(dt_override, dt_current, which = TRUE) # run foverlaps and get indices
dt_current[indx$yid, num := dt_override[indx$xid, value]] # adjust by reference
并避免创建foverlaps
,但在创建全新数据集时
indx
答案 1 :(得分:4)
使用滚动连接的另一种选择:
setkey(dt_current, unit, date)
setkey(dt_override, unit, start_date)
dt_current[, num := dt_override[dt_current, roll = T][end_date >= start_date,
num := value]$num]
# another version of the above, but using ifelse (unclear to me which one is faster)
dt_current[, num := dt_override[dt_current,
ifelse(end_date >= start_date, value, num), roll = T]]
答案 2 :(得分:2)
这是一种方式,枚举日期序列:
dt_override[,value:=as.integer(value)]
# It's necessary to convert to integer because `NA` is logical unless otherwise specified.
dto = dt_override[,.(
unit,
date = seq.Date(start_date,end_date,by="day"),
value
),by=seq_along(dt_override)][,seq_along:=NULL]
setkey(dt_current,unit,date)
dt_current[dto,num:=i.value]
现在foverlaps
已经存在,可能有更好的方法。