简体   繁体   English

从R中的lavaan列表矩阵中提取残值

[英]Extracting residual values from lavaan list matrices in R

I am using lavaan package and my intention is to get my model residuals as dataframes for further use. 我正在使用lavaan软件包,我的目的是将模型残差作为数据框获取以供进一步使用。 I run several models that have grouping variables. 我运行了几个具有分组变量的模型。 Here's the basic workflow: 这是基本的工作流程:

require(lavaan)
df <- data.frame(
        y1 = sample(1:100),
        y2 = sample(1:100),
        x1 = sample(1:100),
        x2 = sample(1:100),
        x3 = sample(1:100),
        grpvar = sample(c("grp1","grp2"), 100, replace = T))
semModel <- list(length = 2)
semModel[1] <- 'y1 ~ c(a,b)*x1 + c(a,b)*x2'
semModel[2] <- 'y1 ~ c(a,b)*x1 
                y2 ~ c(a,b)*x2 + c(a,b)*x3'
funEstim <- function(model){
    sem(model, data = df, group = "grpvar", estimator = "MLM")}
fits <- lapply(semModel, funEstim)
residuals <- lapply(fits, function(x) resid(x, "obs"))

Now the resulting residuals object bugs me. 现在,产生的残差对象使我烦恼。 It is a list of matrices that is nested few times. 它是嵌套几次的矩阵列表。 How do I get each of the matrices as a separate dataframe without any hardcoding? 我如何在没有任何硬编码的情况下将每个矩阵作为一个单独的数据帧? I don't want to unlist them as that would lose some information. 我不想取消列出他们,因为那样会丢失一些信息。

You can use list2env along with unlist to make the grp1 , grp2 , length.grp1 , and length.grp2 directly available in the global environment. 您可以使用list2env随着unlist ,使grp1grp2length.grp1length.grp2在全球环境中直接可用。

list2env(unlist(residuals, recursive=FALSE), envir=.GlobalEnv)
ls()
#[1] "df"          "fits"        "funEstim"    "grp1"        "grp2"       
#[6] "length.grp1" "length.grp2" "residuals"   "semModel"

But they won't be data frames. 但是它们不会是数据帧。 For that you could convert them to data frames before calling list2env : 为此,您可以在调用list2env之前将它们转换为数据帧:

df.list <- lapply(unlist(residuals, recursive=FALSE), data.frame)
list2env(df.list, envir=.GlobalEnv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM