I would like to propose tidyverse version of sim_happiness function as below. Note it is slow.
sim_happiness_tidyverse <- function(seed = 1977, N_years = 1000, max_age = 65, N_births = 20, aom = 18) {
set.seed(seed)
# initial state
d <- tibble(
age = rep(1:max_age, each = N_births),
happiness = rep(seq(-2, 2, length.out = N_births), max_age),
married = 0L
)
# repeat one year later for N_years
for (i in seq_len(N_years)) {
d <- d %>%
# one year later
mutate(
age = age + 1,
married = if_else(age >= aom & married == 0,
rbinom(n(), size = 1,
prob = inv_logit_scaled(happiness - 4)),
married)) %>%
# death and birth
filter(age <= max_age) %>%
bind_rows(
tibble(
age = 1L,
happiness = seq(-2, 2, length.out = N_births),
married = 0L
)
)
}
d
}
I would like to propose tidyverse version of sim_happiness function as below. Note it is slow.