2017-09-15 39 views
4

我试图在一个数据集中的任意一组变量上运行dplyr::count()。如果我为每个变量手动运行count()一次,我会得到预期的结果。但是,当我尝试将count()放在for循环中以便为一组变量中的每个变量自动运行时,出现错误。看起来问题在于我如何将变量传递给for循环中的count()。我知道count()将其变量未加引号,无论出于何种原因,R无法说明我传递的是变量。将变量传递给循环中的dplyr :: count

我已经尝试了很多事情来解决这个问题,包括通过变量为data$var1quo(var1)enquo(var1)var1“var1”quo(data$var1)enquo(data$var1)以及与!! unquoting迭代器。我还尝试指定count()的参数,如count(x=data, var=i),但这会导致count()返回数据中的总行数作为每次迭代的计数。如果您对导致错误的原因有任何想法,或者我可以如何解决它,我将非常感激他们的声音!

这是一个可重复使用的最小示例,它依赖于lubridate附带的lakers数据集。

# 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)) 
} 

回答

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 

如果你想通过myCols在tibbledish方式,你必须来查找rlang包。

+0

嗯,当我尝试运行线我得到 “(as.quoted“)在UseMethod错误”的错误: 为‘as.quoted’不适用的方法适用于类的对象‘功能’” – jozimck

+0

@ jozimck如果你在一个新的R会话中只用你的问题和这个答案中的代码来运行它,那你看到了什么?它可能是一个版本化的东西;我在dplyr 0.4.3和R 3.3.3 – Frank

+1

啊是的,那么它的工作原理如上所示。我的工作空间一定会有些混乱。感谢您的回答! – jozimck