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

时间:2015-02-04 14:46:54

标签: r filter dplyr

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

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列为1或2的行,我可以这样做:

df %>% filter(A %in% c(1,2))

我明白了:

  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))

3 个答案:

答案 0 :(得分:8)

你可以尝试

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

或者

fun2 <- function(x, column, n){
   args <- as.list(match.call())
   x %>%
     filter(eval(args$column, x) %in% n)
 }

 fun2(df, A, 1:2)

答案 1 :(得分:4)

如果您想保留您的功能,请尝试:

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

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

答案 2 :(得分: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
相关问题