使用 write_xlsx 保存列表的每个 data.frame
Saving each data.frame of list with write_xlsx
想要将列表的每个 data.frame
单独保存为具有 write_xlsx
功能的 Excel Workbook
。能够将列表的每个 data.frame
分别保存为 .RData
但不能保存为 Excel Workbook
。有什么想法。
library(tidyverse)
library(writexl)
df1 <- data.frame(X = 1:3)
df2 <- data.frame(X = 5:6)
ls1 <-
list(df1, df2) %>%
set_names(c("df1", "df2"))
ls1
#> $df1
#> X
#> 1 1
#> 2 2
#> 3 3
#>
#> $df2
#> X
#> 1 5
#> 2 6
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
save(list = x1, file = paste0(x1, ".RData"))
})
#> [[1]]
#> NULL
#>
#> [[2]]
#> NULL
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
write_xlsx(x = x1, path = paste0(x1, ".xlsx"))
})
#> Error in write_xlsx(x = x1, path = paste0(x1, ".xlsx")): Argument x must be a data frame or list of data frames
已编辑
使用 openxlsx
R
包中的 write.xlsx
函数的以下 R
代码可以工作并生成具有多个工作表的单个 Workbook
。
write.xlsx(x = ls1, file = "ls1.xlsx")
但是,我要求将每个 data.frame 保存在单独的 Workbook
中,并尝试了 openxlsx
R
包中的 write.xlsx
函数,但它产生了错误的输出:
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
write.xlsx(x = x1, path = paste0(x1, ".xlsx"))
})
做:
library(openxlsx)
lapply(1:length(ls1), function(x) write.xlsx(ls1[[x]], file = paste0(names(ls1)[x], '.xlsx')))
相同的代码与 map
完全相同:
library(purrr)
map(.x = 1:length(ls1),
.f = function(x) write.xlsx(ls1[[x]], file = paste0(names(ls1)[x], '.xlsx')))
想要将列表的每个 data.frame
单独保存为具有 write_xlsx
功能的 Excel Workbook
。能够将列表的每个 data.frame
分别保存为 .RData
但不能保存为 Excel Workbook
。有什么想法。
library(tidyverse)
library(writexl)
df1 <- data.frame(X = 1:3)
df2 <- data.frame(X = 5:6)
ls1 <-
list(df1, df2) %>%
set_names(c("df1", "df2"))
ls1
#> $df1
#> X
#> 1 1
#> 2 2
#> 3 3
#>
#> $df2
#> X
#> 1 5
#> 2 6
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
save(list = x1, file = paste0(x1, ".RData"))
})
#> [[1]]
#> NULL
#>
#> [[2]]
#> NULL
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
write_xlsx(x = x1, path = paste0(x1, ".xlsx"))
})
#> Error in write_xlsx(x = x1, path = paste0(x1, ".xlsx")): Argument x must be a data frame or list of data frames
已编辑
使用 openxlsx
R
包中的 write.xlsx
函数的以下 R
代码可以工作并生成具有多个工作表的单个 Workbook
。
write.xlsx(x = ls1, file = "ls1.xlsx")
但是,我要求将每个 data.frame 保存在单独的 Workbook
中,并尝试了 openxlsx
R
包中的 write.xlsx
函数,但它产生了错误的输出:
map(.x = names(ls1), .f = function(x1){
assign(x = x1, ls1[[x1]])
write.xlsx(x = x1, path = paste0(x1, ".xlsx"))
})
做:
library(openxlsx)
lapply(1:length(ls1), function(x) write.xlsx(ls1[[x]], file = paste0(names(ls1)[x], '.xlsx')))
相同的代码与 map
完全相同:
library(purrr)
map(.x = 1:length(ls1),
.f = function(x) write.xlsx(ls1[[x]], file = paste0(names(ls1)[x], '.xlsx')))