[R] pass lm( ) a char vector as the variables to be included

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Nov 26 17:09:20 CET 2007


On Mon, 2007-11-26 at 14:17 +0000, Richard.Cotton at hsl.gov.uk wrote:
> > Here are the codes of the example of lm( ):
> > 
> > ## Annette Dobson (1990) "An Introduction to
> > Generalized Linear Models".
> > ## Page 9: Plant Weight Data.
> > ctl <-
> > (4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
> > trt <-
> > (4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
> > group <- gl(2,10,20, labels=c("Ctl","Trt"))
> > weight <- c(ctl, trt)
> > anova(lm.D9 <- lm(weight ~ group))
> > lm.D90 <- lm(weight ~ group - 1) # omitting intercept
> > 
> > What I am doing is let the variable name "group"
> > stored in a vector, say, g <- "group". The question is
> > how to strip the quotation marks when we call lm( )
> > through g?
> 
> Try: 
> w = "weight"
> g = "group"
> form = as.formula(paste(w,g,sep="~"))
> lm(form)
> 
> Regards,
> Richie.

For more complicated automation, the ideas and examples from Bill
Venables Programmer Niche article in the R newsletter from a few years
ago might be of use:

[39] Bill Venables. Programmer's niche. R News, 2(2):24-26, June 2002.
[ bib | PDF | http ]

The PDF is available here:

http://cran.r-project.org/doc/Rnews/Rnews_2002-2.pdf

HTH

G

> 
> Mathematical Sciences Unit
> HSL
> 
> 
> ------------------------------------------------------------------------
> ATTENTION:
> 
> This message contains privileged and confidential inform...{{dropped:20}}
> 
> ______________________________________________
> R-help at r-project.org 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.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list