knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(linearReg)
This function is used to build linear models. It can be used to carry out both simple linear regression (SLR) and multiple linear regression (MLR). The companion function summary_linearReg is used to print out the coefficients and other statistic.
To use the function, you need to do prepare two data sets. One for the outcome data (Y), other for the predictor data(X). Both data sets can be vectors or a matrices. For instance:
Y = c(2,3,4,5) X = c(1.1, 2.2, 2.9, 3.9) model1 = linearReg(Y,X)
We can check the result of above SLR model using summary_linearReg()
:
summary_linearReg(model1)
We can also use matrices to build a MLR model. Note that the function can not build multi-covariate model, i.e. Y matrix can not have more than 1 colomn. In such case, the function will stop and print an error message. For instance:
set.seed(7) X = matrix(rnorm(100), 50, 2) Y = matrix((X[,1]+ 3*X[,2] + rnorm(50,sd=2)), 100, 2) try(linearReg(Y,X))
The correct using:
set.seed(7) X = matrix(rnorm(100), 50, 2) Y = matrix((X[,1]+ 3*X[,2] + rnorm(50,sd=2)), 50, 1) model1 = linearReg(Y,X)
Similarly, we use summary_linearReg to print out the model:
summary_linearReg(model1)
If you want to combine predictors from different X matrices, use cbind()
to combine them into one X matrix first. User are responsible to check each colomn of X are orthogonal. For instance:
set.seed(7) X1 = rnorm(100) X2 = rnorm(100) Y = X1+ 3*X2 + rnorm(100,sd=2) X= cbind(X1,X2) model2 = linearReg(Y,X) summary_linearReg(model2)
mm = bench::mark(lm(Y~X1+X2)$coefficients, linearReg(Y,X)$coefficients) mm #plot(mm)
The simlified linearReg()
function is around five times faster than the original lm()
function.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.