Re: [R] convert text to exprission good for lm arguments

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Thu, 03 May 2007 09:47:22 -0400

On 5/3/07, Vladimir Eremeev <wl2776_at_gmail.com> wrote:
>
>
> Vadim Ogranovich wrote:
> >
> > Hi,
> >
> > I ran into a problem of converting a text representation of an expression
> > into parsed expression to be further evaluated inside lm ().
> >
> >> n <- 100
> >> data <- data.frame(x= rnorm (n), y= rnorm (n))
> >> data. lm <- lm (y ~ x, data=data)
> >>
> >> ## this works
> >> update(data. lm , subset=x<0)
> >
> > Call:
> > lm (formula = y ~ x, data = data, subset = x < 0)
> >
> > Coefficients:
> > (Intercept) x
> > -0.07864094193322170023 -0.14596982635007796358
> >
> >>
> >> ## this doesn't work
> >> ## text representation of subset
> >> subset <- "x<0"
> >> update(data. lm , subset=parse(text=subset))
> > Error in `[.data.frame`(list(y = c(-0.601925958140825, -0.111931189071517,
> > :
> > invalid subscript type
> >
> > What is the correct way to convert "x<0" into a valid subset argument?
> >
>
> update(data.lm,subset=eval(parse(text=subset)))

Just wanted to point out one difference. Using eval is not quite the same as using do.call since the Call: part does not come out as desired if you use eval but if you use do.call it comes out good enough that you can tell what was intended to be subset from the output:

> update(data.lm,subset=eval(parse(text=subset)))

Call:
lm(formula = y ~ x, data = data, subset = eval(parse(text = subset)))

Coefficients:

(Intercept)            x
    -0.1335      -0.1248


> do.call("update", list(data.lm, subset = parse(text = subset)))

Call:
lm(formula = y ~ x, data = data, subset = expression(x < 0))

Coefficients:

(Intercept)            x
    -0.1335      -0.1248

______________________________________________
R-help_at_stat.math.ethz.ch 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. Received on Thu 03 May 2007 - 14:11:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 03 May 2007 - 15:01:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.