R,将列名称作为参数使用dplyr :: filter()和%在% [英] R, pass column name as argument to function using dplyr::filter() and %in%

查看:131
本文介绍了R,将列名称作为参数使用dplyr :: filter()和%在%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何传递类似于这里,但使用 dplyr 链接和 filter()连同 %in%

How can I pass a column name in a function similar to the question here but using dplyr chaining and filter() together with %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的行,我可以做:

If want to get rows where column A is 1 or 2 I can do:

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

现在,我如何将它放在一个可以指定列的函数中,这不起作用:

Now, how can I put this in a function, where one can specify the column, this does not work:

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


推荐答案

您可以尝试

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)

这篇关于R,将列名称作为参数使用dplyr :: filter()和%在%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆