2

A petty problem with an obvious solution to rename the parameter of the function. Yet I am interested whether there is a way how I can achieve the following where column name and argument name are the same?

library(dplyr)
d <- data.frame(x = 1:3)

f <- function(x) {
  list(
          ## returns all b/c always true
          d %>% filter(x == x), 

          ## does not work either
          ## any way to tell dplyr to use the parameter x
          d %>% filter(.data$x == x)
       )
}
f(1)
thothal
  • 16,690
  • 3
  • 36
  • 71

2 Answers2

3

One option could be:

f <- function(x) {
 d %>% 
  filter(x == !!x)
}
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
1

You can use {{}}

library(dplyr)
library(rlang)

f1 <- function(df, x) df %>% filter({{x}} == x)
f1(d, 1)

#  x
#1 1

f1(d, 2)
#  x
#1 2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213