[R] transfer string to expression

Duncan Murdoch murdoch.duncan at gmail.com
Sun Oct 31 21:29:19 CET 2010


On 31/10/2010 3:22 PM, Yilong Zhang wrote:
> Dear all:
>
> when I use parse() there is some problems. Below is an example:
>
> b0<-1
> b1<-1
> x<-1
> str2expr<-function(x){eval(parse(text=x))}
> test1<-"b0+b1*sqrt(x)"
> test2<-"b0+b1"
> str2expr(test1)
> str2expr(test2)
>
> it can work well for test2 but not for test1.
>
> Could you tell me how to fix this problem or is there other more stable
> method to transfer an string to expression?

You are evaluating those expressions in the evaluation frame of your 
function, where "x" is the expression.  Just specify the environment in 
which you want to evaluate them, e.g.

str2expr<-function(x){eval(parse(text=x), envir=parent.frame() )}

Duncan Murdoch

>
> best regards
>
> Elong
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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