2016-05-19 78 views
0

我目前使用openxlsx將多個數據框寫入1個工作表,每個工作表之間有一個很好的開放列。我想將這些數據框寫入到這張表中,因爲我希望將它們全部放在一張紙上進行分析,而不必通過10張紙進行分析。寫入xlsx時寫入列開始更新函數的更好方法

我的玩具數據集如下所示:

> random_dat 
    Letters Count Letters.1 Count.1 Letters.2 Count.2 Final 
1  A  1  A1 0.21477659   Z  10 Z10 
2  A  2  A2 0.92217670   X  12 X12 
3  A  3  A3 0.49196523   T  14 T14 
4  B  1  B1 0.08086314   Y  16 Y16 
5  B  2  B2 0.80177983   Z  18 Z18 
6  A  4  A4 0.35970442   X  20 X20 
7  B  3  B3 0.21102868   T  22 T22 
8  C  1  C1 0.75816713   Y  24 Y24 
9  C  2  C2 0.59261425   Z  26 Z26 
10  D  1  D1 0.73484393   X  28 X28 
11  A  5  A5 0.32830008   T  30 T30 
12  C  3  C3 0.21672748   Y  32 Y32 

現在我創造我簿和工作表,並創建3種不同的data.frames將被寫入到我xlsx文件。

library(openxlsx) 
wb <- createWorkbook() 
addWorksheet(wb,sheetName = "Output") 
df1 <- random_dat[,1:2] 
df2 <- random_dat[,2:3] 
df3 <- random_dat[,3:7] 

我現在已經準備好開始寫這些給我的文件:

writeData(wb, sheet = "Output", df1, startCol = 1, startRow = 1, xy = NULL, 
      colNames = TRUE, rowNames = FALSE, headerStyle = NULL, withFilter = FALSE, 
      keepNA = FALSE) 
start_col <- 1 
start_col <- start_col+dim(df1)[2]+1 

writeData(wb, sheet = "Output", df2, startCol = start_col, startRow = 1, xy = NULL, 
      colNames = TRUE, rowNames = FALSE, headerStyle = NULL, withFilter = FALSE, 
      keepNA = FALSE) 

start_col <- start_col+dim(df1)[2]+1 

writeData(wb, sheet = "Output", df1, startCol = start_col, startRow = 1, xy = NULL, 
      colNames = TRUE, rowNames = FALSE, headerStyle = NULL, withFilter = FALSE, 
      keepNA = FALSE) 

start_col <- start_col+dim(df1)[2]+1 

saveWorkbook(wb, "output.xlsx") 

正如你所看到的,之後每次寫,我用數據dim()更新開始列,添加1作爲請在data.frames之間留出空欄。

心不是有更簡單的方法來創建一個全球性的功能,可以只得到最後的書面data.frame作爲輸入,例如更新列計數器變量我在一個簡單的方法:

update_col<-function(df,envir = .GlobalEnv) 
{ 
    if(!("start_col" %in% ls())) start_col<<-1 
    start_col<<-start_col + dim(df)[2] 
} 

update_col(df1) 

回答

1

東西未經測試,使用你的建議globalEnv變量:

mywriteData <- function(wb, sheet="output",df, first=TRUE,...){ 
    if first { 
    previous_Ncol <<- 0 
    start_col <<- 1 
    } 
    start_col <<- start_col+previous_Ncol 
    writeData(wb, sheet = "Output", df, startCol = start_col, ...) 
previous_Ncol <<- previous_Ncol + ncol(df) 
} 

現在更好的東西:創建數據集的列表,並創建一個基於同一個循環就行了同等功能,在循環incremeting計數器 - 這避免使用全球ENV(exerice)

甚至更​​好,有data.frame的列表,並使用do.call("cbind",dataframe_list)(假定它們都具有相同的行數...的)

+0

謝謝,這正是我想要的,因爲我現在的儲蓄我的數據幀到一個列表對象,我現在可以將這個功能應用於其中 –