2016-07-28 22 views
0

私はいくつかの分析を実行するデータフレームを持っており、その結果をExcelファイルにエクスポートしたい。グループごとに1つのワークブックと各分析結果が別のタブに表示されます。私はopenxlsxを使って方程式からjavaを取り除くことを好むでしょう。データフレームのリストを複数のシートにExcelに書き込む

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

私の希望輸出出力は3つのExcelブック、setosa.xlsxversicolor.xlsx、およびvirginica.xlsxだろう。それぞれに2つのシート "results1"と "results2"があり、グループ内の結果のみが含まれています。 versicolor Excelファイルのsetosa行がないことを意味します。

私はwrite.xlsxlappyを使用するために、データフレームのリストにresults1results2を分割しようとしたが、私はそれを動作させることができませんよ。

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

その他の提案ですか?

+1

私の提案、それによっては役に立たない、Excelを使用しないことです。 –

+0

また、私は[xlsx'パッケージ](https://cran.r-project.org/web/packages/xlsx/xlsx.pdf)があなたが探しているものだと信じています –

+0

'xlsx'はJavaに依存していますが、可能であれば私は避けようとしています –

答えて

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,]) 
} 
関連する問題