Madhu Sareen Madhu Sareen - 1 year ago 41
R Question

in R how to compute means of increasing number/order of sequence

Suppose I have a data frame which is something like the one below:

mydataframe <- data.frame(x=1:10, y=c(2,4,6,8,11,14,17,19,22,29))

plot(mydataframe$y, type = "l", lwd="3", col="red")


What I am trying to do is to compute averages such as average of y[1]=2, y[1,2]=3 and so forth...

y Avg basically
2 2 2/1
4 3 (2+4)/2
6 4 (2+4+6)/3
8 5 (2+4+6+8)/4
11 6 (2+4+6+8+11)/5
14 8 so forth
17 9
19 10
22 11
29 13


I was trying using for loop, but I know I am wrong and won't get the desired result...

for (i in 1:length(mydataframe$x)) {
print (mean(mydataframe$y[i]))
}


Can someone help please? Thanks.

Answer Source

You can simply use cumsum divided by x,

cumsum(mydataframe$y)/mydataframe$x
#[1]  2.000000  3.000000  4.000000  5.000000  6.200000  7.500000  8.857143 10.125000 11.444444 13.200000
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download