如何将 lapply 与传递给 2-way tabyl 的列列表一起使用

How to use lapply with a list of columns passing to a 2-way tabyl

我正在尝试使用 lapply() 创建多个交叉表,使用 tabyl() 功能,我非常喜欢并且很舒服。我更喜欢这种格式,这样我就可以继续用它做其他事情。

但是,我只能 lapply() 使用 1-way tabyl() 像这样:

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

这是输出:

[[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

但是,我想用 2-way tabyl() 来做这个,所以基本上显示 tabyl(mtcars, cyl, carb)tabyl(mtcars, gear, carb),所以 carb 作为“by " 变量。

我想要的看起来像这样:

  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

当我尝试这个时:

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

我收到错误:

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

我也一直在尝试各种其他变体,但没有任何效果。

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

我似乎找不到其他类似的问题,也找不到任何使用 tabyl() 的人。任何帮助,将不胜感激!谢谢。

将列名作为字符串变量传递时使用 .data

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