Reputation: 798
I'm trying to create a wrapper for xtabs
with a custom function.
I tried doing this:
xtabs_fun <- function(data, variable) {
xtabs(~ variable, data = data)
}
But using it doesn't return the correct value.
xtabs_fun(mtcars, "cyl")
cyl
1
The expected output should be this:
xtabs(~ cyl, data = mtcars)
cyl
4 6 8
11 7 14
Upvotes: 3
Views: 229
Reputation: 269556
xtabs
accepts a data frame so:
xtabs_fun <- function(data, variable) xtabs(data[variable])
# test
xtabs_fun(mtcars, "cyl")
## cyl
## 4 6 8
## 11 7 14
Alternately use table
which works the same:
table_fun <- function(data, variable) table(data[variable])
Upvotes: 3
Reputation: 887098
We could use reformulate
xtabs_fun <- function(data, variable) {
xtabs(reformulate(variable), data = data)
}
-testing
> xtabs_fun(mtcars, "cyl")
cyl
4 6 8
11 7 14
Upvotes: 3
Reputation: 173803
Variable names inside formulas are always taken literally rather than being substituted, so inside your function, xtabs
is looking for a column called variable
inside mtcars
, which doesn't exist. Instead, you can build the formula as a string:
xtabs_fun <- function(data, variable) {
xtabs(as.formula(paste("~", variable)), data = data)
}
xtabs_fun(mtcars, "cyl")
#> cyl
#> 4 6 8
#> 11 7 14
If you prefer your function to take unquoted variable names in a tidyverse style, you can do
xtabs_fun <- function(data, variable) {
xtabs(as.formula(paste("~", deparse(substitute(variable)))), data = data)
}
mtcars |> xtabs_fun(cyl)
#> cyl
#> 4 6 8
#> 11 7 14
Created on 2022-09-24 with reprex v2.0.2
Upvotes: 2