rfor-looplapplyfrequency-table

Using a loop or lapply on the freq_table() function in R


I'm trying to create a series of frequency tables for several categorial variables using the freq_table() function. I've seen plenty of posts about this using similar table functions but can't get them to work with freq_table(), which I'm specifically interested in because it automatically generates confidence intervals.

This is the long version of what I'm trying to accomplish:

data(mtcars)
freq_table_am <- freq_table(mtcars, am, percent_ci = 95, ci_type = "logit", drop = FALSE)
freq_table_gear <- freq_table(mtcars, gear, percent_ci = 95, ci_type = "logit", drop = FALSE)
freq_tables <- rbind(freq_table_am, freq_table_gear)
freq_tables

I've tried using both lapply and for loops to accomplish this, with no luck so far. As an example of my attempt with the for loop:

vars<- c('am', 'gear')

#Attempt 1 with a for loop - produces an error message about "[" being an unexpected symbol
for(i in vars) {
      freq_table(community_survey, [i], percent_ci = 95, ci_type = "logit", drop = FALSE) 
    }

#Attempt 2 with a for loop - produces an error message about column "i" not being found
for(i in vars) {
      freq_table(community_survey, i, percent_ci = 95, ci_type = "logit", drop = FALSE) 
    }

Is there a way to do what I'm hoping to do, using either lapply, for loops, or another method? Or is there an alternative function I can use that will work better than freq_table() but still produce the confidence intervals I'm looking for?

Thank you!


Solution

  • It does not work because the function freqtables::freq_table calls the dplyr function count under the hood, and this uses tidy evaluation to select grouping variables (in this case "gear" and "am").

    Solution is mentioned on this page:

    If you have the column name as a character vector, use the .data pronoun, e.g. summarise(df, mean = mean(.data[[var]])).

    See below for a solution with base R lapply:

    library(freqtables)
    table_list <- lapply(vars, function(x){
      freq_table(mtcars, .data[[x]], percent_ci = 95, ci_type = "logit", drop = FALSE)}
      )
    do.call("rbind", table_list)