Skip to content

Turning strings into expressions

4 messages · Alexander Sokol, Duncan Murdoch, Dimitris Rizopoulos +1 more

#
Hello,

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"

to

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?

Thanks,
 Alexander
#
On Thu, 25 Nov 2004 14:09:14 +0100, Alexander Sokol
<alexandersokol at ofir.dk> wrote :
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
#
Hi Alexander,

you could try:

my.string <- "A==1 & B==2"
(my.frame <- data.frame(A=sample(1:2, 20, TRUE), B=sample(1:2, 20, 
TRUE)))
subset(my.frame, eval(parse(text=my.string)))

I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat
     http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Alexander Sokol" <alexandersokol at ofir.dk>
To: <r-help at stat.math.ethz.ch>
Sent: Thursday, November 25, 2004 2:09 PM
Subject: [R] Turning strings into expressions
#
"Dimitris Rizopoulos" <dimitris.rizopoulos at med.kuleuven.ac.be> writes:
Hmm, considering the nonstandard evaluation that is going on inside
subset(), I think I'd rather try

 my.frame <- data.frame(A=sample(1:2, 20, TRUE), B=sample(1:2, 20,TRUE))
 my.string <- "A==1 & B==2"
 l <- as.list(parse(text=my.string))
 names(l)<-"sub"
 eval(substitute(subset(my.frame, sub), l))
   A B
18 1 2


(or perhaps l <- list(sub=parse(text=my.string)[[1]]) is less
cryptic).

Point being that this way you'll literally evaluate
subset(my.frame, A == 1 & B == 2)