将变量传递给循环中的dplyr :: count

joz*_*mck 6 r dplyr

我正在尝试dplyr::count()在一个数据集中运行一组任意变量.如果我count()为每个变量手动运行一次,我会得到预期的结果.但是当我尝试为count()一组变量中的每个变量自动运行for循环时,我收到了一个错误.似乎问题在于我如何将变量传递给count()for循环.我知道count()它的变量不加引号,无论出于何种原因,R都无法判断我传递的是变量.

我已经尝试了很多事情来解决这个问题,包括传递变量data$var1,quo(var1),enquo(var1),var1,“var1”,quo(data$var1),和enquo(data$var1)以及unquoting与迭代器!!.我也尝试将参数指定为count()like count(x=data, var=i),但这导致count()返回数据中的总行数作为每次迭代的计数.如果您对导致错误的原因或我如何解决错误有任何想法,我将非常感谢您听到它们!

这是一个可重复的最小示例,它依赖于lakers包含的数据集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))
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 7

这有效:

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
Run Code Online (Sandbox Code Playgroud)

如果你想以myCols愚蠢的方式传递,你将不得不查看rlang包.


小智 6

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

如果您有一个由变量名组成的字符向量,并且想使用 for 循环对它们进行操作,请索引到特殊.data代词:

for (var in names(mtcars)) {
  mtcars %>% count(.data[[var]]) %>% print()
}
Run Code Online (Sandbox Code Playgroud)