A typical way to use group_by and then nest is to estimate a series of models--
library(tidyverse)
mpg %>%
group_by(
manufacturer
) %>%
nest %>%
mutate(
mods = data %>%
map(
\(i)
lm(cty ~ displ, data = i)
)
)
returns
# A tibble: 15 x 3
# Groups: manufacturer [15]
manufacturer data mods
<chr> <list> <list>
1 audi <tibble [18 x 10]> <lm>
2 chevrolet <tibble [19 x 10]> <lm>
3 dodge <tibble [37 x 10]> <lm>
4 ford <tibble [25 x 10]> <lm>
but trying to be concise by using nest_by results in an error:
mpg %>%
nest_by(
manufacturer
) %>%
mutate(
mods = data %>%
map(
\(i)
lm(cty ~ displ, data = i)
)
)
the error:
Error: Problem with `mutate()` column `mods`.
i `mods = data %>% map(function(i) lm(cty ~ displ, data = i))`.
x 'data' must be a data.frame, environment, or list
i The error occurred in row 1.
how can I use nest_by to replicate the sequential use of group_by and nest?