Suppose I have a response variable and a data containing three covariates (as a toy example):
y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
I want to fit a linear regression to the data:
fit = lm(y ~ d$x1 + d$x2 + d$y2)
Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like
fit = lm(y ~ d)
(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc
.
There is a special identifier that one can use in a formula to mean all the variables, it is the
.
identifier.You can also do things like this, to use all variables bar one:
Technically,
.
means all variables not already mentioned in the formula. For examplewhere
.
would only referencex3
asx1
andx2
are already in the formula.An extension of juba's method is to use
reformulate
, a function which is explicitly designed for such a task.For the example in the OP, the easiest solution here would be
or
Note that adding the dependent variable to the data.frame in
d <- cbind(y, d)
is preferred not only because it allows for the use ofreformulate
, but also because it allows for future use of thelm
object in functions likepredict
.Yes of course, just add the response
y
as first column in the dataframe and calllm()
on it:Also, my information about R points out that assignment with
<-
is recommended over=
.I build this solution,
reformulate
does not take care if variable names have white spaces.```
A slightly different approach is to create your formula from a string. In the
formula
help page you will find the following example :Then if you look at the generated formula, you will get :
You can check the package
leaps
and in particular the functionregsubsets()
functions for model selection. As stated in the documentation:Model selection by exhaustive search, forward or backward stepwise, or sequential replacement