我有一个像这样的虚拟数据的数据框:
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 库的一种解决方法here。
# 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语句有问题。
答案 0 :(得分:1)
在您的writeData
函数中,您需要为每个对应的工作表的数据子集。
因此,在您的for
循环中,您需要以下内容:
for (d in names) {
addWorksheet(wb, sheetName = d)
writeData(wb, d, df[df$name == d, ]) ## Subsets on the name
}