I'm trying to apply a function summarizing the linear relationships between an exposure variable (exp
) and several outcome variables (out1
, out2
, etc) within groups. Consider the following toy data, along with a helper function to fit a model between two variables and return the desired output:
library(dplyr)
df <- tibble(group = sample(c("a", "b"), size = 100, replace = T),
exp = rnorm(100),
out1 = rnorm(100, 4, 1),
out2 = rnorm(100, 3, 1))
linear_beta <- function(y, x) {
tidy(lm(y ~ x)) %>%
filter(term == "x") %>%
mutate(return = paste0("Beta = ", round(estimate, 2))) %>%
pull(return)
}
If I use the helper function to summarize the relationship between the exposure and a single outcome for both groups, that works
df %>%
group_by(group) %>%
summarize(out1 = linear_beta(out1, exp))
# # A tibble: 2 x 2
# group out1
# <chr> <chr>
# a Beta = 0.01
# b Beta = 0.11
However, when I try to use summarize_at
and find the relationships for out1
and out2
, I get an error
df %>%
group_by(group) %>%
summarize_at(c("out1", "out2"), linear_beta, .$exp)
Error in summarise_impl(.data, dots) : Evaluation error: variable lengths differ (found for 'x').
As best I can tell, the lengths for the outcome and .$exp
should be identical, though clearly I'm missing something. Any help would be appreciated!
Update:
Seems as though the second argument .$exp
is not having the grouping applied to it - as evidenced by the fact that this works.
df %>%
# group_by(group) %>%
summarize_at(c("out1", "out2"), linear_beta, .$exp)
# # A tibble: 1 x 2
# out1 out2
# <chr> <chr>
# Beta = 0.08 Beta = 0.06
It's not clear to me how to get groupings applied to .$exp
, or if that's even possible....