简体   繁体   English

如何在一个excel中输出多张表格,带多个标签

[英]how to output multiple table in one excel with multiple tabs

I have a 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)
                )

where I want to output each unique group_num to a separate tab in one excel, and I've tried below:我想将每个唯一的 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 )
)

But I got error:但是我得到了错误:

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)

If I try group_num == x , the ouput excel will just have the last group_num.如果我尝试group_num == x ,输出 excel 将只有最后一个 group_num。

And what should I do if I want to add more tables on that map function?如果我想在那个地图功能上添加更多的表,我该怎么办?

You could do this by arranging the data groups into a named list...您可以通过将数据组排列到命名列表中来做到这一点...

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"))

data数据

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)
)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM