我有一个成对的变量:
-a_x,a_y,
-b_x,b_y,
-c_x,c_y等。
如何编写根据“ a”,“ b”或“ c”过滤的函数。例如,我想返回
filter(df, a_x != a_y)
或
filter(df, b_x != b_y)
我正在使用quasure,如 https://dplyr.tidyverse.org/articles/programming.html, 但没有成功。
这是示例:
test <-tribble(~a_x, ~b_x, ~a_y, ~b_y,
1,2,1,2,
5,6,5,8,
9,8,11,8)
# that works
x <-quo(a_x)
y <-quo(a_y)
filter(test, !!x == !!y)
x <-quo(b_x)
y <-quo(b_y)
filter(test, !!x == !!y)
# but the function doesn't work
my <- function(df, var){
a <- paste0(quo_name(var), "_x")
b <- paste0(quo_name(var), "_y")
print(quo(filter(df, !!a == !!b)))
return(filter(df, !!a == !!b))
}
my(test, "a")
my(test, "b")
答案 0 :(得分:3)
在传递字符串时,转换为符号并求值更容易
library(dplyr)
library(rlang)
my <- function(df, var){
a <- sym(paste0(var, "_x"))
b <- sym(paste0(var, "_y"))
df %>%
filter(!!a == !!b)
}
my(test, "a")
# A tibble: 2 x 4
# a_x b_x a_y b_y
# <dbl> <dbl> <dbl> <dbl>
#1 1 2 1 2
#2 5 6 5 8
my(test, "b")
# A tibble: 2 x 4
# a_x b_x a_y b_y
# <dbl> <dbl> <dbl> <dbl>
#1 1 2 1 2
#2 9 8 11 8
如果OP也打算传递不带引号的参数,则
my <- function(df, var){
a <- sym(paste0(quo_name(enquo(var)), "_x"))
b <- sym(paste0(quo_name(enquo(var)), "_y"))
df %>%
filter(!!a == !!b)
}
my(test, a)
my(test, b)
注意:上面同时接受了带引号和不带引号的参数
identical(my(test, "a"), my(test, a))
#[1] TRUE
identical(my(test, "b"), my(test, b))
#[1] TRUE