Export a grouped dataframe to excel and creating a separate tab for each group (R, dplyr)
Asked Answered
T

1

5

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.

Truax answered 30/11, 2022 at 13:23 Comment(0)
H
8

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

Helle answered 30/11, 2022 at 14:7 Comment(1)
Nice! I was just looking for arguments and didn't read the description. Gonna delete my answer.Karlie

© 2022 - 2024 — McMap. All rights reserved.