0

I want to create a column in R that is simply the average of all previous values of another column. For Example:

D
    X
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

I would like D$Y to be the prior average of D$X that is, D$Y is the average of all previous observations of D$X. I know how to do this using a for loop moving through every row, but is there a more efficient manner?

I have a large dataset and hardware not up to that task!

4

1 回答 1

5

您可以像这样生成向量的累积均值:

set.seed(123)
x<-sample(20)
x
## [1]  6 15  8 16 17  1 18 12  7 20 10  5 11  9 19 13 14  4  3  2
xmeans<-cumsum(x)/1:length(x)
xmeans
## [1]  6.000000 10.500000  9.666667 11.250000 12.400000 10.500000 11.571429
## [8] 11.625000 11.111111 12.000000 11.818182 11.250000 11.230769 11.071429
## [15] 11.600000 11.687500 11.823529 11.388889 10.947368 10.500000

所以D$Y<-cumsum(D$X)/1:nrow(D)应该工作。

于 2013-10-09T14:59:51.610 回答