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

In R conditional statement with lag value and starting value

I want to create a new column y that adds x to previous y value (i.e. lag(y)) and prints based on conditions below. The start value of y is 44169.

if (x + lag(y)) is greater or equal than 44169, than 44169 is printed.
if (x + lag(y)) is less than 44169, then print x + lag(y).

I am tripped up by the lag and how to handle the starting value. Data and desired results are below, Thanks for your help

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

date<-seq(as.Date('1968-04-01'),as.Date('1968-09-01'), by='month')
x<-c(20,10,-15,-12,5,-50)
df<-data.frame(date,x)

tried and failed

df2<- df %%
  mutate(y = if (x+lag(y) > 44169) {
      44169}
  else {x + lag(y)}
    )
y<-c(44169, 44169, 44154, 44142, 44147, 44169)
result<- data.frame(date,x,y)

>Solution :

We may use accumulate

library(dplyr)
library(purrr)
df %>% 
  mutate(y = accumulate(x, ~
     if((.x + .y) > 44169) 44169 else .x + .y, .init = 44169)[-1])

Or with pmin/min

df %>%
   mutate(y = accumulate(x, ~ pmin(44169, .x + .y), .init = 44169)[-1])
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