[R] First Variable in lm

Christian Hoffmann christian.hoffmann at wsl.ch
Thu Mar 25 08:44:56 CET 2004


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

Thanks to all who answered my question:

Prof. Brian Ripley:
-------------------
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.

andy_liaw at merck.com:
--------------------
lm(formula = dat)


rolf at math.unb.ca:
-----------------
for(j in 1:ncol(dat)) {
	fff <- as.formula(paste(names(dat)[j],"~",
                           paste(names(dat)[-j],collapse="+")))
	nm <- paste("rslt",j,sep=".")
	assign(nm,lm(fff,data=dat))
}


ggrothendieck at myway.com
-----------------------
data(longley)
lm( longley[,7] ~. , data = longley[,-7] )

You cannot call data() inside a function:
   data(dat)
   reg <- lm(dat[,1] ~ dat[,-1])
Error in model.frame(formula, rownames, variables, varnames, extras, 
extranames,  :
	invalid variable type
In addition: Warning message:
Data set 'dat' not found in: data(dat)


Regards
Christian
-- 
Dr.sc.math.Christian W. Hoffmann, 
http://www.wsl.ch/staff/christian.hoffmann
Mathematics + Statistical Computing   e-mail: christian.hoffmann at wsl.ch
Swiss Federal Research Institute WSL  Tel: ++41-44-73922-   -77  (office)
CH-8903 Birmensdorf, Switzerland             -11(exchange), -15  (fax)




More information about the R-help mailing list