Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading