1 | initial version |
We can create summary tables by using nested tibbles in R by following these steps:
group_by()
function.nest()
function, which creates a new column with a tibble of the data for each group.map()
or purrr::map()
functions, which calculates summaries for each group and returns a tibble of summary statistics.unnest()
function to flatten it and combine the summary statistics back into a single tibble.Here's an example:
library(tidyverse) # create a tibble with data data <- tribble( ~year, ~month, ~sales, 2020, "Jan", 100, 2020, "Feb", 200, 2020, "Mar", 300, 2021, "Jan", 400, 2021, "Feb", 500, 2021, "Mar", 600 ) # group by year and create a nested tibble nested_data <- data %>% group_by(year) %>% nest() # apply a summary function to calculate mean sales for each year summary_table <- nested_data %>% mutate(mean_sales = map(data, ~mean(.x$sales))) %>% select(year, mean_sales) %>% unnest() # print summary table summary_table
This code creates a summary table of mean sales for each year, which is calculated by nesting the data by year, using the map()
function to calculate mean sales for each group, and unnesting the resulting summary tibble.