[R] Q: selecting a name when it is known as a string

Gustaf Rydevik gustaf.rydevik at gmail.com
Thu Sep 6 09:13:27 CEST 2007


On 9/5/07, D. R. Evans <doc.evans at gmail.com> wrote:
> D. R. Evans said the following at 09/04/2007 04:14 PM :
> > I am 100% certain that there is an easy way to do this, but after
>
> I have reconsidered this and now believe it to be essentially impossible
> (or at the very least remarkably difficult) although I don't understand why
> it is so :-(
>
> At least, I spent another two hours trying variations on the suggestions I
> received, but still nothing worked properly.
>
> It sure seems like it _ought_ to be easy, because of the following argument:
>
> If I type an expression such as "A <- <something>" then R is perfectly
> capable of parsing the <something> and executing it and assigning the
> result to A. So it seems to follow that it ought to be able to parse a
> string that contains exactly the same sequence of characters (after all,
> why should the R parsing engine care whether the input string comes from
> the terminal or from a variable?) and therefore it should be possible to
> assign "<something>" to a variable and then have R parse that variable
> precisely as if it had been typed.
>
> That was my logic as to why this ought to be easy, anyway. (And there was
> the subsidiary argument that this is easy in the other languages I use, but
> R is sufficiently different that I'm not certain that that argument carries
> much force.)
>
> It does seem that there are several ways to make the
>
>   lo <- loess(percent ~ ncms * ds, d, control=loess.control(trace.hat =
> > 'approximate'))
>
> command work OK if the right hand side is in a character variable, but I
> haven't been able to find a way to make
>
>   grid <- data.frame(expand.grid(ds=MINVAL:MAXVAL, ncms=MINCMS:MAXCMS))
>
> work.
>
> I always end up with a parse error or a complaint that "'newdata' does not
> contain the variables needed" when I perform the next task:
>
>   plo <- predict(lo, grid).
>
> So I guess I have to stick with half a dozen compound "if" statements, all
> of which do essentially the same thing :-(
>

How about:

> foo<-c("a","b")
> a<-1
> b<-2
> lapply(foo,function(x){eval(parse(text=paste(c("10+",x),collapse="")))})
[[1]]
[1] 11

[[2]]
[1] 12


,i.e you build up a text string containing your function call, and
then evaluate it, once for each value of foo?

/Gustaf


-- 
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik



More information about the R-help mailing list