How to add a value from a row to the previous one in a column in R?

I have a dataset similar to the dataset below,

Row Date       Value
1   2022-01-03 400
2   2022-01-04 350
3   2022-01-05 368
4   2022-01-06 418
...

I would like to calculate B by using a formula like below

B = ((Value2 + Value1) / 2) + ((Value3 + Value2) / 2) + ((Value4 + Value3) / 2) + ...

I am expecting the output to be

B = ((350 + 400)/2) + ((368 + 350)/2) + ((418 + 368)/2) = 1127

I would appreciate if you could help me with.

Thanks in advance

>Solution :

Another way:

sum((df$Value[-nrow(df)] + df$Value[-1])/2)

Leave a Reply