Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

r - Calculate cumulative average (mean)

I would like to know how to calculate the cumulative average for some numbers. I will give a simple example to describe what I am looking for.

I have the following numbers

vec <- c(1, 2, 3, 4, 5)

If I do the average of these numbers I will get 3 as a result.

Now, how to do the cumulative average of these numbers.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In analogy to the cumulative sum of a list I propose this: The cumulative average avg of a vector x would contain the averages from 1st position till position i.

One method is just to compute the the mean for each position by summing over all previous values and dividing by their number.

By rewriting the definition of the arithmetic mean as a recursive formula. One gets

avg(1) = x(1)

and

avg(i) = (i-1)/i*avg(i-1) + x(i)/i;    (i > 1)

Evaluating this expression for every element of your vector (or list, one-dimensional array or however you call it) gives you the cumulative average.

This recursive method comes in handy if you have to calculate an average over very large or very many integers and would run into an overflow if you had to store their cumulative sum.

Example

In your example

1, 2, 3, 4, 5

we get

1, 1.5, 2, 2.5, 3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...