rpurrrjanitor

How can I set names of variables in janitor::tabyl using purrr map in R


I would like to purrr::map() a set of variables to the tabyl function from the janitor package. Instead of labeling the variables, map() calls everything .

library(palmerpenguins)
suppressPackageStartupMessages(library(dplyr))
library(purrr)
suppressPackageStartupMessages(library(janitor))

palmerpenguins::penguins |> 
  select(where(~is.factor(.x) | is.character(.x))) |> 
  map(~janitor::tabyl(.))  
#> $species
#>          .   n   percent
#>     Adelie 152 0.4418605
#>  Chinstrap  68 0.1976744
#>     Gentoo 124 0.3604651
#> 
#> $island
#>          .   n   percent
#>     Biscoe 168 0.4883721
#>      Dream 124 0.3604651
#>  Torgersen  52 0.1511628
#> 
#> $sex
#>       .   n    percent valid_percent
#>  female 165 0.47965116     0.4954955
#>    male 168 0.48837209     0.5045045
#>    <NA>  11 0.03197674            NA

Created on 2023-06-30 with reprex v2.0.2

I think map() is naming a vector . (but using the real values) as it passes data to tabyl(). Is there a way to tell map() to use the original name? If not, is there an easy way to change the . to be the variable name in produced output?

I read this SO post but I could not get it to behave using map2() or imap().


Solution

  • Here's a way to produce the expected output using imap, hopefully not the best:

    palmerpenguins::penguins |> 
      select(where(~is.factor(.x) | is.character(.x))) |> 
      imap(~ {dat <- janitor::tabyl(.x)
        names(dat)[1] <- .y
        dat})