Search code examples
rdplyrdynamic-programmingpanel-data

Dynamic calculations with panel data in R


I have a panel data (individuals observed in different time periods) like df, with much more individuals in my dataset:

id <- c("1", "1", "1", "2", "2", "2")
t <- c("1", "2", "3", "1", "2", "3")
w <- c("0.17", "NA", "NA", "0.23", "NA", "NA")
alpha <- c("0.15", "0.15", "0.15", "0.15", "0.15", "0.15")
rho <- c("0.10", "0.21", "0.32", "0.12", "0.2", "0.08")

df <- data.frame(id, t, w, alpha, rho)


I would like to fill w following these mathematical dynamics: w_id_t = w_id_t-1 * alpha + rho_id_t. However, I do not know how to move the outcome in such a way that appears in the following line, so I can continue with the dynamic calculations. The outcome should look like df_dynamics:

w_new <- c("0.17", "0.2355", "0.345", "0.23", "0.2345", "0.115")
df_dynamics <- data.frame(id, t, w_new, alpha, rho)

Any clue?


Solution

  • The columns are all character class. We may need to convert to numeric first and then do a group by operation

    library(dplyr)
    type.convert(df, as.is = TRUE) %>%
        group_by(id) %>%
        mutate(w = coalesce(w, lag(first(w) * first(alpha) + lead(rho)))) %>% 
       ungroup
    # A tibble: 6 × 5
         id     t     w alpha   rho
      <int> <int> <dbl> <dbl> <dbl>
    1     1     1 0.17   0.15  0.1 
    2     1     2 0.236  0.15  0.21
    3     1     3 0.346  0.15  0.32
    4     2     1 0.23   0.15  0.12
    5     2     2 0.234  0.15  0.2 
    6     2     3 0.114  0.15  0.08