2

Perhaps is a silly question, but I couldn't find a solution for this. I want to pass the variable name using paste(), and use the variable name to evaluate an inequality within dplyr::filter(), but it returns 0 rows, not my expected output

I tried using eval() and as.formula() without success

library(dplyr)

dcl <- '07'
xdecil <- paste('detr0', dcl, sep='')
final_cust <- cd_probs %>% filter(final_prob>=xdecil)
Nate
  • 10,361
  • 3
  • 33
  • 40
Oscar Benitez
  • 255
  • 3
  • 13
  • 1
    `xdecil` returns `"detr007"`, so how are you expecting to compare `final_prob` (likely a numeric variable) with a string? Are you trying to do string comparison? – acylam Jul 17 '19 at 18:04
  • 1
    Please give a [mcve]. See [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269/4996248) for what this would mean in R. – John Coleman Jul 17 '19 at 18:04

2 Answers2

2

We can turn the string representation of the variable name to a symbol and unquote with !!:

library(dplyr)
library(rlang)

varname <- 'mpg'
mtcars %>%
  filter(qsec >= !!sym(varname))

or with as.name if we don't want to load rlang:

library(dplyr)

varname <- 'mpg'
mtcars %>%
  filter(qsec >= !!as.name(varname))

Output:

    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
2  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
3  22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
4  17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
5  16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
6  17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
7  15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
8  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
9  10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
10 14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
11 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
12 15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
13 13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
acylam
  • 18,231
  • 5
  • 36
  • 45
  • I wish I could upvote this ten times. Googling for this issue is hard, and I don't know how I would've found the `as.name`. It's not in https://dplyr.tidyverse.org/articles/programming.html#different-expressions, where I look for this stuff. – dfrankow Apr 14 '20 at 15:48
  • @dfrankow Related and may give you some insights: https://stackoverflow.com/a/50161301/5150629 – acylam Apr 14 '20 at 16:14
0

Although I agree with @avid_useR solution, I share some of my thoughts:

If I understand your issue correctly, you want the xdecil object to point to another existing variable named detro007 with certain value? If that is the case, you can use ?get() function to assign the value of your existing detro007 variable to the one you created.

Try:

library(dplyr)

dcl <- '07'
xdecil <- get(paste('detr0', dcl, sep=''))

final_cust <- cd_probs %>% filter(final_prob>=xdecil)

Chuan
  • 667
  • 8
  • 22