gpt4 book ai didi

r - 无法使用输入参数函数作为过滤器参数 (R/dplyr)

转载 作者:行者123 更新时间:2023-12-04 16:00:04 24 4
gpt4 key购买 nike

我在 R 中编写函数时遇到了以下问题。我想使用我的列名称之一 (id) 作为我的输入参数 (X)过滤我的数据集的功能。

不幸的是,我的函数似乎无法理解 filter() 中的 X 参数。有人对我如何让它发挥作用有什么建议吗?

谢谢

数据

library(tidyverse)

df_data <- tibble(
year = c(2004, 2005, 2006),
id = c(1, 2, 3),
value = c(10, 12, 1)
)

功能

FUNCTION <- function(data, X, Y){
result <- df_data %>%
filter(X == Y) %>%
glimpse
}

输出

FUNCTION(data = df_data,X = "id", Y = 1)  

Observations: 0
Variables: 3
$ year <dbl>
$ id <dbl>
$ value <dbl>

最佳答案

如果 'X' 的预期输入参数是字符串,我们可以使用 rlang 中的 sym

FUNCTION <- function(data, X, Y){
data %>%
filter((!! rlang::sym(X)) == Y)
}

FUNCTION(data = df_data, X = "id", Y = 1)
# A tibble: 1 x 3
# year id value
# <dbl> <dbl> <dbl>
#1 2004 1 10

如果我们对“X”使用不带引号的值,请转换为 quosure,然后计算 (!!)

FUNCTION <- function(data, X, Y){
X <- enquo(X)
data %>%
filter((!! X) == Y)

}

注意:在 OP 的帖子中,FUNCTION

中的 'data' 参数也不同
FUNCTION(data = df_data, X = id, Y = 1)  
# A tibble: 1 x 3
# year id value
# <dbl> <dbl> <dbl>
#1 2004 1 10

关于r - 无法使用输入参数函数作为过滤器参数 (R/dplyr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776013/

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