dfrankow
dfrankow

Reputation: 21387

Using function-scoped variable in a tidyverse filter expression

Suppose I have this code:

library(dplyr)

foo <- function(df, var) {
  message("var is ", var)
  df %>% filter(var==var)
}

df <- data.frame(var=c(1,2,3))
foo(df, 3)

The output is unfiltered, because var==var uses only the data frame column, and not the function parameter. See below:

> foo(df, 3)
var is 3
  var
1   1
2   2
3   3

What I always do is rename the function parameter the_var, and use var == the_var. However, I'd like to learn more about tidyverse scoping.

How can I filter the var column by the var function parameter value without changing any names?

Upvotes: 1

Views: 56

Answers (1)

akrun
akrun

Reputation: 887108

We can escape the variable inside the function to check the variable outside the environment of the data

foo <- function(df, var) {
  message("var is ", var)
   df %>% 
       filter(var == !!var)
 }

-output

foo(df, 3)
#var is 3
#  var
#1   3

Upvotes: 2

Related Questions