简体   繁体   English

R-在data.table的列上递归

[英]R - recursion over columns of data.table

I am given data-table, where the (i+1)-th column depends on the previous one and needs to be calculated recursively. 我得到了数据表,其中第(i + 1)列取决于上一个,并且需要递归计算。 The header of data-table consists of a sequence starting from 0.` 数据表的标题由一个从0开始的序列组成。

   0  1  2  3
1: 1 NA NA NA
2: 2 NA NA NA
3: 3 NA NA NA

Accessing the columns by the index, eg dt[,..2] makes the code IMHO the most readable. 通过索引访问列,例如dt[,..2]使代码IMHO最易读。 Yet, this apparently cannot be used when trying to assign: 但是,在尝试分配时,显然不能使用此方法:

library(data.table)
dt <- data.table("0"=c(1,2,3),"1"=c(NA,NA,NA),"2"=c(NA,NA,NA),"3"=c(NA,NA,NA))
x <- c(0.01, 0.02, 0.015)

for (u in 1:3){
               v<- u+1
               dt[,..v] <- dt[,..u]*(1+x[u])
 }

This yields the following error: 这将产生以下错误:

Error in `[<-.data.table`(`*tmp*`, , ..v, value = list(`0` = c(1.01, 2.02,  : object '..v' not found

Update: Thanks @IceCreamToucan for the answer. 更新:感谢@IceCreamToucan的答案。 However, I have just posted a simple example to illustrate my general issue. 但是,我刚刚发布了一个简单的示例来说明我的一般性问题。 Due to the higher complexity of my actual code, I probably will have to stick to a for-loop. 由于实际代码的复杂性较高,因此我可能不得不坚持使用for循环。 So I look to a solution, to recursively access and assign the columns. 因此,我寻求一种解决方案,以递归方式访问和分配列。

You can do this with lapply and cumprod . 您可以使用lapplycumprod进行此cumprod I renamed the varibles because I'm not sure how to deal with numeric column names. 我重命名了变量,因为我不确定如何处理数字列名称。 Also see comments for an outer and cumprod option. 另请参阅有关outercumprod选项的注释。

setnames(dt, names(dt), paste0('v', names(dt)))
dt[, names(dt)[-1] := lapply(cumprod(1 + x), '*', v0)][]

#    v0   v1     v2       v3
# 1:  1 1.01 1.0302 1.045653
# 2:  2 2.02 2.0604 2.091306
# 3:  3 3.03 3.0906 3.136959

You can also do it this way 你也可以这样

for (u in 0:2){
  v <- u+1
  dt[, as.character(v) := get(as.character(u))*(1 + x[u + 1])] 
}

dt[]

#    0    1      2        3
# 1: 1 1.01 1.0302 1.045653
# 2: 2 2.02 2.0604 2.091306
# 3: 3 3.03 3.0906 3.136959

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

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