[R] lm with an arbitrary number of terms
John Fox
jfox at mcmaster.ca
Thu Apr 3 00:21:45 CEST 2003
Dear Richard,
At 05:49 PM 4/2/2003 +0100, Richard Nixon wrote:
>Any ideas how to do this?
>
>data.frame is a data frame with column names "x1",...,"xn"
>y is a response variable of length dim(data.frame)[1]
>
>I want to write a function
>
>function(y, data.frame){
> lm(y~x1+...+xn)
>}
>
>This would be easy if n was always the same.
>If n is arbitrary how could I feed the x1+...+xn terms into
>lm(response~terms)?
If y contains the *name* of the response variable, which is also in the
data frame, then the following should work:
fun <- function(y, df){
lm(as.formula(paste(y, "~.")), data=df)
}
Alternatively, if y is a vector and is not in the data frame, then you
might try
fun <- function(y, df){
df <- data.frame(y, df)
lm(y~., data=df)
}
I hope that this helps,
John
____________________________
John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
web: http://www.socsci.mcmaster.ca/jfox
More information about the R-help
mailing list