[R] Turning strings into expressions

Duncan Murdoch murdoch at stats.uwo.ca
Thu Nov 25 14:37:38 CET 2004

On Thu, 25 Nov 2004 14:09:14 +0100, Alexander Sokol
<alexandersokol at ofir.dk> wrote :

>I am running R 1.9.1 om Windows 2000 SP4. My problem is as follows:
>Say I have a dataframe my.frame with column names A and B. I have a string,
>[1] "A==1 & B==2"
>And I would like to retrieve the subset corresponding to my.string, that is, 
>from my.frame and my.string I would like to get the result of
>subset(my.frame,A==1 & B==2)
>So I need to find a way to convert
>"A==1 & B==2"
>A==1 & B==2
>I at first hoped that get() could do the job, but this does not work. Does 
>anyone know how to do this?

parse() does the conversion to an expression, but doesn't evaluate it.
So you probably want 

  eval(parse(text = "A == 1 & B == 2"))

but you may want to set the envir argument to eval, to tell R where to
go looking for A and B.

Duncan Murdoch

More information about the R-help mailing list