Consider this code:
iris %>% count(Species) %>% group_by(Species)
# A tibble: 3 x 2
# Groups: Species [3]
Species n
<fct> <int>
1 setosa 50
2 versicolor 50
3 virginica 50
I want to define a function which does the same task, something like this :
table_freq <- function(Table, Var) {
freq <- NA
freq <- Table %>%
dplyr::count(Var) %>%
group_by(Var)
return(freq)
}
table_freq(iris, "Species")
But it does not work :
> table_freq(iris, "Species")
Error in `group_by_prepare()`:
! Must group by variables found in `.data`.
* Column `Var` is not found.
Any ideas?
Please do not write alternate solutions, I need to define a function that takes the table and the column name for which we need the freq. table.
CodePudding user response:
You can use table
to create a function that will take the table and the column name.
table_freq <- function(Table, Var) {
setNames(data.frame(table(Table[,Var])), c(Var, "n"))
}
table_freq(iris, "Species")
Output
Species n
1 setosa 50
2 versicolor 50
3 virginica 50
CodePudding user response:
The secret sauce is {{}}
, we simply write :
table_freq <- function(Table, Var) {
freq <- NA
freq <- Table %>%
dplyr::count({{Var}}) %>%
group_by({{Var}})
return(freq)
}
table_freq(iris, Species)