Home > Enterprise >  Export a grouped dataframe to excel and creating a separate tab for each group (R, dplyr)
Export a grouped dataframe to excel and creating a separate tab for each group (R, dplyr)

Time:12-01

I have a large dataframe in R that I want to export to Excel. To make the understanding easier; I will use the mtcars dataset as an example. The dataframe has a grouping variable (cyl) and I would want the data for each group to be in a different Excel tab. Since my own dataframe has more than 20 groups, I would be happy if I didn't have to manually assign each group to a tab.

This is how far I made it (not very far)

library(dplyr) 
library(writexl)
mtcars %>% group_by(cyl)

Ideally, this could be solved with the package writexl and not xlsx, since I can not install xlsx on my work computer.

The Excel file should then contain 3 tabs labelled "4", "6" and "8". Each tab should contain the data for the respective group.

Many thanks for help on this.

CodePudding user response:

From the write_xlsx helpfile you can read

To create an xlsx with (multiple) named sheets, simply set x to a named list of data frames.

So you can solve your problem by doing the following:

write_xlsx(split(mtcars, mtcars$cyl), "mtcars.xlsx")

The resulting excel file looks like this:

enter image description here

  • Related