gpt4 book ai didi

r - Dplyr "Arrange"在函数内向其传递参数时函数不起作用

转载 作者:行者123 更新时间:2023-12-02 17:17:53 29 4
gpt4 key购买 nike

我一直在查看有关在自定义函数内向 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

尽管如此,我希望对结果进行排序,因此我使用了 arrange 函数来按统计数据对其进行排序。

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)

所以我不知道如何解决这个问题。

最佳答案

利用 Rlang's new curly-curly notation :

top_leaders <- function(df, playerID, metric, n) {
df %>%
dplyr::select({{playerID}}, {{metric}}) %>%
dplyr::top_n(n) %>%
dplyr::arrange(desc({{metric}})) %>%
return(.)
}

top_leaders(as_tibble(Lahman::Batting), playerID, R, 5)

#Selecting by R
## A tibble: 5 x 2
# playerID R
# <chr> <int>
#1 hamilbi01 198
#2 brownto01 177
#3 ruthba01 177
#4 oneilti01 167
#5 gehrilo01 167

您还需要将playerID传递给该函数,但这是一个很小的改变。

关于r - Dplyr "Arrange"在函数内向其传递参数时函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58106445/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com