#' Gives variance inflation factors for a linear model or data frame of covariates
#'
#' \code{vifs(X, digits = 3)}
#'
#' @param X is the name of a linear model with 2+ explanatory variables or a
#' data frame comprising covariates.
#' @param digits is the number of decimal places to display
#'
#' @details Returns variance inflation factors for explanatory variables in a
#' linear model. Produces the same values as the `vif()` function in car
#' package.
#'
#' @examples
#' Mod1 = lm(mpg ~ ., data=mtcars)
#' vifs(Mod1,2)
#' vifs(mtcars[,-1],2)
vifs = function (X, digits = 3)
{
if(class(X)!="lm" & class(X)!="data.frame")
stop("requires either a linear model or a data frame of covariates as input")
if(class(X) == "lm"){
VN = variable.names(X)[-1]
DF = X$model[VN]
}
if(class(X) == "data.frame"){
VN = names(X)
DF = X
}
# Drop non-numeric variables:
S = unname(sapply(DF,FUN = class))
DF = DF[,which(S == "numeric" | S == "integer")]
VN = names(DF)
LEN = length(VN)
if (LEN < 2)
stop("requires a model with more than one explanatory variable")
M = numeric(LEN)
i = 1
for (a in VN) {
DF = DF[c(a, VN[VN != a])]
Lmod = lm(DF)
M[i] = 1/(1 - summary(Lmod)$r.squared)
i = i + 1
}
M = as.matrix(round(M, digits), nc = 1)
rownames(M) = VN
colnames(M) = "vif"
print(M)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.