将不同的数据帧导出到相同的 Excel sheet

Export different dataframes to the same Excel sheet

我正在使用 openxlsx 包将数据帧从 R 导出到 excel。

如何导出多个数据帧:

a <- data.frame("y"=c(2009,2010,2011,2012),"b"=c(3,4,5,6))
b <- data.frame("y"=c(2009,2010,2011,2012),"b"=c(12,2,7,8))
c <- data.frame("y"=c(2009,2010,2011,2012),"b"=c(5,9,1,6))

在同一个excelsheet上,每一个和前一个用空行隔开,并为每个添加一个列名?

也许你可以试试下面的方法

df <- do.call(rbind,lapply(list(a,b,c),function(x) rbind(x,"")))
write.xlsx(df,"xxx.xlsx")

其中 df 看起来像

> df
      y  b
1  2009  3
2  2010  4
3  2011  5
4  2012  6
5
6  2009 12
7  2010  2
8  2011  7
9  2012  8
10
11 2009  5
12 2010  9
13 2011  1
14 2012  6
15

如果你想垂直堆叠这些数据框,这是另一个版本(类似于 的版本)

wb <- createWorkbook()
addWorksheet(wb, "Sheet1")
lst <- list(a,b,c)
startRows <- cumsum(c(1,(sapply(lst,nrow)+2)[-length(lst)]))
for (k in seq_along(lst)) {
  writeData(wb = wb, sheet = "Sheet1", startCol = 1, startRow = startRows[k], x = lst[[k]])
}
saveWorkbook(wb, "xxxx.xlsx", overwrite = TRUE)

我们可以使用 writeDatastartRow 参数一起玩,这里有一个例子:

# create workbook
wb <- createWorkbook()
addWorksheet(wb, "Sheet1")

# add dataframes a,b,c starting on different rows
writeData(wb = wb, sheet = "Sheet1", startCol = 1,
               startRow = 1, x = a)
writeData(wb = wb, sheet = "Sheet1", startCol = 1,
               startRow = 1 + nrow(a) + 2, x = b)
writeData(wb = wb, sheet = "Sheet1", startCol = 1,
               startRow = 1 + nrow(a) + 2 + nrow(b) + 2, x = c)

# outout to a file
saveWorkbook(wb, "myFile.xlsx", overwrite = TRUE)