[R] using names with functions..

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Wed Nov 28 17:04:59 CET 2007


vito muggeo wrote:
> Dear all,
> I have the following (rather) strange problem..
> For some reasons, I finally work with a variable whose name includes an 
> R function, "a.log(z)", say. And that is a problem when I call it in a 
> formula, for instance:
>
>  > myname<-"a.log(z)"
>  > dd<-data.frame("a.log(z)"=1:10,y=rnorm(10))
>  > o<-lm(y~1,data=dd)
>  > fo<-as.formula(paste(".~.+",paste(myname, collapse = "+")))
>  > fo
> . ~ . + a.log(z)
>  > update(o,formula=fo)
> Error in eval(expr, envir, enclos) : could not find function "a.log"
>  >
>
> How can fit the model? namely how can I use "a.log(z)" in the example above?
>
> Many thanks,
> vito
>
>
>   
Use backquotes as in `a.log(z)`, I think.

myname<-"a.log(z)"
o<-lm(y~1,data=dd)
dd<-data.frame("a.log(z)"=1:10,y=rnorm(10),check.names=F)
fo<-as.formula(paste(".~.+",paste(deparse(as.name(myname), backtick=T),
collapse = "+")))
update(o,formula=fo)

or, actually nicer, use

fo <- bquote(. ~ . + .(as.name(myname)))


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