[R] Replacement in an expression - can't use parse()
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Mar 28 13:37:57 CEST 2007
The solution in my post has the advantage of not using
eval or character conversions (except in setting up
L where you want such character conversions to
build up the names, as your more general sitution
shows). The following is the same as in that post except
the line setting L in that post is replaced with the 2 lines
setting i, j and L. Setting L in this way would also work
in conjunction with some of the other solutions too:
e <- expression(u1 + u2 + u3)
i <- 1; j <- 2; L <- list()
L[[paste("u", i, sep = "")]] <- as.name(paste("u", j, sep = ""))
as.expression(do.call(substitute, list(as.call(e), L))[[1]])
One can streamline it further by making it a function and
using assign:
subu <- function(e, i, j) {
assign(paste("u", i, sep = ""), as.name(paste("u", j, sep = "")))
as.expression(do.call(substitute, list(as.call(e)))[[1]])
}
e <- expression(u1 + u2 + u3)
subu(e, 1, 2)
On 3/28/07, Daniel Berg <daniel at danielberg.no> wrote:
> Thank you very much for your good suggestions.
> I have chosen to pursue the suggestion by Peter which worked like a dream :)
> However, my problem is slightly more complicated still. I apologize
> for not mentioning this in the initial question.
>
> I have to do the evaluation inside a loop, not knowing explicitly
> which 'u' to replace. This is given by the loop I'm in, say something
> like:
>
> i <- 2; j <- 3
> eval(substitute(substitute(call,list(paste("u",i,sep="")=quote(x),paste("u",j,sep="")=1)),list(call=e[[1]])))
>
> But this returns a syntax error.
> Any further suggestions?
>
> Regards,
> Daniel
>
> On 3/27/07, Thomas Lumley <tlumley at u.washington.edu> wrote:
> > On Tue, 27 Mar 2007, Peter Dalgaard wrote:
> >
> > >The way around this is to add a further layer of substitute() to insert
> > >the value of e:
> >
> > >> eval(substitute(substitute(call,list(u2=quote(x),u3=1)),list(call=e[[1]])))
> > > u1 + x + 1
> >
> > Or eval(do.call(substitute, list(e[[1]], list(u2=quote(x),u3=1)))
> >
> > -thomas
> >
> >
>
>
> --
> danielberg.no
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list