I have the following dataset:
I want to calculate impute the NA in the n_j column in the second row with the formula n_j - (d_j+c_j).
To create the data:
df = structure(list(time_intervals = structure(1:8, levels = c("[0,12)",
"[12,24)", "[24,36)", "[36,48)", "[48,60)", "[60,72)", "[72,84)",
"[84,96]"), class = "factor"), d_j = c(16L, 10L, 1L, 3L, 2L,
2L, 0L, 2L), c_j = c(4L, 4L, 0L, 1L, 2L, 0L, 1L, 0L), n_j = c(48L,
NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))
I managed to do this with a for loop:
for (i in 1:nrow(df)) {
df <- df |>
mutate(
n_j =
ifelse(is.na(n_j), lag(n_j)- (lag(d_j)+lag(c_j)), n_j)
)
}
Is there a way to do this using purrr::map or other Tidyverse functions?