0

我想导出通过 for 循环创建的一些数据框。这些应导出到同一文件中的不同 Excel 工作表。导出时,我希望每张工作表都有不同的名称。例如,以下示例中的工作表名称应该来自字符向量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")

如何修复此错误?

4

2 回答 2

1

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')
于 2021-05-12T03:39:09.210 回答
1

你得到的错误是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)

于 2021-05-12T03:31:16.267 回答