我有一个数据框,我运行了一些分析,我想将结果导出到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.xlsx
,versicolor.xlsx
和virginica.xlsx
;每个都有两张“results1”和“results2”,只包含他们的组内结果。意思是在versicolor Excel文件中没有setosa行。
我试图将results1
和results2
分成数据框列表,以便将lappy
与write.xlsx
一起使用,但我无法使其工作。
r1_list <- dlply(results1, .(Species))
r2_list <- dlply(results2, .(Species))
其他建议?
示例代码
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,])
}