在脚本中明确解析R代码的一部分 [英] Explicitly parse part of R code in a script

查看:100
本文介绍了在脚本中明确解析R代码的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用例如下:

  • 显示GUI以收集一些R表达式
  • 生成包含我的仿真框架的单个源文件,并与用户提供的R表达式混合
  • 允许用户生成单个源文件.如果用户指定的任何表达式包含错误(语法或运行时),我想以一种用户友好的方式显示这些错误.

简而言之,我想做如下事情:

In short, I want to do something as follows:

myExpression <- "3 * 5"
myExprParsed <- tryCatch( parse(myExpression), .... )

我的问题很简单:R是否在正则表达式中具有类似\Q \E的结构,从头到尾完全引用了文本字符串? myExpression不太可能包含"字符,从而引入语法错误.我不想将文本内容写到单独的文本文件中并使用source().

My question is very simple: does R have some construct like \Q \E in regex, fully quoting a text string from beginning to end ? It is not unlikely that myExpression will contain the " character, thereby introducing a syntax error. I do not want to write the text contents to a separate text file and use source().

=示例=

myExpression <- " XXXXXXX "

其中XXXXXX是paste("my random value is ", runif(3))

myExpression <- " paste("my random value is ", runif(3)) "

这将给出语法错误.我想要类似的东西

which would give a syntax error. I want something like

myExpression <- verbatim@   paste("my random value is ", runif(3))   @

推荐答案

从用户那里获取一些输入-我想您只是从GUI文本框中获取值.我将使用scan:

Get some input from the user - you'd just be getting values from text boxes in your GUI, I guess. I'll use scan:

> dowhat = scan(what="")
1: x="hello world"
3: 
Read 2 items

我们引用了字符串:

> dowhat
[1] "x=\"hello" "world\""  

我们可以解析它:

> parse(text=dowhat)
expression(x="hello
world")

并且有一个换行符,因为scan()按行分割内容.并不是真正的问题,并且可以在需要时修复.

And there's a line break because scan() splits things by lines. Not really a problem, and fixable if you care.

现在让我们实际运行它:

Now let's actually run it:

> eval(parse(text=dowhat))

现在我们应该有一个x:

> x
[1] "hello\nworld"
> 

?

这篇关于在脚本中明确解析R代码的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆