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

Time:12-03

One of my favorite ways to get summaries is to use janitor::tabyl(), and using map helps me get every variable (or all non-numeric like the following example). When I do one variable at a time (e.g. df%>% tabyl(Variable) I can then pipe into gt::gt %>%gtsave("name.tex"). But when I make my tabyl through map, I can't. Any suggestions about further transformations to make it compatible with the gt package?

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

CodePudding user response:

Consider using imap/iwalk, from which we can extract the column name (.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")) 
   })

A reproducible example with

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

-output

enter image description here

CodePudding user response:

After troubleshooting @akrun's answer because I was getting some errors:

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

filepath is not needed if you've setwd() sometime before and if you have then restating it with their suggestion creates an error.

If saving to word replace both gt functions for save_as_docx(path = str_c(variable, ".docx"))

  • Related