Skip to content

Instantly share code, notes, and snippets.

@jeromyanglim
Last active July 26, 2023 17:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeromyanglim/9f766e030966eaa1241f10bd7d6e2812 to your computer and use it in GitHub Desktop.
Save jeromyanglim/9f766e030966eaa1241f10bd7d6e2812 to your computer and use it in GitHub Desktop.
Function that allows you to run a linear model on a covariance matrix using lavaan
# see
# http://stackoverflow.com/questions/20203485/why-is-source-gist-function-in-r-devtools-package-not-working
covlm <- function(dv, ivs, n, cov) {
# Assumes lavaan package
# library(lavaan)
# dv: charcter vector of length 1 with name of outcome variable
# ivs: character vector of names of predictors
# n: numeric vector of length 1: sample size
# cov: covariance matrix where row and column names
# correspond to dv and ivs
# Return
# list with lavaan model fit
# and various other features of the model
results <- list()
eq <- paste(dv, "~", paste(ivs, collapse = " + "))
results$fit <- lavaan::sem(eq, sample.cov = cov,
sample.nobs = n)
# unstandardised coefficients
ufit <- parameterestimates(results$fit)
ufit <- ufit[ufit$op == "~", ]
results$coef <- ufit$est
names(results$coef) <- ufit$rhs
sfit <- standardizedsolution(results$fit)
sfit <- sfit[sfit$op == "~", ]
results$standardizedcoef <- sfit$est.std
names(results$standardizedcoef) <- sfit$rhs
# use unclass to not limit r2 to 3 decimals
results$r.squared <- as.numeric(unclass(inspect(results$fit, 'r2'))) # r-squared
# adjusted r-squared
adjr2 <- function(rsquared, n, p) 1 - (1-rsquared) * ((n-1)/(n-p-1))
results$adj.r.squared <- as.numeric(adjr2(unclass(inspect(results$fit, 'r2')),
n = n, p = length(ivs)) )
results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment