如何对齐两个命名的 tibbles 列表并将它们插入 excel 工作表中?

How to align two named lists of tibbles and insert them into excel worksheets?

我想对齐数据框列表以将它们插入到自己的 excel 工作簿中。下面是示例代码。

library(tidyverse)
library(XLConnect)


a <- tibble(x = 1:10, y = 11:20, z = 21:30)
b <- tibble(x = 1:10, y = 11:20, z = 21:30)
c <- tibble(x = 1:10, y = 11:20, z = 21:30)

ldf_abc <- list(a,b,c)
names(ldf_abc) <- c("a", "b", "c")

c <- tibble(n = 1:10, o = 11:20, p = 21:30)
a <- tibble(n = 1:10, o = 11:20, p = 21:30)
b <- tibble(n = 1:10, o = 11:20, p = 21:30)

ldf_cab <- list(c,a,b)
names(ldf_cab) <- c("c", "a", "b")

在这个例子中,我想将 ldf_cabldf_abc 对齐。

之后,我想将 ldf_cabldf_abc 中的值放入它们自己的 excel 文件中。 (例如 a.xls 包含变量 n o p in sheet 1 和变量 x y z in sheet 2. 下面是我的尝试(我没走多远)

my_order <- c("a.xlsx", "b.xlsx", "c.xlsx")
my_wb_l <- lapply(my_order, function(x) loadWorkbook(filename = paste0("~/Desktop/", x), create = TRUE))

从这个块我得到这个错误。

 Error: NoSuchMethodError (Java): org.apache.poi.ss.usermodel.FillPatternType.getCode()S

我将如何解决这个问题。

尝试

library(purrr)
walk(c("a", "b", "c"), function(x) {
  wb <- loadWorkbook(filename = paste0("~/Desktop/", x,".xlsx"), create = TRUE)
  createSheet(wb, "ldf_cab")
  createSheet(wb, "ldf_abc")
  writeWorksheet(wb, ldf_cab[[x]], sheet = 1)
  writeWorksheet(wb, ldf_abc[[x]], sheet = 2)
  saveWorkbook(wb)
})

顺便说一句,如果 XLConnect 给您带来问题,您可以尝试使用 openxlsx。我的运气要好得多。一个解决方案是

library(openxlsx)
walk(c("a", "b", "c"), function(x) {
  temporary_list <- list(
    ldf_cab[[x]],
    ldf_abc[[x]]
  )
  write.xlsx(temporary_list, file = paste0("~/Desktop/",x,".xlsx"))
})