I'm using R for a project, but I am very new to R and not very familiar with it. I have a single dataset, and I want to split it and display separate summaries using the summarize function. I wrote some code using a for loop, but I understand that for loops are usually avoided in R, due to its functional nature.
Basically, I want to learn how to convert my code into a more functional approach using a map or perhaps a group_split function, or whatever else would work. I've tried a few things and haven't figured it out yet.
I've written an example of what I am trying to do by using a built-in R database:
library(tidyverse)
data(mtcars)
unique_gears <- unique(mtcars$gear)
for (g in unique_gears){
summ <- mtcars %>% filter(gear == g) %>% group_by(gear, cyl) %>%
summarize(min = min(mpg), max = max(mpg), mean=mean(mpg))
print(summ)
}
Using the mtcars database, effectively what that does is print 3 separate summary tables, split out by the number of gears in the car, with each table showing the number of cylinders in the car and the mpg.
I tried to look at ways to do that without using the For loop.
For example, I tried this:
mtcars %>% group_by(gear) %>% group_split() %>% group_by(cyl) %>% summarize(min = min(mpg))
I have the second group_by in there because I want the final summarize output to be grouped by another column (and I am using cyl for this example).
group_splitis alist- akrunmtcars %>% group_by(gear, cyl) %>% summarise(across(mpg, list(Min = min, Max = max, Mean = mean)))- akrun