excel 如何在R中插入具有不同数量的数据框和图的数据框和图?

kmbjn2e3  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(112)

我有两个 Dataframe df1和df2.Also我有5个不同的图表,我想插入他们在不同的工作表在excel文件。
与此类似,我有

data_list = list(DF1,DF2)
graph_list = list(G1,G2,G3,G4,G5)

BOOK  = createWorkbook()

export_xl = function(i) {
  data_sheet  =  paste("Data_Frame", i)
  plot_sheet  =  paste("Graph", i)
  addWorksheet(BOOK, data_sheet)
  addWorksheet(BOOK, plot_sheet)
  
  writeData(BOOK, data_sheet, data_list[[i]])
  print(graph_list[[i]])
  insertPlot(BOOK, plot_sheet,width = 5,height = 5)
}

for (i in seq(length(graph_list))) {
  export_xl(i)
}

saveWorkbook(BOOK,path.xlsx,overwrite=TRUE)

但它只导出两个 Dataframe 和前两个图形?
我如何纠正这一点,以expresrt所有的dfs和ad图形在不同的工作表在excel?

lskq00tm

lskq00tm1#

将导出函数一分为二,一个用于数据,一个用于图。然后使用两个for循环:

library(openxlsx)
library(ggplot2)

p <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point()

data_list <- list(mtcars, iris)
graph_list <- list(p, p, p, p, p)

BOOK <- createWorkbook()

export_data <- function(i) {
  data_sheet <- paste("Data_Frame", i)
  addWorksheet(BOOK, data_sheet)
  writeData(BOOK, data_sheet, data_list[[i]])
}

export_plot <- function(i) {
  plot_sheet <- paste("Graph", i)
  addWorksheet(BOOK, plot_sheet)
  print(graph_list[[i]])
  insertPlot(BOOK, plot_sheet, width = 5, height = 5)
}

for (i in seq_along(data_list)) {
  export_data(i)
}

for (i in seq_along(graph_list)) {
  export_plot(i)
}

saveWorkbook(BOOK, "plot.xlsx", overwrite = TRUE)

相关问题