How about:
l <- lm(y~.,data=data.frame(X,y=Y))
pred <- predict(l,data.frame(X_new))
In this case R constructs the column names (X1
... X20
) automatically, but when you use the y~.
syntax you don't need to know them.
Alternatively, if you are always going to fit linear regressions based on a matrix, you can use lm.fit()
and compute the predictions yourself using matrix multiplication: you have to use cbind(1,.)
to add an intercept column.
fit <- lm.fit(cbind(1,X),Y)
all(coef(l)==fit$coefficients) ## TRUE
pred <- cbind(1,X_new) %*% fit$coefficients
(You could also use cbind(1,X_new) %*% coef(l)
.) This is efficient, but it skips a lot of the error-checking steps, so use it with caution ...