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

Tony Plate tplate at acm.org
Wed Sep 5 00:46:17 CEST 2007


You can use substitute() for this.  The drawback with this approach is 
that the formula in the call in the printed value of loess() is ugly.

 > x <- data.frame(y=rnorm(20), x1=rnorm(20), x2=rnorm(20))
 > loess(y~x2, data=x)
Call:
loess(formula = y ~ x2, data = x)

Number of Observations: 20
Equivalent Number of Parameters: 4.68
Residual Standard Error: 1.208
 > loess(substitute(y~X, list(X=as.name('x2'))), data=x)
Call:
loess(formula = substitute(y ~ X, list(X = as.name("x2"))), data = x)

Number of Observations: 20
Equivalent Number of Parameters: 4.68
Residual Standard Error: 1.208
 > loess(y~x1, data=x)
Call:
loess(formula = y ~ x1, data = x)

Number of Observations: 20
Equivalent Number of Parameters: 4.87
Residual Standard Error: 1.179
 > loess(substitute(y~X, list(X=as.name('x1'))), data=x)
Call:
loess(formula = substitute(y ~ X, list(X = as.name("x1"))), data = x)

Number of Observations: 20
Equivalent Number of Parameters: 4.87
Residual Standard Error: 1.179
 >

hope this helps,

Tony Plate


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.
> 
> ______________________________________________
> 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