[R] parse/eval and character encoded expressions: How to deal with non-encoding strings?

Johannes Graumann johannes_graumann at web.de
Mon Jan 28 08:29:24 CET 2013


I am intending to save a path-describing character object in a slot of a 
class I'm working on. In order to have the option to use "system.file" etc 
in such string-saved path definitions, I wrote this

ExpressionEvaluator <- function(x){
  x <- tryCatch(
    error = function(e){return(as.expression(x))},

This produces

> ExpressionEvaluator("system.file(\"INDEX\")")
> eval(ExpressionEvaluator("system.file(\"INDEX\")"))
[1] "/usr/lib/R/library/base/INDEX"

Which is what I want. However, 

> eval(ExpressionEvaluator("Test"))
Error in eval(expr, envir, enclos) : object 'Test' not found

prevents me from general usage (also in cases where "x" does NOT encode an 

I don't understand why it is that
> base::parse(text="Test")
will return
[1] expression(Test)
> as.expression("Test")
[1] expression("Test")
which would work with the eval call.

Can anyone point out to me how to solve this generally? How can I feed the 
function a character object and get back an eval-able expression independent 
of whether there was an expression "encoded" in the input or not.

Thank you for any hints.

Sincerely, Joh

More information about the R-help mailing list