[英]Working with Data.table within Data.table in R
I'm trying to build a column in a data.table by interacting with another data.table and having trouble referring to variables correctly to do this without a for-loop. 我试图通过与另一个data.table进行交互来在data.table中建立一列,并且在没有for循环的情况下无法正确引用变量来做到这一点。 Once I enter the second data.table, I can no longer seem to refer to the column in the first data.table correctly.
输入第二个data.table后,似乎不再能正确引用第一个data.table中的列。
This is kind of similar to Subsetting a data.table using another data.table but I believe the merge-style solutions aren't appropriate. 这有点类似于使用另一个data.table设置data.table的子集,但是我认为合并样式的解决方案不合适。
Consider something like 考虑类似
#used numbers instead of dates to not have to deal with formatting, but idea is the same.
dt1 <- data.table(id = c('a', 'b', 'c'), date1 = c(1.1, 5.4, 9.1), amt= '100')
dt2 <- data.table(date2 = c(1.3, 3, 6.4, 10.5),
dt2col = c(1.5, 1.02, 1.005, .99)
)
dt1[result := prod(dt2[date2-(date1)>0,
dt2col
]
)
]
I want the result to be a new column in dt1 which is the product of dt2col when date2 (in dt2) is later than date1 (in dt1) for each specific row in dt1. 我希望结果是dt1中的每个特定行的date2(在dt2中)晚于date1(在dt1中)时dt1中的新列,它是dt2col的乘积。 I think the (date1) part is the problem.
我认为(date1)部分是问题。
I expect result[1] to be the product of dt2col for all of them, but result[2] to be the product of dt2col for only the dates after '5/4/2018', etc. 我希望result [1]都是dt2col的乘积,但仅在'5/4/2018'之后的日期,结果是dt2col的乘积,等等。
Try this:
dt1[,`:=`(date1 = as.Date.character(date1,format = "%d/%m/%Y"))]
dt2[,`:=`(date2 = as.Date.character(date2,format = "%d/%m/%Y"))]
dt1[,`:=`(inds = lapply(X = date1,function(t){
intersect(x = which(year(t)==year(dt2$date2)),
y = which(as.integer(dt2$date2-t)>0))}))][,result:=
lapply(X = inds,function(t){prod(dt2$dt2col[t])})]
# id date1 amt inds result
#1: a 2018-01-01 100 1,2,3,4 1.522273
#2: b 2018-04-05 100 1,4 1.485
#3: c 2018-01-09 100 1,4 1.485
Here are some data.table
options: 以下是一些
data.table
选项:
1) Using non-equi joins: 1)使用非等额联接:
dt1[, result := dt2[dt1, on=.(date2 > date1), prod(dt2col), by=.EACHI]$V1]
dt1
2) Using rolling joins after calculating the cumulative product: 2)在计算累积乘积后使用滚动联接:
setorder(dt2, -date2)
dt2[, cprod := cumprod(dt2col)]
dt1[dt2, result := cprod, on=.(date1=date2), roll=Inf]
output: 输出:
id date1 amt result
1: a 1.1 100 1.522273
2: b 5.4 100 0.994950
3: c 9.1 100 0.990000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.