I have a data frame that looks a bit like this:
example <- tribble(
~PERSON_ID, ~RANGE, ~outcome1, ~outcome2, ~outcome3, ~type,
"1", "PRE", 1, 2, 3, "type1",
"1", "POST", 2, 3, 4, "type1",
"2", "PRE", 3, 4, 5, "type2",
"2", "POST", 5, 6, 7, "type2",
"3", "PRE", 6, 7, 8, "type3",
"3", "POST", 9, 10, 11, "type3",
"4", "PRE", 12, 12, 13, "type1",
"4", "POST", 12, 13, 14, "type1",
"5", "PRE", 13, 14, 15, "type2",
"5", "POST", 15, 16, 17, "type2",
"6", "PRE", 16, 17, 18, "type3",
"6", "POST", 19, 10, 11, "type3"
)
I would like to run the following function over it, such that I get a linear model for each "type" and within each type, a result for each outcome ("outcome1", "outcome2", "outcome3")
model_function <- function(outcome, df) {
fit <- lmer(as.formula(paste0(outcome, "~ RANGE + (1|PERSON_ID)")), data = df)
return(summary(fit))
}
This is what I have tried, but get the following error: "Error: The result of .f should be a data frame."
outcomes <- purrr::set_names(names(example)[c(3,4,5)])
example %>%
dplyr::group_by(type) %>%
group_modify(~model_function(outcome = outcomes, df = .x))
Any help much appreciated... Ideally the end result would be a table that looks like this:
outcome1 | outcome2 | outcome3 | |
---|---|---|---|
type1 | coefficient; pvalue | coefficient; pvalue | coefficient; pvalue |
type2 | coefficient; pvalue | coefficient; pvalue | coefficient; pvalue |
type3 | coefficient; pvalue | coefficient; pvalue | coefficient; pvalue |