R dplyr column as variable

Viewed 60

Could you please help me.

I tried already many combinations, but nothing works.

Here the example:

library(dplyr)

foo <- function(AA,x){
  mn <- make.names(x)
  mn <- enquo(mn)
  filter(AA,mn==min(!!mn))
}

aa <- data.frame(A=c("a","b","c","d"), B.D = c(1,2,1,3))

foo(aa,"B D")

The output is

 Error: Base operators are not defined for quosures.
Do you need to unquote the quosure?

  # Bad:
  myquosure == rhs

  # Good:
  !!myquosure == rhs
Run `rlang::last_error()` to see where the error occurred. 

instead of

filter(aa,B.D==min(B.D))

  A B.D
1 a   1
2 c   1

Could you please help me to get the desired output using my function.

Thank you.

John

2 Answers

Slightly simpler to use the {{ }} "embrace" or "double curly" operator, but it expects the variable name raw vs. as a string.

foo <- function(AA,x){
  filter(AA, {{ x }} == min({{ x }}))
}


foo(aa, B.D)  # or foo(aa, `B.D`)
  A B.D
1 a   1
2 c   1

Convert to symbol instead of quosure

foo <- function(AA,x){
   mn <- make.names(x)
    mn <- ensym(mn)
    filter(AA,!!mn==min(!!mn))
 }

-testing

foo(aa, "B D")
#  A B.D
#1 a   1
#2 c   1
Related