英文:
Exporting same named Data Frames from separate lists into their own excel documents
问题
我有五个数据框的列表。我尝试编写一个应用函数或for循环,以从这五个列表中提取具有相似名称的数据框,将它们放入单独的电子表格中,然后将它们导出为Excel文档。
所以我从一个包含5个电子表格的大型Excel文档开始(我将其称为“ORIGINAL_DOCUMENT”)。我使用了split函数根据列值创建了列表:
LIST_DF <- ORIGINAL_DOCUMENT %>%
base::split(., .$COMPANY_NAME)
这是我目前在R中看到的一种可视化示例:
|List 1 | List 2 | | List 3 | List 4 | List 5 |
| -------- | -------- | | -------- | -------- | -------|
| DF 1 | DF 1 | | DF 1 | DF 1 | DF 1 |
| DF 2 | DF 2 | | DF 2 | DF 2 | DF 2 |
我希望输出创建一个Excel文档,其中来自每个列表的DF 1保存为一个电子表格,依此类推。对于每个Excel文档,我希望电子表格的名称相同(Company1,Company2,Company3,Company4和Company5)。
我真的会非常感激任何建议或帮助。谢谢!
英文:
I have five lists of Data frames. I am trying to write an apply function or a for loop that will pull similar named Dataframes from the five lists, put them into separate spreadsheets and then export them as excel documents.
So I started with a large excel document with 5 spreadsheets (I'll call it "ORIGINAL_DOCUMENT". I used a split function to create lists based on column value:
LIST_DF <- ORIGINAL_DOCUMENT%>%
base::split(., .$COMPANY_NAME)
Here's a kind of visual example of what I'm seeing in R right now:
|List 1 | List 2 | | List 3 | List 4 | List 5 |
| -------- | -------- | | -------- | -------- | -------|
| DF 1 | DF 1 | | DF 1 | DF 1 | DF 1 |
| DF 2 | DF 2 | | DF 2 | DF 2 | DF 2 |
I would like the output to create an excel document with DF 1 from each list saved as a spreadsheet and so on. For every excel document, I want the spreasheets named the same (Company1, Company2, Company3, Company 4 and Company 5.)
I could really appreaciate any advice/help out there. Thanks!
答案1
得分: 1
以下是翻译好的代码部分:
# 创建一个数据框列表
df_list <- lapply(1:5, function(x) {
data.frame(COMPANY_NAME = c("A", "B"), values = rnorm(2))
})
# 为列表命名
names(df_list) <- paste0("df", 1:5)
# 遍历每个数据框
for (df_name in df_names) {
# 创建一个新的工作簿
wb <- openxlsx::createWorkbook()
# 为每个列表添加工作表
for (i in seq_along(lists)) {
df <- lists[[i]][[df_name]]
openxlsx::addWorksheet(wb, paste0("Company", i))
openxlsx::writeData(wb, paste0("Company", i), df)
}
# 保存工作簿
openxlsx::saveWorkbook(wb, paste0(df_name, ".xlsx"), overwrite = TRUE)
}
希望这对你有所帮助。
英文:
Here is a possibly way how we could do it:
# create a list of dataframes
df_list <- lapply(1:5, function(x) {
data.frame(COMPANY_NAME = c("A", "B"), values = rnorm(2))
})
# name list
names(df_list) <- paste0("df", 1:5)
# Loop through each data frame
for (df_name in df_names) {
# Create a new workbook
wb <- openxlsx::createWorkbook()
# Add a worksheet for each list
for (i in seq_along(lists)) {
df <- lists[[i]][[df_name]]
openxlsx::addWorksheet(wb, paste0("Company", i))
openxlsx::writeData(wb, paste0("Company", i), df)
}
# Save the workbook
openxlsx::saveWorkbook(wb, paste0(df_name, ".xlsx"), overwrite = TRUE)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论