3

I have a data frame that I run a few analyses on and I want to export the results to Excel files. One workbook per group and each analysis results on a separate tab. I would prefer to use openxlsx for the exporting to take java out of the equation.

library(plyr)
library(dplyr)
library(openxlsx)

df <- iris

# Analysis 1
results1 <- df %>%
  group_by(Species) %>%
  summarise(count = n())

# Analysis 2
results2 <- df %>%
  group_by(Species) %>%
  summarise(mean.sl = mean(Sepal.Length),
            mean.sw = mean(Sepal.Width))

My desired export output would be three Excel workbooks, setosa.xlsx, versicolor.xlsx, and virginica.xlsx; each with two sheets "results1" and "results2" containing only their within-group results. Meaning no setosa rows in the versicolor Excel file.

I tried to split results1 and results2 into lists of data frames in order to use lappy with write.xlsx but I'm not able to make it work.

r1_list <- dlply(results1, .(Species))
r2_list <- dlply(results2, .(Species))

Other suggestions?

4
  • 1
    My suggestion, unhelpful as it may be, is to not use Excel. Commented Jul 28, 2016 at 19:56
  • Also, I believe the xlsx package is what you're looking for Commented Jul 28, 2016 at 19:57
  • xlsx depends on java, which I'm trying to avoid, if possible Commented Jul 28, 2016 at 20:13
  • The WriteXLS package worked fine for me. Just pass it a named list of data.frames and those will be tabs in the result. Commented Jul 28, 2016 at 20:27

1 Answer 1

3

Sample code

library(plyr)
library(dplyr)
library(openxlsx)


setwd("c:/r")
df <- iris

# Analysis 1
results1 <- df %>%
  group_by(Species) %>%
  summarise(count = n())

# Analysis 2
results2 <- df %>%
  group_by(Species) %>%
  summarise(mean.sl = mean(Sepal.Length),
            mean.sw = mean(Sepal.Width))

#get the unique species
sp <- unique(df$Species)

createSpreadsheets <- function(species,r1,r2){
  ## Create new workbooks
  wb <- createWorkbook() 

  ## Create the worksheets
  addWorksheet(wb, sheetName = "Results1" )
  addWorksheet(wb, sheetName = "Results2" )

  ## Write the data
  writeData(wb, "Results1", r1)
  writeData(wb, "Results2", r2)

  ## Save workbook to working directory 
  saveWorkbook(wb, file = paste(species,".xlsx", sep=""), overwrite = TRUE)
}

## create spreadsheets by calling our function for each species
for(s in sp){
  createSpreadsheets(s,results1[results1$Species==s,],results2[results2$Species==s,])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.