vickm
vickm

Reputation: 23

How to create a variable that uses previous (lagged) instance of its own value?

There is a panel dataset. I have to compute a new variable:

cases_new = 3^(lag(cases, n=1L))

for the first date alone. Then the 2nd date onwards, it uses lag (i.e previous instance) on its own value, i.e.:

cases_new = 3^lag(cases_new, n=1L)

I tried to implement using the following code:

df2 <-df1 %>%
  mutate(cases_new = if_else(date == "2020-01-01", 3^(lag(cases, n=1L)), 3^(lag(cases_new, n=1L)))

But it threw an error stating that object 'cases_new' not found. I even tried initializing cases_new prior to the above assignment by:

df1$cases_new <- NA

But this did not update cases_new correctly (I get all NAs). Can someone help me out with this particular recursive implementation?

Upvotes: 2

Views: 53

Answers (1)

eastclintw00d
eastclintw00d

Reputation: 2364

You could solve your initialization problem like this:

df2 <-df1 %>%
  mutate(
    cases_new = 3^(lag(cases, n=1L)),
    cases_new = if_else(date == "2020-01-01", cases_new, 3^(lag(cases_new, n=1L)))
  )

BUT, I dont think that this will give you the values you want. You will have to iterate over the rows like this:

cases_new <- c(3^(lag(cases, n=1L)), rep(0, nrow(df1) - 1))
for (i in 2:nrow(df1)) {
  cases_new[i] <- 3^(lag(cases_new[i - 1], n=1L))
}
df1$cases_new <- cases_new

Upvotes: 1

Related Questions