R - 如何运行存储在变量中的计算

Nim*_*ima 1 r formula

如果我有一个存储在字符向量中的算术公式,我如何让R运行它?即:

> the_character
[1] "282 * 480 - 129"
Run Code Online (Sandbox Code Playgroud)

上面的结果是一个字符类型.简单地将as.numeric(the_character)结果为NA:

> as.numeric(the_character, na.rm = TRUE)

Warning message:
NAs introduced by coercion 
Run Code Online (Sandbox Code Playgroud)

我知道我可以将其复制并粘贴到控制台中,但我想知道是否有办法在脚本中自动执行此操作?

Gre*_*now 6

您可以使用evalparse(如评论中所述)执行此操作:

eval(parse(text=the_character))
Run Code Online (Sandbox Code Playgroud)

但请注意以下事项:

> library(fortunes)
> fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)
Run Code Online (Sandbox Code Playgroud)

您的示例相当温和,但如果您允许其他人确定要解析的字符串,那么您将打开一个主要的安全漏洞.即使你自己构建字符串并确保它是安全的,这种方法很容易发现错误.

如果您可以向我们提供有关字符串构建方式以及最终目标的更多信息,那么我们可能会建议以更好的方式完成您想要的方法.