0

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

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 文件,其中包含每个变量名称的多个工作表。我在这里找到了一个使用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')

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

4

1 回答 1

1

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

所以在你的for循环中,你需要类似的东西:

for (d in names) {
  addWorksheet(wb, sheetName = d)
  writeData(wb, d, df[df$name == d, ]) ## Subsets on the name
}
于 2019-06-06T02:09:00.093 回答