R、 使用dplyr::filter()和%in%将列名作为参数传递给函数

R、 使用dplyr::filter()和%in%将列名作为参数传递给函数,r,filter,dplyr,R,Filter,Dplyr,如何在与问题类似的函数中传递列名,但使用dplyr链接和filter()以及%中的% require(dplyr) set.seed(8) df <- data.frame( A=sample(c(1:3), 10, replace=T), B=sample(c(1:3), 10, replace=T)) 我得到: A B 1 2 3 2 1 2 3 1 3 4 2 1 5 1 1 6 1 3 现在,我如何将其放入函数中,在函数中可以指定列,但这不起作用: fun1 &l

如何在与问题类似的函数中传递列名,但使用
dplyr
链接和
filter()
以及%中的
%

require(dplyr)
set.seed(8)
df <- data.frame(
  A=sample(c(1:3), 10, replace=T), 
  B=sample(c(1:3), 10, replace=T))
我得到:

  A B
1 2 3
2 1 2
3 1 3
4 2 1
5 1 1
6 1 3
现在,我如何将其放入函数中,在函数中可以指定列,但这不起作用:

fun1 <- function(x, column, n){
  res <- 
    x %>% filter(column %in% n)
  return(res)
}
fun1(df, A, c(1,2))
fun1你可以试试

fun1 <- function(x, column, n){
 x %>% 
  filter_(lazyeval::interp(quote(x %in% y), x=as.name(column), y=n))
 }
fun1(df, 'A', 1:2)
fun1%
过滤器(lazyeval::interp(引号(x%in%y),x=as.name(column),y=n))
}
fun1(df,'A',1:2)


fun2如果要保留功能,请尝试:

fun1 <- function(x, column, n){
  res <- x %>% filter_(paste(column,"%in%",n))
  return(res)
}

fun1(df, "A", "c(1,2)")

fun1尝试将函数更改为

fun1 <- function(x, column, n){
    require(lazyeval)
    filter_(x,
        interp(quote(col %in% n),
            col = lazy(column), n = n))
}

all(fun1(df, A, c(1, 2)) == filter(df, A %in% c(1,2)))
# TRUE

fun1现在这是一件很好的事情。刚才我问了一个类似的问题,@aosmith给出了一个很好的答案。在这里,我看到了一个更新版本。今天我在做笔记+1@akrun您能解释一下您的选项2吗?
match.call()
是否包含函数中的所有参数?在
eval()
中,
filter()
是如何解释的?@user3375672是的,match.call()包含所有参数。这里,数据集是该列的
envir
(即
x
)。请检查
?eval
fun1 <- function(x, column, n){
  res <- x %>% filter_(paste(column,"%in%",n))
  return(res)
}

fun1(df, "A", "c(1,2)")
fun1 <- function(x, column, n){
    require(lazyeval)
    filter_(x,
        interp(quote(col %in% n),
            col = lazy(column), n = n))
}

all(fun1(df, A, c(1, 2)) == filter(df, A %in% c(1,2)))
# TRUE