我使用R来分割数据集100多种方式,然后获取拆分数据集并将它们导出到模板中。具体来说,我使用XLConnect和DPLYR包来拆分数据集,并创建一个列表。然后,我想获取列表中的每个项目并将其导出到“模板”(已加载的工作簿)并将其另存为唯一名称。
但是,我不知道如何使用唯一名称保存。在下面给出的示例中,代码将每个项目保存为相同的名称。我需要更改工作簿的标题,以便我可以拥有100X文件。意思是,我想根据“LvL1_Mgr”名称更改工作簿的标题。想法?
Example Below.
library(readxl)
SurveyDataRaw <- read_excel("~/SurveyDataRaw.xlsx")
#distinct leaders
library(dplyr)
Leaders_in_file <- SurveyDataRaw %>%
distinct(Lvl1_Mgr)
#store leader names as list
Leaders_in_file <- as.list(Leaders_in_file)
Sam2 <- SurveyDataRaw %>%
group_by(Lvl1_Mgr, Q_Short) %>%
summarise(Q_Responses = mean(Q_Response, na.rm=TRUE)) %>%
split(.,.$Lvl1_Mgr)
#THis is where I get the problem. All files are being created successfully,
but #the save over each other.
for(i in Sam2){
wb <- loadWorkbook("Test123456.xlsx", create = TRUE)
wb["TestSheetName"] = i
saveWorkbook(wb, Create=TRUE)
}
答案 0 :(得分:0)
也许其中一个对你有用?
一个文件,每个&#34;型号&#34;在工作簿中获取自己的工作表:
library(openxlsx)
wb <- loadWorkbook("Test123456.xlsx", create = TRUE)
for (s in names(Sam2)) {
addWorksheet(wb, s)
writeDataTable(wb, s, Sam2[[s]])
}
saveWorkbook(wb, "Test123456.xlsx", overwrite = TRUE)
或者每个模型的新工作簿?
for (s in names(Sam2)) {
wb <- loadWorkbook("Test123456.xlsx", create = TRUE)
addWorksheet(wb, "SomeName")
writeDataTable(wb, "SomeName", Sam2[[s]])
saveWorkbook(wb, sprintf("Test123456-%s.xlsx", s))
}
修改强>:
潜在XLConnect
版本,基于评论:
library(XLConnect)
for (s in names(Sam2)) {
# if it's an already-created template, no need to 'create'
wb <- loadWorkbook("Test123456.xlsx", create = FALSE)
writeWorksheet(wb, Sam2[[s]], "SomeName")
saveWorkbook(wb)
}
答案 1 :(得分:0)
感谢您的帮助。最终代码如下。
for (s in names(Sam2)) {
wb <- loadWorkbook("test.xlsx", create = FALSE)
writeWorksheet(wb, Sam2[[s]], "test")
saveWorkbook(wb, sprintf("%s.xlsx", s))
}