简体   繁体   中英

How to evaluate a string as a variable in R?

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM