'Creating a function that generates freq.table

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.



Solution 1:[1]

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AndrewGB
Solution 2 AndrewGB