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

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Sep 5 00:41:45 CEST 2007


D. R. Evans wrote:
> I am 100% certain that there is an easy way to do this, but after
> experimenting off and on for a couple of days, and searching everywhere I
> could think of, I haven't been able to find the trick.
>
> I have this piece of code:
>
> ...
>   attach(d)
>
>   if (ORDINATE == 'ds')
>   { lo <- loess(percent ~ ncms * ds, d, control=loess.control(trace.hat =
> 'approximate'))
>     grid <- data.frame(expand.grid(ds=MINVAL:MAXVAL, ncms=MINCMS:MAXCMS))
> ...
>
> then there several almost-identical "if" statements for different values of
> ORDINATE. For example, the next "if" statement starts with:
>
> ...
>   if (ORDINATE == 'dsl')
>   { lo <- loess(percent ~ ncms * dsl, d, control=loess.control(trace.hat =
> 'approximate'))
>     grid <- data.frame(expand.grid(dsl=MINVAL:MAXVAL, ncms=MINCMS:MAXCMS))
> ...
>
> This is obviously pretty silly code (although of course it does work).
>
> I imagine that my question is obvious: given that I have a variable,
> ORDINATE, whose value is a string, how do I re-write statements such as the
> "lo <-" and "grid <-" statements above so that they use ORDINATE instead of
> the hard-coded names "ds" and "dsl".
>
> I am almost sure (almost) that it has something to do with "deparse()", but
> I couldn't find the right incantation, and the ?deparse() help left my head
> swimming.
>   

myvar <- 12345
vname <- "myvar"
eval(substitute(X+54321, list(X=as.name(vname))))

However, this does not work for argument names  as in 
expand.grid(ds=.....), so for that part you may need to patch up names 
afterwards.

It is (paraphrasing Thomas Lumley) often a good idea to reconsider the 
question if the answer involves this sort of trickery. Perhaps it is 
better handled by a loop or lapply over a list of variables?


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list