这是使用 NSE(非标准评估)的函数的问题。使用 NSE 的函数在交互式编程中非常有用,但会在开发中引起许多问题,即当您尝试在其他函数中使用这些函数时。由于表达式没有被直接求值,R 无法在它所查找的环境中找到对象。我建议您阅读here最好是范围问题章节以获取更多信息。
首先你需要知道所有的标准dplyr
函数使用 NSE。让我们看一下您的问题的一个大概示例:
Data:
df <- data.frame(col1 = rep(c('a','b'), each=5), col2 = runif(10))
> df
col1 col2
1 a 0.03366446
2 a 0.46698763
3 a 0.34114682
4 a 0.92125387
5 a 0.94511394
6 b 0.67241460
7 b 0.38168131
8 b 0.91107090
9 b 0.15342089
10 b 0.60751868
让我们看看 NSE 如何解决我们的简单问题:
首先,简单的交互式案例有效:
df %>% group_by(col1) %>% summarise(count = n())
Source: local data frame [2 x 2]
col1 count
1 a 5
2 b 5
让我们看看如果我把它放在一个函数中会发生什么:
lets_group <- function(column) {
df %>% group_by(column) %>% summarise(count = n())
}
>lets_group(col1)
Error: index out of bounds
和你的错误不一样,但它是由 NSE 引起的。完全相同的代码行在函数之外工作。
幸运的是,有一个解决方案可以解决您的问题,那就是标准评估。 Hadley 还制作了所有函数的版本dplyr
使用标准评估。它们只是普通功能加上_
末尾加下划线。
现在看看这是如何工作的:
#notice the formula operator (~) at the function at summarise_
lets_group2 <- function(column) {
df %>% group_by_(column) %>% summarise_(count = ~n())
}
这会产生以下结果:
#also notice the quotes around col1
> lets_group2('col1')
Source: local data frame [2 x 2]
col1 count
1 a 5
2 b 5
我无法测试你的问题,但使用 SE 而不是 NSE 会给你你想要的结果。欲了解更多信息,您还可以阅读here