[R] Character string to R object

Duncan Murdoch murdoch.duncan at gmail.com
Sat Apr 28 17:07:54 CEST 2012


On 12-04-28 10:37 AM, Ista Zahn wrote:
> Hi JN,
>
> You can use
>
> eval(parse(text = cstr))
>
> for this. I've been told to avoid this when possible, though I'm not sure why.

I would say to avoid it because it's hard to catch errors easy errors, 
and it can introduce difficult errors.  Presumably cstr isn't a constant 
string (or you wouldn't have bothered with this form), so you need to 
make sure that cstr contains valid code.  That requires lots of checks 
that really belong in the parser at install time, not at execution time, 
when errors are harder to fix.

For an example of a hard error, I think you might use 
deparse(substitute(arg)) to get an expression passed as an argument. 
But deparse() is not guaranteed to reproduce the original expression. 
So why not just use substitute(arg), which is guaranteed to give the 
original expression, and plunk it into your function using a trick like 
Gabor's, e.g.

body(f) <- substitute(arg)

if that's what you're intending?  (This example is nearly as silly as 
John's, but the point is that once something is parsed, just keep it 
parsed, don't deparse and reparse it.)

Duncan Murdoch


>
> Best,
> Ista
>
> On Sat, Apr 28, 2012 at 10:27 AM, John C Nash<nashjc at uottawa.ca>  wrote:
>> I've been creating some R tools that manipulate objective functions for
>> optimization. In so doing, I create a character string with R code, and then
>> want to have it in my workspace. Currently -- and this works fine -- I write
>> the code out, then use source() to bring it in again. Example:
>>
>> cstr<-"jack<-function(x){\n cat(\"Silly x:\")\n print(x) \n  }\n"
>> write(cstr, file='tfile.txt')
>> jack<-source('tfile.txt')$value # You need the value element!
>> print(jack)
>>
>> However, I feel it would be more elegant if I could avoid the file, and am
>> sure I must have missed some way to pipe the cstr through the source()
>> function. Also, if the file cannot be written (directory permissions?), then
>> my approach won't work.
>>
>>
>> JN
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list