0

if just for two independent variables, we have

X1=rnorm(n=3, mean=4, sd=2)
X2=rnorm(n=3, mean=2, sd=1)
e=rnorm(n=3, mean=0, sd=1)
Y=5+2*X1+3*X2+e
M=data.frame(Y, X1, X2)
My_lm= lm(Y~X1+X2, data=M)

The issue is writing the program that can compute any number of X's and not a fixed number of independent variables.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

3

Just use the . symbol within your formula and this will take care of all the independent variables:

eg

My_lm= lm(Y ~ ., data = M)
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

You can use reformulate to construct the formula dynamically.

response <- 'Y'
My_lm <- lm(reformulate(setdiff(names(M), response), response), data = M)

Here reformulate returns :

reformulate(setdiff(names(M), response), response)
#Y ~ X1 + X2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213