2012-07-09 148 views
1

我有一個for循環,將值填充到名爲Df的數據框中。我的所有列填充準確,但下面的代碼行不產生價值,我想:計算滯後值

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

這是P2-P1/P1的簡單回報計算。我的一位朋友提出了一個操作順序問題,但解決方案是什麼?

謝謝!

+0

由於您使用了圓括號,因此不能是操作順序問題。如果你沒有,你會得到'P2 - P1',因爲除法之前的分割,但你做到了,所以不是這樣。 – Joshua 2012-07-09 05:27:27

回答

2

沒有一個可重複的例子很難回答,但你不應該需要在一個循環中完成此操作。這是否做你想要的?

#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