使用循环在 R 中写入 excel 个文件
Using loop to write excel files in R
我有一个要导出到 excel 的数据框列表。导出每个数据帧将非常繁琐且容易出错。有没有办法使用 for 循环或 map 函数来实现这一点?希望也将所有数据帧导出到一个工作簿中。
library(tidyverse)
library(writexl)
df <- tribble(
~var1, ~var2, ~group,
12, 11, "A",
15, 10, "B",
16, 18, "A",
18, 14, "C",
18, 3, "A",
10, 17, "B",
20, 1, "A",
10, 13, "A"
)
nest(df, data = c(var1, var2))
sheet1 <- df %>% filter(group == "A")
sheet2 <- df %>% filter(group == "B")
sheet3 <- df %>% filter(group == "C")
write_xlsx(sheet1, "sheet1.xlsx")
write_xlsx(sheet2, "sheet2.xlsx")
write_xlsx(sheet3, "sheet3.xlsx")
在 write_xlsx
中,“要创建具有(多个)命名工作表的 xlsx,只需将 x 设置为命名的数据框列表。”因此,您可以执行以下操作来实现您的要求:
groups <- distinct(df, group) %>% pull(group)
list_of_dfs <- groups %>%
map(~ df %>% filter(group == .x))
names(list_of_dfs) <- groups
write_xlsx(list_of_dfs, "out.xlsx")
我有一个要导出到 excel 的数据框列表。导出每个数据帧将非常繁琐且容易出错。有没有办法使用 for 循环或 map 函数来实现这一点?希望也将所有数据帧导出到一个工作簿中。
library(tidyverse)
library(writexl)
df <- tribble(
~var1, ~var2, ~group,
12, 11, "A",
15, 10, "B",
16, 18, "A",
18, 14, "C",
18, 3, "A",
10, 17, "B",
20, 1, "A",
10, 13, "A"
)
nest(df, data = c(var1, var2))
sheet1 <- df %>% filter(group == "A")
sheet2 <- df %>% filter(group == "B")
sheet3 <- df %>% filter(group == "C")
write_xlsx(sheet1, "sheet1.xlsx")
write_xlsx(sheet2, "sheet2.xlsx")
write_xlsx(sheet3, "sheet3.xlsx")
在 write_xlsx
中,“要创建具有(多个)命名工作表的 xlsx,只需将 x 设置为命名的数据框列表。”因此,您可以执行以下操作来实现您的要求:
groups <- distinct(df, group) %>% pull(group)
list_of_dfs <- groups %>%
map(~ df %>% filter(group == .x))
names(list_of_dfs) <- groups
write_xlsx(list_of_dfs, "out.xlsx")