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

R – Find the sum for the lagging record and add another column to current value iteratively

So my dataframe is structured like so:

x s
NA 0
13 0
-3 0
2 0
-4 0

for each row in s, I would like to take the lag(s), add it to column x, then set it to the value of s.

my output data would therefore look like:

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

x s
NA 0
13 13
-3 10
2 12
-4 8

I tried the following function, but after fiddling I was only able to get all NA’s or all 0’s:

mydata$s = lag(mydata$s)+mydata$x  

Note – if it helps, I can remove the first row.

>Solution :

It works for me.
Set up:

mydata <- data.frame(x = c(NA, 13, -3, 2, -4), s = c(0, 13, 10, 12, 8) )
mydata$s <- lag(mydata$s)+mydata$x 

Gives:

mydata
   x  s
1 NA NA
2 13 13
3 -3 10
4  2 12
5 -4  8

The difference is my first s is NA. That should be expected as the first x is NA.

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