How to calculate the cumulative average for some numbers?

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 make an average of these numbers, I get 3 as a result.

Now, how to make the aggregate average of these numbers.

+5
source share
7 answers

By analogy with the total amount of the list, I propose the following: The total average value of the vector x will contain the average values ​​from the 1st position to the position i.

One method is simply to calculate the average value for each position by summing all previous values ​​and dividing them by their number.

Rewriting the definition of an arithmetic value as a recursive formula. You get

avg(1) = x(1)

and

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

( , , ) .

, , .

1, 2, 3, 4, 5

1, 1.5, 2, 2.5, 3
+14

. - .

+7

, R? Ans: jholtman@gmail.com cumsum() seq_along(), . . 6, 6 + 16, 6 + 16 + 8 ..

   x <- sample(1:20)
    x
 # [1]  6 16  8  1 17 11  2 19 18  5 15 13  3 20  9 14  7 10 12  4

    cumsum(x) / seq_along(x)
 # [1]  6.000000 11.000000 10.000000  7.750000  9.600000  9.833333  8.714286
 #10.000000 10.888889 10.300000
 #[11] 10.727273 10.916667 10.307692 11.000000 10.866667 11.062500 10.823529
 #10.777778 10.842105 10.500000
+6

, , . , , .

Wikipedia . , ( ).

+3
source

This is an old question, and a lot has changed since then. I just decided to update it with an answer dplyr. dplyrhas a function cummeanthat directly gives the cumulative average of the vector.

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

#[1] 1.0 1.5 2.0 2.5 3.0
+1
source

tupit [1] 1 2 3 4 5

cumsum (mynum) / seq (from = 1, to = 5)

[1] 1.0 1.5 2.0 2.5 3.0

0
source

I created a simple C ++ class.

#include <iostream>

using namespace std;

class Average {

public:
    Average(const double initVal=0.0){accumVal=initVal;}
    double getAverage(const double newVal) {

        accumVal += newVal;
        return accumVal / ++numAccumVal;
    }
    void clear(const double clearedVal=0.0) {

        accumVal = clearedVal;
        numAccumVal = 0;
    }
private:
    double accumVal;
    unsigned int numAccumVal=0;
};

int main(int argc, const char * argv[]) {

    Average avg;

    for (size_t i=1; i<=5; ++i) { //feed in 1 to 5

        double result = avg.getAverage(i);
        cout << "Result : " << result << endl; //print the result
    }
    return 0;
}

And if you run the code, you will get the result as shown below.

Result : 1
Result : 1.5
Result : 2
Result : 2.5
Result : 3
Program ended with exit code: 0
0
source

All Articles