【发布时间】:2019-09-25 20:58:31
【问题描述】:
我一直在查看有关在自定义函数中将参数传递给 dplyr 函数的帖子,但我无法解决以下情况:
我创建了以下函数来获取数据框的子集。
library(Lahman)
top_leaders <- function(df, metric, n) {
# metric is the name of the column of Batting df which I would like to analyze
# n is the number of top players leaders on that metric
stat_leader <- enquo(metric)
df %>%
dplyr::select(playerID, !!stat_leader) %>%
dplyr::top_n(n)
}
因为这个函数在该统计数据上对 n 个玩家的领导者进行了子集化,所以效果很好。例如:
> top_leaders(Lahman::Batting, "R", 5)
Selecting by R
playerID R
1 oneilti01 167
2 brownto01 177
3 hamilbi01 198
4 ruthba01 177
5 gehrilo01 167
尽管如此,我希望对结果进行排序,所以我使用 include arrange 函数来按 stat 对其进行排序。
top_leaders <- function(df, metric, n) {
stat_leader <- enquo(metric)
df %>%
dplyr::select(playerID, !!stat_leader) %>%
dplyr::top_n(n) %>%
dplyr::arrange(desc(!!stat_leader))
}
但它给出了以下错误:
Selecting by R
Error: incorrect size (1) at position 1, expecting : 5
我后来尝试使用arrange_(desc(!!stat_leader)) 也出现另一个错误:
Selecting by R
Error: Quosures can only be unquoted within a quasiquotation context.
# Bad:
list(!!myquosure)
# Good:
dplyr::mutate(data, !!myquosure)
所以我不知道如何解决这个问题。
【问题讨论】:
-
当您使用裸列名称(即
R而不是"R")调用它时是否有效?这就是这些基于dplyr的函数中的约定