data = df
explicitly uses the entire data frame df
, ignoring any grouping. Use .
to refer to the data that is piped in, which will let do
use the groups. See the example at the bottom of ?do
for reference:
## From ?do
by_cyl <- mtcars %>% group_by(cyl)
models <- by_cyl %>% do(mod = lm(mpg ~ disp, data = .))
Though, versions of dplyr
> 1.0 will prefer using nest_by
(also demonstrated on the ?do
help page):
models <- mtcars %>%
nest_by(cyl) %>%
mutate(mod = list(lm(mpg ~ disp, data = data)))
models %>% summarise(broom::tidy(mod))
CLICK HERE to find out more related problems solutions.