R语言 如何在一个带有多个选项卡Excel中输出多个表格

sr4lhrrt  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个 Dataframe :

df <- data.frame(subgroup= c(1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3),
                 group_num=(2,2,5,5,10,21,18,17,16,22,20,25,21,30,29,20),
                 state= c(NJ,NJ,NJ,VT,VT,VT,VT,DC,DC,DC,DC,IL,IL,IL,IL),
                 date= c(2010-01-01,2010-01-01,2010-01-01,2010-01-01,2010-01-02,2010-01-02,2010-01-02,2010-01-02,2010-02-03,2010-02-03,2010-02-03,2010-02-03,2010-03-05,2010-03-05,2010-03-05,2010-03-05),
                 value = c(12,7,6,9,15,7,6,9,18,5,6,3,20,5,5,6)
                )

在这里,我想将每个唯一的group_num输出到一个excel中的一个单独的选项卡,我尝试了以下操作:

map(unique(df$group_num),function(x) 
  write.xlsx(df%>% 
              filter(group_num == !!sym(x)) ,
              file.path(test ,"TEST.xlsx"),
              sheetName=x )
)

但我得到了错误:

Error in `.fun()`:
! Problem while computing `..1 = group_num== `2``.
Caused by error in `mask$eval_all_filter()`:
! object '2' not found
Backtrace:
  1. purrr::map(...)
  6. tidylog::filter(., metric_num == !!sym(x))
  7. tidylog:::log_filter(...)
  9. dplyr:::filter.data.frame(.data, ...)
 10. dplyr:::filter_rows(.data, ..., caller_env = caller_env())
 11. dplyr:::filter_eval(dots, mask = mask, error_call = error_call)
 13. mask$eval_all_filter(dots, env_filter)

如果我尝试group_num == x,输出excel将只有最后一个group_num。
如果我想在map函数上添加更多的表,我应该怎么做?

tnkciper

tnkciper1#

您可以通过将数据组排列到一个命名列表中来完成此操作...

library(purrr)
library(dplyr)
library(openxlsx)

ls1 <- map(unique(df1$group_num), ~filter(df1, group_num == .))

names(ls1) <- unique(df1$group_num)

#this assumes that directory `test` exists

write.xlsx(ls1, file.path("test/TEST.xlsx"))

资料

df1 <- data.frame(subgroup= c(1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3),
                 group_num=c(2,2,5,5,10,21,18,17,16,22,20,25,21,30,29,20),
                 state = rep(c("NJ", "VT", "DC", "IL"), each = 4),
                 date= c(2010-01-01,2010-01-01,2010-01-01,2010-01-01,2010-01-02,2010-01-02,2010-01-02,2010-01-02,2010-02-03,2010-02-03,2010-02-03,2010-02-03,2010-03-05,2010-03-05,2010-03-05,2010-03-05),
                 value = c(12,7,6,9,15,7,6,9,18,5,6,3,20,5,5,6)
)

相关问题