[R] First Variable in lm

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Mar 24 18:03:44 CET 2004


On Wed, 24 Mar 2004, Christian Hoffmann wrote:

> Hi all,
> 
> I just cannot think of how to do it:
> I want to take the first variable (column) of a data frame and regress 
> it against all other variables.
> 
> bla <- function (dat) {
>    reg <- lm(whateverthefirstofthevariablenamesis ~., data=dat)
>    return(reg)
> }
> 
> What kind of function do I have to take instead of the 
> whateverthefirstofthevariablenamesis,
> 
> eval(), substitute(), get(),  ...
> 
> to correctly compute this regression?
> 
> With   lm(get(names(dat)[1] ~., data=dat) there are no errors, but the 
> first variable also shows up among the regressors.

Andy Liaw has pointed out that lm(dat) happens to work.  But for a more 
generalizable solution try

bla <- function (dat)
  eval(substitute(lm(foo ~., data=dat), list(foo=as.name(names(dat)[1]))))

which has the advantage of embedding a clean value of $call.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list