R data.table中的列的递归更新 [英] Recursive update of columns in R data.table

查看:58
本文介绍了R data.table中的列的递归更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个简单的示例,我需要创建下表(这是我想要的结果):

As a simple example I need to create the following table (this is my desired result):

library(data.table)
DT <- data.table( A= c(2,5,4,-2,4), 
                  B= c(1000,1100,1375,1650,1485), 
                  C= c(50,55,68.75,82.5,74.25), 
                  D= c(100,275,275,-165,297))
DT

这是我到目前为止无法进行的尝试:

This is my attempt so far which is not working:

DT.2 <- data.table(A= c(2,5,4,-2,4) )
DT.2[, B := 1000 ]  # B should begin at 1000, then cumulatively add column D
DT.2[, C := B * 0.05 ]  
DT.2[, D := A * C ]  
DT.2[, B := 1000 + cumsum(shift(D, type= "lag", fill=FALSE)) ]
DT.2

如您所见,由于各列依赖于其他列的结果,因此这些列无法正确更新。在Excel中这是一个非常简单的计算,我只需要了解如何使其适应R。
谢谢

As you can see the columns do not update correctly as each column relies on the results of other columns. It's a very easy calculation in Excel and I just need to understand how to adapt it to R. Thank you

推荐答案

据我所知,您需要一个循环。这是我的输入数据:

So far as I can tell, you need a loop. Here's my input data:

DT <- data.table(A = c(2, 5, 4, -2, 4),
                 B = c(1000, rep(NA, 4)),
                 C = numeric(5),
                 D = numeric(5))

我使用的循环是:

#initial row
DT[1, c("C", "D") := .(.05 * B, .05 * A * B)]

#subsequent rows
for (nn in 2:nrow(DT)){
  new_B <- DT[nn - 1L, B + D]
  DT[nn, c("B", "C", "D") := .(new_B, .05 * new_B, .05 * A * new_B)]
}

也可以轻松地翻译成 sapply ,这样您就没有 nn 坐在您的命名空间中(但现在它将在您的控制台上打印出毫无意义的东西):

Could also easily be translated to a sapply so you don't have nn sitting around in your namespace (but now it will print something meaningless to your console):

sapply(2:nrow(DT), function(nn){
  (same as before)})

是的,我可以想象这在Excel中看起来会简单得多,因为它可以通过单击+拖动自动为您更新公式。

And yes, I can imagine this would look much simpler in Excel since it auto-updates the formula for you with click+drag.

这篇关于R data.table中的列的递归更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆