Pass a variable to dplyr::count in a loop

This works:

myData[myCols] %>% tidyr::gather(var, value) %>% count(var, value)

# A tibble: 407 x 3
         var value     n
       <chr> <chr> <int>
 1 game_type  away 17153
 2 game_type  home 17471
 3  opponent   ATL   904
 4  opponent   BOS   886
 5  opponent   CHA   412
 6  opponent   CHI   964
 7  opponent   CLE   822
 8  opponent   DAL  1333
 9  opponent   DEN  1855
10  opponent   DET   845
# ... with 397 more rows

If you want to pass myCols in a tibbledish manner, you'll have to look up the rlang package.


From :https://github.com/tidyverse/dplyr/blob/master/vignettes/programming.Rmd

If you have a character vector of variable names, and want to operate on them with a for loop, index into the special .data pronoun:

for (var in names(mtcars)) {
  mtcars %>% count(.data[[var]]) %>% print()
}

Tags:

R

Dplyr