calc_lm | R Documentation |
Perform multivariate linear regression using least squares and return a named list of regression coefficients, their t-values, and p-values.
calc_lm(respv, predm)
respv |
A single-column time series or a vector of response data. |
predm |
A time series or a matrix of predictor data. |
The function calc_lm()
performs the same calculations as the
function lm()
from package stats.
It uses RcppArmadillo
C++
code so it's several times faster
than lm()
. The code was inspired by this article (but it's not
identical to it):
http://gallery.rcpp.org/articles/fast-linear-model-with-armadillo/
A named list with three elements: a matrix of coefficients (named "coefficients"), the z-score of the last residual (named "zscore"), and a vector with the R-squared and F-statistic (named "stats"). The numeric matrix of coefficients named "coefficients" contains the alpha and beta coefficients, and their t-values and p-values.
## Not run:
# Calculate historical returns
retp <- na.omit(rutils::etfenv$returns[, c("XLF", "VTI", "IEF")])
# Response equals XLF returns
respv <- retp[, 1]
# Predictor matrix equals VTI and IEF returns
predm <- retp[, -1]
# Perform multivariate regression using lm()
regmod <- lm(respv ~ predm)
regsum <- summary(regmod)
# Add unit intercept column to the predictor matrix
predm <- cbind(rep(1, NROW(predm)), predm)
# Perform multivariate regression using calc_lm()
regarma <- HighFreq::calc_lm(respv=respv, predm=predm)
# Compare the outputs of both functions
all.equal(regarma$coefficients[, "coeff"], unname(coef(regmod)))
all.equal(unname(regarma$coefficients), unname(regsum$coefficients))
all.equal(unname(regarma$stats), c(regsum$r.squared, unname(regsum$fstatistic[1])))
# Compare the speed of RcppArmadillo with R code
summary(microbenchmark(
Rcpp=HighFreq::calc_lm(respv=respv, predm=predm),
Rcode=lm(respv ~ predm),
times=10))[, c(1, 4, 5)] # end microbenchmark summary
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.