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

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?

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

PS. I've duplicated the question to SO on request from janitor's package author, I'll update any answer I get there, in case it happens first.

Maybe like this

library(dplyr,quietly = TRUE,warn.conflicts = FALSE,verbose=FALSE)
library(datasets,quietly = TRUE,warn.conflicts = FALSE,verbose=FALSE)
library(janitor,quietly = TRUE,warn.conflicts = FALSE,verbose=FALSE)
#> Warning: package 'janitor' was built under R version 4.1.2

myfun <- function(x,y) {names(x)[1] <- y ; x}

df1 <- as.data.frame(HairEyeColor)

tabs <- df1 %>% select(!where(is.numeric)) %>% 
  purrr::imap(~tabyl(.x) %>% adorn_pct_formatting() 
                         %>% myfun(.y)
              )
for (i in seq_along(tabs))
   print(knitr::kable(tabs[[i]],format="latex"))
#> 
#> \begin{tabular}{l|r|l}
#> \hline
#> Hair & n & percent\\
#> \hline
#> Black & 8 & 25.0\%\\
#> \hline
#> Brown & 8 & 25.0\%\\
#> \hline
#> Red & 8 & 25.0\%\\
#> \hline
#> Blond & 8 & 25.0\%\\
#> \hline
#> \end{tabular}
#> 
#> \begin{tabular}{l|r|l}
#> \hline
#> Eye & n & percent\\
#> \hline
#> Brown & 8 & 25.0\%\\
#> \hline
#> Blue & 8 & 25.0\%\\
#> \hline
#> Hazel & 8 & 25.0\%\\
#> \hline
#> Green & 8 & 25.0\%\\
#> \hline
#> \end{tabular}
#> 
#> \begin{tabular}{l|r|l}
#> \hline
#> Sex & n & percent\\
#> \hline
#> Male & 16 & 50.0\%\\
#> \hline
#> Female & 16 & 50.0\%\\
#> \hline
#> \end{tabular}
Created on 2021-12-02 by the reprex package (v2.0.1)

Yes, imap was the key! I found a slightly less code-intensive way I thought I should share:

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

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.