ASKurz / Statistical_Rethinking_with_brms_ggplot2_and_the_tidyverse_2_ed

The bookdown version lives here:
https://bookdown.org/content/4857/
Creative Commons Zero v1.0 Universal
125 stars 37 forks source link

Ch 6.3.1 sim_happiness function #41

Closed mitsuoxv closed 2 years ago

mitsuoxv commented 2 years ago

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
}
ASKurz commented 2 years ago

How does it compare with the other versions proposed here?

mitsuoxv commented 2 years ago

Basically same as for loop version. Sorry, I didn't notice those versions.