How to use tabyl() with two variables within a function?

Viewed 578

I'm making two tables that include lots of variables, so am looking to write functions that use tabyl() from the janitor package and map over the variables I'm interested in.

The first function works fine:

cars = datasets::mtcars

first_table = function(variable){
  
  tabyl(variable, show_na = FALSE) %>% 
  adorn_pct_formatting(digits = 1) 
  
}

first_table(cars$vs)

enter image description here

The second table is produced in almost the same way, but should produce the cross-tabs of two variables and row percents instead of a table representing a single variable. This code and output represents what I'm trying to do with my function:

cars %>% 
  tabyl(vs, am, show_na = FALSE) %>% 
  adorn_percentages("row") %>% 
  adorn_pct_formatting(digits = 1) %>% 
  adorn_ns()

enter image description here

When I write this as a function, however, it seems like the tabyl() function only wants to recognize the first variable:

second_table = function(variable1, variable2){
  
  tabyl(variable1, variable2, show_na = FALSE) %>% 
  adorn_percentages("row") %>% 
  adorn_pct_formatting(digits = 1) %>% 
  adorn_ns() 
  
}

second_table(cars$vs, cars$am)


enter image description here

I'm not quite sure what the issue is, and am wondering how I can edit this function to give me the 2x2 table with row percents that I was able to produce without a function above.

Any help is greatly appreciated.

1 Answers

Instead of passing column values, pass the unquoted column names and evaluate with curly_curly operator {{}}

second_table <- function(dat, variable1, variable2){
 dat %>% 
  tabyl({{variable1}}, {{variable2}}, show_na = FALSE) %>% 
  adorn_percentages("row") %>% 
  adorn_pct_formatting(digits = 1) %>% 
   adorn_ns() 

 }

-testing

second_table(cars, vs, am)
#  vs        0         1
#  0 66.7% (12) 33.3% (6)
#  1 50.0%  (7) 50.0% (7)

NOTE: It is better to pass dataset name also as an argument

Related