简体   繁体   English

如何将字符串评估为 R 中的变量?

[英]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我想使用paste()传递变量名,并使用变量名来评估dplyr::filter()内的不等式,但它返回 0 行,而不是我预期的输出

I tried using eval() and as.formula() without success我尝试使用eval()as.formula()没有成功

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 :或者使用as.name如果我们不想加载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:虽然我同意@avid_useR 的解决方案,但我分享了一些我的想法:

If I understand your issue correctly, you want the xdecil object to point to another existing variable named detro007 with certain value?如果我正确理解您的问题,您是否希望xdecil对象指向另一个名为detro007且具有特定值的现有变量? If that is the case, you can use ?get() function to assign the value of your existing detro007 variable to the one you created.如果是这种情况,您可以使用?get()函数将现有detro007变量的值分配给您创建的变量。

Try:尝试:

library(dplyr)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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