Aziz Ghazi
Aziz Ghazi

Reputation: 11

Calculate the Average of Data frame iteratively

I have a set of Data and I want to be able to iteratively calculate the Average. i.e. the first two points, then the first three points, then first four points, and so on.

For example,

D <- [1, 2, 3, 4, 5, 6]

Average <- [1.5, 2, 2.5, 3, 3.5]

Is there any way to do that in R?

Upvotes: 1

Views: 48

Answers (1)

tpetzoldt
tpetzoldt

Reputation: 5813

Try the following:

D <- c(1, 2, 3, 4, 5, 6)
(cumsum(D)/1:length(D))[-1]
# [1] 1.5 2.0 2.5 3.0 3.5

Upvotes: 1

Related Questions