我不知道为什么从自定义函数传递参数不起作用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)
Run Code Online (Sandbox Code Playgroud)
我注意到,当我显式传递列名称时,group_by
它会起作用:
group_by(stations) %>%
Run Code Online (Sandbox Code Playgroud)
但是,在函数中对列名称进行硬编码是没有意义的。
这是另一种使其发挥作用的方法。您可以使用.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
Run Code Online (Sandbox Code Playgroud)
如果您决定不将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
Run Code Online (Sandbox Code Playgroud)