Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lavResidualsY (a re-imagining of "casewise" residuals) #269

Open
jebyrnes opened this issue Mar 8, 2023 · 1 comment
Open

lavResidualsY (a re-imagining of "casewise" residuals) #269

jebyrnes opened this issue Mar 8, 2023 · 1 comment

Comments

@jebyrnes
Copy link

jebyrnes commented Mar 8, 2023

Given the existence of lavPredictY() we can easily write a function lavResidualsY() to get residuals of observed variables.

lavResidualsY <- function(object,
                          ynames = lavNames(object, "ov.nox"),
                          xnames = lavNames(object, "ov.x")){
  pred <- lavPredictY(object,
                      ynames = ynames,
                      xnames = xnames) |> 
    as.data.frame()
  
  d <- inspect(object, "data") |> 
    as.data.frame()

  r <- lapply(names(pred), function(x){
    pred[[x]] - d[[x]]
  })

  res <- do.call(cbind, r) |> 
    as.data.frame()
  names(res) <- names(pred)
  
  res
}

mod <- "
rich ~ cover + firesev 
firesev ~ age
"

f <- sem(mod, data = piecewiseSEM::keeley) 

#let's get residuals and then do a test for MV normality
r <- lavResidualsY(f)

mvnormtest::mshapiro.test(t(r))

This should also work with LV models, but might take a bit more - e.g.,

lavResidualsY(fit, ynames = c("y5", "y6", "y7", "y8"),
            xnames = c("x1", "x2", "x3", "y1", "y2", "y3", "y4"))
@jebyrnes
Copy link
Author

jebyrnes commented Mar 8, 2023

(and you can un-pipe it if you want. I'm just a pipe fan.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants