【问题标题】:Calculating lagged values计算滞后值
【发布时间】:2012-07-09 05:16:45
【问题描述】:

我有一个用于将值填充到名为 Df 的数据框中的 for 循环。我的所有列都准确填充,但以下代码行没有产生我想要的值:

for(i in 2:(dim(Df)[1])){
Df$dailyReturns200[i] <- (Df$index200[i+1]-Df$index200[i])/Df$index200[i]
}

这是一个简单的 P2-P1/P1 回报计算。我的一个朋友提出了一个操作顺序问题,但是解决方案是什么?

谢谢!

【问题讨论】:

  • 这不可能是运算顺序问题,因为您使用了括号。如果你没有,你会得到P2 - P1,因为除法在减法之前,但你做到了,所以不是这样。

标签: r loops for-loop


【解决方案1】:

如果没有可重复的示例,很难回答,但您根本不需要循环执行此操作。这符合你的要求吗?

#Start with a simple one column matrix
x <- matrix(1:6, ncol = 1)

#Compute the diffence, pad with an NA at the front, and then divide by x
cbind(x, c(NA, diff(x))/x)
#----
     [,1]      [,2]
[1,]    1        NA
[2,]    2 0.5000000
[3,]    3 0.3333333
[4,]    4 0.2500000
[5,]    5 0.2000000
[6,]    6 0.1666667

从帮助页面,diff() 返回一个suitably lagged and iterated differences.。在这种情况下,所有的差都为 1,然后除以 x,如上所示。详情请见?diff。

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2017-11-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多