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

时间:2018-04-11 20:43:17

标签: r excel sorting xlconnect

我想对齐数据框列表,将它们插入到自己的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在表单1中包含变量n o p,在表单2中包含变量x y z。是我的尝试(我不是很远)

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

我将如何解决这个问题。

1 个答案:

答案 0 :(得分:3)

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