循环使用lavaan语法的列名组合

时间:2019-02-25 09:13:51

标签: r loops automation purrr r-lavaan

使用lavaan进行中介分析时,如何遍历包含变量名排列的数据框的行?

假设我有4个变量var1var2var3var4

df<- data.frame(var1 = rnorm(100), 
                var2 = rnorm(100), 
                var3 = rnorm(100),
                var4 = rnorm(100))

使用gtools::permutations()将4个变量的所有可能排列保存为3组:

permut <- 
  gtools::permutations(n = 4, r = 3, v = names(df), repeats.allowed = FALSE)

colnames(permut) <- c("Y", "X", "M")

> head(permut)
     Y      X      M     
[1,] "var1" "var2" "var3"
[2,] "var1" "var2" "var4"
[3,] "var1" "var3" "var2"
[4,] "var1" "var3" "var4"
[5,] "var1" "var4" "var2"
[6,] "var1" "var4" "var3"

然后,我使用lavaan语法设置冥想模型,我对MXY之间的关系的中介作用感兴趣:

mod <- "
    M ~ a * X
    Y ~ c * X + b * M
    ind := a*b
    tot := c + (a*b)
    "

我想运行模型并存储其结果以供将来检查:

library(lavaan)
library(dplyr)

#fit the model
fit <- sem(mod, df, se = "robust")

#save results
result <-
parameterestimates(fit) %>% filter(op != "~~")

我的问题是这样:

如何指示 R 用作Y,X,M每行中的permut变量名,使用df中的数据和{ {1}}并最终存储每个适合模型的结果?

上面的代码是我想用于以相同方式运行更复杂的模型的最简单的方案。

我知道有关循环循环使用以下变量的线性模型的答案:loop over all possible combinationsLooping over combinations of regression model termsLinear Regression loop for each independent variable individually against dependent,还有可能是最接近的变量:How to use reference variables by character string in a formula?,但我仍然陷入困境,周末无法解决这个问题。

1 个答案:

答案 0 :(得分:1)

这是一种方法:

fits <- apply(permut, 1, function (p) {
    permuted.df <- df[p]
    colnames(permuted.df) <- names(p)
    sem(mod, permuted.df, se="robust")
})

fits包含permut中每3个排列的SEM结果。要查看例如首次拟合的估算值,您可以照常进行:

> parameterestimates(fits[[1]]) %>% filter(op != "~~")
  lhs op     rhs label         est         se          z     pvalue    ci.lower
1   M  ~       X     a -0.18393765 0.10977670 -1.6755618 0.09382406 -0.39909603
2   Y  ~       X     c  0.07314372 0.09891034  0.7394952 0.45960637 -0.12071699
3   Y  ~       M     b  0.01944518 0.08852450  0.2196587 0.82613697 -0.15405965
4 ind :=     a*b   ind -0.00357670 0.01600038 -0.2235385 0.82311644 -0.03493686
5 tot := c+(a*b)   tot  0.06956702 0.09816192  0.7086966 0.47851276 -0.12282680
    ci.upper
1 0.03122074
2 0.26700443
3 0.19295001
4 0.02778346
5 0.26196084