将 map%>% janitor::tabyl() 导出到乳胶中

Exporting map%>% janitor::tabyl() into latex

我最喜欢的获取摘要的方法之一是使用 janitor::tabyl(),使用 map 可以帮助我获取每个变量(或所有非数字变量,如下例所示)。当我一次做一个变量时(例如 df%>% tabyl(Variable) 然后我可以通过管道输入 gt::gt %>%gtsave("name.tex")。但是当我通过地图制作我的 tabyl 时,我不能。关于进一步转换以使其兼容的任何建议gt 包?

library(gt)
library(janitor)
library(datasets)
gss_cat%>% select(!where(is.numeric)) %>% 
  map(~(tabyl(.) %>% adorn_pct_formatting()))

考虑使用 imap/iwalk,我们可以从中提取列名称 (.y)

library(purrr)
library(stringr)
gss_cat%>% 
   # // select non-numeric columns
   select(!where(is.numeric)) %>% 
    # // loop over the columns 
    imap(~ {
        # // assign the column name to nm1
        nm1 <- .y
        # // get the tabyl
        tabyl(.) %>%
        # // rename the first column to the column name
         rename_with(~ nm1, 1) %>%
        # // get the percentage
         adorn_pct_formatting() %>% 
         # // convert to gt
         gt() %>%
         # // save by creating the .tex file name from nm1
         gtsave(str_c(nm1, ".tex")) 
   })

一个可重现的例子

mtcars %>%  
   select(cyl, hp) %>% 
   imap(~ {nm1 <- .y
      tabyl(.) %>%
      rename_with(~ nm1, 1) %>% 
      adorn_pct_formatting() %>%
      gt() %>% 
      gtsave(file.path(getwd(), 'test', str_c(nm1, ".tex"))) 
    })

-输出

在对@akrun 的回答进行故障排除后,因为我遇到了一些错误:

gss_cat %>%  
   select(!where(is.numeric)) %>% 
   imap(~ {variable <- .y
      tabyl(.) %>% 
      rename_with(~ variable, 1) %>% 
      adorn_pct_formatting(.) %>%
      gt(.) %>% 
      gtsave(str_c(variable, ".tex"))
    })

如果您之前 setwd() 过,则不需要文件路径,如果您按照他们的建议重述它会产生错误。

如果保存到 word,则将 gt 函数替换为 save_as_docx(path = str_c(variable, ".docx"))