2014-11-06 74 views
-1

我有一個數據結構中的R,如下所示:如何計算平均數在R(數據結構)

> tkr[[i, 4]] 
[1] 81.3 
> tkr[[i - 1, 4]] 
[1] 82.59 
> tkr[[i - 2, 4]] 
[1] 80.69 
> tkr[[i - 3, 4]] 
[1] 79.76 
> tkr[[i - 4, 4]] 
[1] 81.19 
> tkr[[i - 5, 4]] 
[1] 77.71 
> tkr[[i - 6, 4]] 
[1] 77.9 
> tkr[[i - 7, 4]] 
[1] 75.06 
> tkr[[i - 8, 4]] 
[1] 72.76 
> tkr[[i - 9, 4]] 
[1] 75.5 

我想計算這10個值的平均值(行索引而變化,列索引保持恆定在4)。

我試過了:意思是(tkr [i:i - 9,4]),我得到75.5這只是最後一個數據點的值。

平均值是78.446 - 這是我期待的值。

有人可以請指出我在正確的方向嗎?

dput(head(tkr)) 

structure(c(71, 71, 73, 71.35, 69.7, 70.43, 72.5, 73.3, 73.45, 
71.35, 72, 71.27, 70.2, 70.56, 70.89, 70, 69.18, 67.06, 71.44, 
73.08, 71.1, 70.41, 70.28, 67.56, 116744, 150669, 146162, 153921, 
145007, 356811), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", src = "google", updated = structure(1415233768.37727, class = c("POSIXct", 
"POSIXt")), class = c("xts", "zoo"), index = structure(c(1380585600, 
1380672000, 1380758400, 1380844800, 1381104000, 1381190400), tzone = "UTC", tclass = "Date"), .Dim = c(6L, 
5L), .Dimnames = list(NULL, c("DATA.Open", "DATA.High", "DATA.Low", 
"DATA.Close", "DATA.Volume"))) 
+0

能否請您dput(頭(TKR))'的'結果添加到您的文章 – 2014-11-06 01:50:38

回答

0

你還沒有把括號:

mean(tkr[i:(i - 9), 4]) 

或:

mean(tkr[(i - 9):i, 4]) 
+0

謝謝MSO! – dorkboy 2014-11-06 02:04:14