Pass the variable dplyr :: count in a loop

Im trying to run dplyr::count() on an arbitrary set of variables in one data set. If I manually run count() once for each variable, I get the expected results. But when I try to put count() in a for loop to automatically run each variable in a set of variables, I got an error. It seems like the problem is how I pass the variable to count() in a for loop. I know that count() accepts its variables without quotes and for some reason R cannot say that what I pass is a variable.

Ive tried to fix this, including passing variables like data$var1 , quo(var1) , enquo(var1) , var1 , "var1" , quo(data$var1) and enquo(data$var1) , as well as an unquoting iterator with !! . I also tried to specify the arguments of count() as count(x=data, var=i) , but this called count() to return the total number of rows in the data as a counter for each iteration. If you have any ideas on what causes the error or how I can fix it, I am very grateful for listening to them!

The following is a minimal reproducible example based on the lubridate set included in lubridate .

 # This code requires some of the packages in tidyverse. library(dplyr) library(lubridate) # results = empty data frame for filling with info from the count() command results <- data.frame() # mydata = the source data myData <- lakers # myCols = list of the names of columns I want to count() myCols <- c("opponent", "game_type", "player", "period") # Loop to count() every column in myCols automatically and store the results in # one giant tibble of vars (var) and counts (n) for(i in myCols){ results <- bind_rows(results, count(x=myData, i)) } 
+5
source share
1 answer

It 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 transfer myCols Tibetan way, you will need to find the rlang package.

+7
source

Source: https://habr.com/ru/post/1271848/


All Articles