3

I'm trying to use lapply() to create multiple crosstabs, using the tabyl() function which I really like and am comfortable with. I prefer it in this format so that I can go on to do other things with it.

However, I can only get lapply() to work with a 1-way tabyl() like such:

list_cars <- c("cyl", "gear")
lapply(list_cars, function(w) tabyl(mtcars, w))

And this is the output:

[[1]]
 cyl  n percent
   4 11 0.34375
   6  7 0.21875
   8 14 0.43750

[[2]]
 gear  n percent
    3 15 0.46875
    4 12 0.37500
    5  5 0.15625

However, I want to do this but with a 2-way tabyl(), so essentially showing tabyl(mtcars, cyl, carb) and tabyl(mtcars, gear, carb), so with carb as the "by" variable.

What I want would look something like this:

  cyl 1 2 3 4 6 8
    4 5 6 0 0 0 0
    6 2 0 0 4 1 0
    8 0 4 3 6 0 1

 gear 1 2 3 4 6 8
    3 3 4 3 5 0 0
    4 4 4 0 4 0 0
    5 0 2 0 1 1 1

When I try this:

lapply(list_cars, function(w) tabyl(mtcars, w, carb))

I get the error:

Error: Must group by variables found in `.data`.
* Column `w` is not found.

I've also been trying all sorts of other variations, but not gotten anything to work.

lapply(list_cars, function(w, disp) tabyl(mtcars, w, carb)) ## Nope
lapply(list_cars, function(x, disp) tabyl(mtcars, {{x}}, {{carb}})) ## Very wrong
lapply(list_cars, function(v) paste0("tabyl(mtcars, ", v, ", disp)") %>% as.formula())  ## Also seems very wrong

I can't seem to find other similar issues, or with anyone using tabyl() out there. Any help would be appreciated! Thanks.

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
A. Piong
  • 192
  • 1
  • 11

1 Answers1

3

Use .data when you pass column names as string variable.

library(janitor)

list_cars <- c("cyl", "gear")
lapply(list_cars, function(w) tabyl(mtcars, .data[[w]], carb))

#[[1]]
# cyl 1 2 3 4 6 8
#   4 5 6 0 0 0 0
#   6 2 0 0 4 1 0
#   8 0 4 3 6 0 1

#[[2]]
# gear 1 2 3 4 6 8
#    3 3 4 3 5 0 0
#    4 4 4 0 4 0 0
#    5 0 2 0 1 1 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks!! This is exactly what I was looking for. Do you know why it is ok to not use .data[[w]] when it's just a one-way tabyl? – A. Piong Apr 06 '21 at 04:44
  • 1
    I am actually surprised by it myself. It is ok to use `tabyl(mtcars, "cyl")` but not `tabyl(mtcars, "cyl", "gear")`. I couldn't find anything relevant in the documentation. – Ronak Shah Apr 06 '21 at 04:46
  • That's at least comforting to know that I'm not going crazy or missing something obvious! – A. Piong Apr 06 '21 at 06:31