我不知道为什么将参数从自定义函数传递给group_by
不起作用。我只是通过一个colName
从数据集中,当我运行自己的函数时,会出现错误:必须按 .data 中找到的变量进行分组。
未找到列“colName”。在下面的示例中我使用quakes
R环境中可用的数据集:
foo <- function(data, colName) {
result <- data %>%
group_by(colName) %>%
summarise(count = n())
return(result)
}
foo(quakes, "stations")
# I also tried passing w/o commas but it is not working too:
# foo(quakes, stations)
我注意到,当我将列名显式传递给group_by
然后它就起作用了:
group_by(stations) %>%
但是,在函数中对列名称进行硬编码是没有意义的。
这是另一种使其发挥作用的方法。您可以使用.data[[var]]
构造存储为字符串的列名:
foo <- function(data, colName) {
result <- data %>%
group_by(.data[[colName]]) %>%
summarise(count = n())
return(result)
}
foo(quakes, "stations")
# A tibble: 102 x 2
stations count
<int> <int>
1 10 20
2 11 28
3 12 25
4 13 21
5 14 39
6 15 34
7 16 35
8 17 38
9 18 33
10 19 29
# ... with 92 more rows
如果您决定不通过考试ColName
作为字符串,您可以在函数内用一对大括号将其包裹起来,以获得类似的结果:
foo <- function(data, colName) {
result <- data %>%
group_by({{ colName }}) %>%
summarise(count = n())
return(result)
}
foo(quakes, stations)
# A tibble: 102 x 2
stations count
<int> <int>
1 10 20
2 11 28
3 12 25
4 13 21
5 14 39
6 15 34
7 16 35
8 17 38
9 18 33
10 19 29
# ... with 92 more rows
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)