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.