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

问题描述 投票:0回答:1

我有一个数据框,我运行了一些分析,我想将结果导出到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;每个都有两张“results1”和“results2”,只包含他们的组内结果。意思是在versicolor Excel文件中没有setosa行。

我试图将results1results2分成数据框列表,以便将lappywrite.xlsx一起使用,但我无法使其工作。

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

其他建议?

r excel
1个回答
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,])
}
© www.soinside.com 2019 - 2024. All rights reserved.