在 R 中的单个 Excel 文件中将数据框导出为多个工作表

Export a data frame as multiple worksheets in a single Excel file in R

我有一个像这样的虚拟数据的数据框:

df <- data.frame(
  stringsAsFactors = FALSE,
  id = c(
    "100-1",
    "100-1",
    "100-2",
    "100-2",
    "100-5",
    "100-5",
    "100-5",
    "100-9",
    "100-9",
    "100-9"
  ),
  name = c(
    "Aggi",
    "Aggi",
    "Nina",
    "Nina",
    "Katrin",
    "Katrin",
    "Katrin",
    "Tom",
    "Tom",
    "Tom"
  ),
  date = c(
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019",
    "5/15/2019"
  ),
  start_time = c(
    "11:32:00",
    "11:37:30",
    "12:04:00",
    "12:08:00",
    "13:53:00",
    "13:55:00",
    "17:28:00",
    "17:29:00",
    "17:31:00",
    "17:34:45"
  ),
  end_time = c(
    "11:37:30",
    "12:04:00",
    "12:08:00",
    "13:53:00",
    "13:55:00",
    "17:28:00",
    "17:29:00",
    "17:31:00",
    "17:34:45",
    "17:38:45"
  )
)

经过一系列数据整理后,我想将数据导出到单个 Excel 文件,该文件包含每个变量名称的多个工作 sheet。我用 openxlsx 库找到了解决方法

# export one .xlsx file with sheet for each name:

    library(tidyverse)
    library(lubridate)
    library(openxlsx)

# make a list of names
        names <-
          as.list(
            df$name) %>%
          as.character() %>% 
          unique()

 # create wordbook       
        wb <- createWorkbook()

        for (d in names) {
           addWorksheet(wb, sheetName = d)
          writeData(wb, d, df)
        }

        saveWorkbook(wb, 'data.xlsx')

我的脚本正在运行,将导出包含多个作品sheet 的单个文件,但每个作品sheet 包含所有数据而不是数据子组。我想要一个 sheet 用于属于 Aggi 的数据(工作 sheet 名称 = Aggi)等等。我错过了什么?显然我的for语句有问题。

在您的 writeData 函数中,您需要对每个相应工作表的数据进行子集化。

所以在你的 for 循环中,你需要这样的东西:

for (d in names) {
  addWorksheet(wb, sheetName = d)
  writeData(wb, d, df[df$name == d, ]) ## Subsets on the name
}