1

Possible Duplicate:
Formula with dynamic number of variables

I'm fitting a linear model with many variables and would like to automatically generate a dynamic string following the form of the lm() function in R ("Y ~ X1 + ... + Xn"). The idea is to plug-in the string into the lm() formula so don't have to write down all the names manually.

Also I would like set the name of the response variable so it's identified and included in the first place of the string (" Y ~ ...")

Is this possible? I'm playing with the "state.x77" data set. Let's say I want to use as a response the "Life Exp" variable.

    state.x77                            
    str(state.x77)                       
    st = as.data.frame(state.x77)
n=ncol(st) 
Community
  • 1
  • 1
nopeva
  • 1,547
  • 2
  • 21
  • 35

1 Answers1

2
names(st) <- make.names(names(st))
y <- "Life.Exp"
x <- names(st)[!names(st) %in% y]
x
y
mymodel <- as.formula(paste(y, paste(x, collapse="+"), sep="~"))
lm(mymodel, data=st)
  • I suppose that the third line set all names except the response, could you please briefly explain that? – nopeva Dec 30 '12 at 11:18