【问题标题】:Exporting map%>% janitor::tabyl() into latex将 map%>% janitor::tabyl() 导出到乳胶中
【发布时间】:2021-12-02 17:38:04
【问题描述】:

我最喜欢的获取摘要的方法之一是使用 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()))

【问题讨论】:

    标签: r latex purrr janitor


    【解决方案1】:

    考虑使用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"))) 
        })
    

    -输出

    【讨论】:

      【解决方案2】:

      在对@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"))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多