# Here we fit a regression model inside each slice defined by the
# unique values of the column "cyl". The fitted models are returned
# in a list-column.
mtcars %>%
slice_rows("cyl") %>%
by_slice(partial(lm, mpg ~ disp))
# by_slice() is especially useful in combination with map().
# Mutating and summarising operations can be used indistinctly.
# Mutating operation:
mtcars %>%
slice_rows(c("cyl", "am")) %>%
by_slice(map, ~ .x / sd(.x))
# Summarising operation:
mtcars %>%
slice_rows(c("cyl", "am")) %>%
by_slice(map, mean)
# If you don't need the slicing variables as identifiers, switch
# .labels to FALSE:
mtcars %>%
slice_rows("cyl") %>%
by_slice(partial(lm, mpg ~ disp), .labels = FALSE) %>%
flatten() %>%
map(coef)
Run the code above in your browser using DataLab