This question already has an answer here:
这个问题在这里已有答案:
- Evaluate expression given as a string 5 answers
评估作为字符串给出的表达式5个答案
I'm curious to know how I might achieve something like the following in R.
我很想知道如何在R中实现类似下面的内容。
I hope this psodu-code illustrates the concept.
我希望这个psodu代码说明了这个概念。
g <- 10
condition <- "g > 9"
if(condition) print("This works")
Specifically, does anyone know if it is possible to do something like this with the dplyr filter function? (Again, psudo-code):
具体来说,是否有人知道是否可以使用dplyr过滤器功能执行此类操作? (再次,psudo代码):
df <- data.frame(one = 1:5, two = 6:10, three = 11:15)
condition <- "two == 7 | one == 1"
filter(df, condition)
2 个解决方案
#1
1
Another option is to set your string as an expression
.
另一种选择是将字符串设置为表达式。
g <- 10
condition <- expression(g > 9)
if (eval(condition)) print("This works")
# [1] "This works"
This is what the parse
function in Tim's solution is doing, and that is a more generalised solution than this one in most cases.
这就是Tim解决方案中的解析功能所做的,在大多数情况下,这是一个比这个更通用的解决方案。
#2
1
One option is to use eval
with parse
:
一种选择是使用eval和parse:
g <- 10
exp <- "g > 9"
eval(parse(text=exp))
[1] TRUE
This approach should scale to more complex expressions, including those making function calls.
此方法应扩展到更复杂的表达式,包括进行函数调用的表达式。
#1
1
Another option is to set your string as an expression
.
另一种选择是将字符串设置为表达式。
g <- 10
condition <- expression(g > 9)
if (eval(condition)) print("This works")
# [1] "This works"
This is what the parse
function in Tim's solution is doing, and that is a more generalised solution than this one in most cases.
这就是Tim解决方案中的解析功能所做的,在大多数情况下,这是一个比这个更通用的解决方案。
#2
1
One option is to use eval
with parse
:
一种选择是使用eval和parse:
g <- 10
exp <- "g > 9"
eval(parse(text=exp))
[1] TRUE
This approach should scale to more complex expressions, including those making function calls.
此方法应扩展到更复杂的表达式,包括进行函数调用的表达式。