在多个工作表中将数据框列表写入Excel

时间:2016-07-28 19:19:45

标签: r excel

我有一个数据框,我运行了一些分析,我想将结果导出到Excel文件。每组一个工作簿,每个分析结果在一个单独的选项卡上。我更倾向于使用openxlsx进行导出以使java脱离等式。

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))

我想要的导出输出是三个Excel工作簿,setosa.xlsxversicolor.xlsxvirginica.xlsx;每个都有两张纸&#34;结果1&#34;和&#34;结果2&#34;仅包含其组内结果。意思是在versicolor Excel文件中没有setosa行。

我尝试将results1results2拆分为数据框列表,以便将lappywrite.xlsx一起使用,但我无法使其正常工作

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

其他建议?

1 个答案:

答案 0 :(得分:1)

示例代码

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,])
}