在 for 循环中使用 write_xlsx 将数据帧导出到多个工作表中
Using write_xlsx in a for loop to export dataframes into multiple sheets
我想导出一些通过 for 循环创建的数据帧。这些应该导出到同一文件中的不同 Excel sheet。导出时,我希望每个 sheet 都有不同的名称。例如,我下面示例中的 sheet 名称应该来自字符向量 carriers
.
我无法使用包 xlsx,因为它在我的 R 上没有 运行。我尝试使用 writexl::write_xlsx
函数,但我无法使其工作。这是一个重现我的问题的简单示例:
library(nycflights13)
library(writexl)
carriers <- c( "UA", "AA", "B6", "DL")
for(i in 1:length(carriers)){
dframe_flt <- flights %>% filter(carrier == carriers[i]) %>% summarize(distance_m = mean(distance))
write_xlsx(dframe, sheet = !! paste(carriers[i]), excel = "flights_data.xlsx", col_names = TRUE)
}
它产生以下错误:
Error in write_xlsx(dframe, sheet = !!paste(carriers[i]), excel = "flights_data.xlsx", :
unused arguments (sheet = !!paste(carriers[i]), excel = "flights_data.xlsx")
如何修复此错误?
您收到错误消息,因为 sheet
和 excel
不是 write_xlsx
中的参数。要将多张工作表写入单个 xlsx,您首先要将它们全部放入命名列表中,然后将该列表提供给 write_xlsx
.
library(nycflights13)
library(writexl)
library(tidyverse)
carriers <- c( "UA", "AA", "B6", "DL")
使用地图创建列表(来自 tidyr):
output <- map(set_names(carriers),function(cr){
dframe_flt <- flights %>%
filter(carrier == cr) %>%
summarize(distance_m = mean(distance))
})
写入 xlsx:
write_xlsx(output, path = "flights_data.xlsx", col_names = TRUE)
subset
、aggregate
、split
并写成:
carriers <- c( "UA", "AA", "B6", "DL")
data <- subset(flights, carrier %in% carriers)
data <- aggregate(distance~carrier, data, mean, na.rm = TRUE)
writexl::write_xlsx(split(data, data$carrier), 'data.xlsx')
我想导出一些通过 for 循环创建的数据帧。这些应该导出到同一文件中的不同 Excel sheet。导出时,我希望每个 sheet 都有不同的名称。例如,我下面示例中的 sheet 名称应该来自字符向量 carriers
.
我无法使用包 xlsx,因为它在我的 R 上没有 运行。我尝试使用 writexl::write_xlsx
函数,但我无法使其工作。这是一个重现我的问题的简单示例:
library(nycflights13)
library(writexl)
carriers <- c( "UA", "AA", "B6", "DL")
for(i in 1:length(carriers)){
dframe_flt <- flights %>% filter(carrier == carriers[i]) %>% summarize(distance_m = mean(distance))
write_xlsx(dframe, sheet = !! paste(carriers[i]), excel = "flights_data.xlsx", col_names = TRUE)
}
它产生以下错误:
Error in write_xlsx(dframe, sheet = !!paste(carriers[i]), excel = "flights_data.xlsx", :
unused arguments (sheet = !!paste(carriers[i]), excel = "flights_data.xlsx")
如何修复此错误?
您收到错误消息,因为 sheet
和 excel
不是 write_xlsx
中的参数。要将多张工作表写入单个 xlsx,您首先要将它们全部放入命名列表中,然后将该列表提供给 write_xlsx
.
library(nycflights13)
library(writexl)
library(tidyverse)
carriers <- c( "UA", "AA", "B6", "DL")
使用地图创建列表(来自 tidyr):
output <- map(set_names(carriers),function(cr){
dframe_flt <- flights %>%
filter(carrier == cr) %>%
summarize(distance_m = mean(distance))
})
写入 xlsx:
write_xlsx(output, path = "flights_data.xlsx", col_names = TRUE)
subset
、aggregate
、split
并写成:
carriers <- c( "UA", "AA", "B6", "DL")
data <- subset(flights, carrier %in% carriers)
data <- aggregate(distance~carrier, data, mean, na.rm = TRUE)
writexl::write_xlsx(split(data, data$carrier), 'data.xlsx')