Hello. I have a workflow that currently looks as follows:
*extract posterior draws from a model into a tibble that gets a unique name (basically just make a tibble)
*do some wrangling of the tibble w/ dplyr; last step in wrangling is to add a mutate() with a unique identifier ("model_1, model_2, etc) to indicate which model it came from
*bind_rows() of all the tibbles in anticipation of ggplot
*ggplot with facets mapped to the unique identifier.
My question is: in reality the wrangling takes up quite a few lines of code and with many models I"m copying an pasting a lot. I would like to use purrr or an equivalent for loop to turn the wrangling into a function. I cannot figure out how, within the function, to do a mutate with a unique identifier.
Is there a way to use purr to operate on many tibbles and add a unique name with a mutate statement for each one? I'm open to other options for achieving the same endpoint.
Example (this does what I want but has a lot of copy/paste)
library(tidyverse)
# get a tibble of observations from a model
model_b154_posterior_draws_tbl <- tibble(
param_draw = rnorm(15, 1, 1),
model = as_factor("model_b154")) %>%
mutate(adjusted_draws = param_draw * 2)
# another tibble with unique name
model_65kj_posterior_draws_tbl <- tibble(
param_draw = rnorm(15, 5, 2),
model = as_factor("model_65kj")) %>%
mutate(adjusted_draws = param_draw * 2)
#another tibble with unique name
model_4hwe_posterior_draws_tbl <- tibble(
param_draw = rnorm(15, 10, 3),
model = as_factor("model_4hwe")) %>%
mutate(adjusted_draws = param_draw * 2)
#bind together
bind_rows(
model_b154_posterior_draws_tbl,
model_65kj_posterior_draws_tbl,
model_4hwe_posterior_draws_tbl
) %>%
select(-param_draw) %>%
#visualize and facet on model unique identifier
ggplot(aes(x = 0, y = adjusted_draws)) +
geom_point() +
facet_wrap(~model)
Thank you!