google-sheetsgoogle-sheets-formulamoving-average

Moving average conditioned in Google Sheets


I have a Google Sheet in which I have to calculate a moving average conditioned to the 'ID' that calculates the average of the last 3 periods. Any idea on how to do it? I leave an example with the final results (column "Mean Average (last 3)"). Regards!

ID  value   Mean Average (last 3)
1   12  12,00
1   19  12,00
1   19  15,50
1   18  16,67
1   13  18,67
2   11  11,00
2   18  11,00
2   15  14,50
2   17  14,67
2   11  16,67
3   11  11,00
3   16  11,00
3   10  13,50
3   11  12,33

Solution

  • I've got an answer that may work for you. Assuming that your sample data is in columns A4:C (see my sample sheet), try the following formula in column D, in the same row as your data headers.

    ={"Mean Avg";ArrayFormula(
      IF(ROW(A4:A18)<ROW(A$4)+2,
         C$4,
         IF(NOT(EQ(A4:A18,OFFSET(A4:A18,-1,0))),
           B4:B19,
           IF(NOT(EQ(A4:A18,OFFSET(A4:A18,-2,0))),
             B3:B18,
             IF(NOT(EQ(A4:A18,OFFSET(A4:A18,-3,0))),
               (B2:B17+B3:B18)/2,
               (B1:B16+B2:B17+B3:B18)/3)))))}
    

    The first IF checks whether it is one of the first two data rows, to force the initial values. The next IF checks if the ID is not equal to the row above, and forces the start of a new Average, with just one value. The next IF checks if it is the second ID in a series (NOT EQual to the ID 2 rows up), and if yes, also uses the single value from the row above.

    The next IF checks up three rows, and if the IDs are different, it averages the values from the two rows above.

    Otherwise, this is the fourth data row in a series with the same ID, and the formula takes the values from the three rows above, and averages them.

    Due to the offsets, it seems quite sensitive to ranges, so it may need some tuning if you move it.

    Let me know if this helps.

    enter image description here