I need to run a script in R that updates values in given rows regarding the history of previous rows. More specifically, I want to calculate averages on some given columns over time. I'll explain.
Say, I have the following table:
Key A B C Date
X 1 0 2 1/1/2017
Y 2 1 1 2/1/2017
X 2 1 3 3/1/2017
X 6 2 2 4/1/2017
Y 3 2 1 5/1/2017
I need to update each line, in order that each of the values from columns A, B and C represent the average of the keys X and Y, up until the given date.
So in this case, we would have something like:
Key A B C Date
X 1 0 2 1/1/2017
Y 2 1 1 2/1/2017
X 1.5 0.5 2.5 3/1/2017
X 3 1 2.3 4/1/2017
Y 2.5 1.5 1 5/1/2017
I'm fairly new to R, and I keep ending up with solutions that look too much like procedural code, and don't seem to fit well. Usually in R there is an known solution that I am unaware of, so if there is any lib of native method for doing this type of conditional updates, any help is welcome. You can also assume that the rows are already ordered by date, in case it helps.
Thanks in advance!
Edit: Fixed wrong example number on row 4, column C.