R, pass the column name as an argument to the function using dplyr :: filter () and% in%

How to pass the column name in a function similar to the topic here , but using the dplyr and filter() chain along 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)) 

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

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

I get:

  AB 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 you can specify a column, this does not work:

 fun1 <- function(x, column, n){ res <- x %>% filter(column %in% n) return(res) } fun1(df, A, c(1,2)) 
+5
source share
3 answers

You may try

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

or

 fun2 <- function(x, column, n){ args <- as.list(match.call()) x %>% filter(eval(args$column, x) %in% n) } fun2(df, A, 1:2) 
+8
source

If you want to keep your function, try:

 fun1 <- function(x, column, n){ res <- x %>% filter_(paste(column,"%in%",n)) return(res) } fun1(df, "A", "c(1,2)") 
+4
source

Try changing your function to

 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 
+2
source

Source: https://habr.com/ru/post/1212622/


All Articles