First, simple R example for my problem:
> df
x y
1 1 3
2 2 7
3 4 9
4 8 0
5 3 1
6 12 24
I'd like to compute for each column the mean of three subsequent row data for each row, which results into the following dataframe.
> dfRes
xRes yRes
x y
1 2.333333 6.333333
2 4.666667 5.333333
3 5.000000 3.333333
4 7.666667 8.333333
5 NA NA
6 NA NA
Since I've got very big dataframe with many columns and rows, I'd like to avoid using a for loop for this computation. I've tried defining custom function to use the available sapply
function.
Does somebody know an simple solution in R with a relative fast computation time for this problem?
---- Update ---- The calculation procedure should be something like:
xRes[1] = mean(x[1] + x[2] + x[3])
xRes[2] = mean(x[2] + x[3] + x[4])
...
xRes[5] = NA # because there is no x[7]