在lavaan中具有交互作用的类别变量的编码效果?

时间:2019-07-10 12:54:20

标签: r r-lavaan

我对将lm语法转换为lavaan感兴趣,特别是当因子具有时,在因子x数字变量之间进行了效应编码交互之后> 2个级别。 (提醒:effects-coding是伪编码类别变量的替代方法,例如代码为-1、1和0。)

下面您将看到一个最小的示例(无意义)。您将看到lm(线性回归)语法,然后看到相应的lavaan语法(回归部分)。它适用于没有交互但不具有交互的回归。

首先考虑具有效应编码因子的无交互回归。

这有效

library(lavaan)
# Use iris data as minimal example
# 
# 1. Linear regression model
# Change contrasts to effects-coding
contrasts(iris$Species) <- contr.sum(3)
# Linear regression
lmmodel <- Sepal.Length ~ Species # the regression model
lmfit <- lm(lmmodel, iris) # fit it

# 2. SEM
# first, re-code the factors
iris$s1 <- contrasts(iris$Species)[iris$Species, 1] # Numeric and effects-coed
iris$s2 <- contrasts(iris$Species)[iris$Species, 2] #     - " -
semmodel <- 'Sepal.Length ~ s1 + s2' # the SEM model
semfit <- sem(semmodel, iris) # fit it

# 3. Compare the coefficients lm vs. sem, should be equal (and are equal)
cbind(coef(lmfit)[-1], coef(semfit)[-length(coef(semfit))])
#                 [,1]        [,2]
# Species1 -0.83733333 -0.83733330
# Species2  0.09266667  0.09266664

这是我如何通过互动进行操作 我要去哪里错了?

# 1. Linear regression w/ interaction
lmmodel <- Sepal.Length ~ Species + Species:Sepal.Width
lmfit <- lm(lmmodel, iris)

# 2. SEM
iris$s3 <- as.numeric(iris$Species=='virginica') # Code third species
iris$s1_w <- iris$s1 * iris$Sepal.Width # Numeric interaction
iris$s2_w <- iris$s2 * iris$Sepal.Width #      - " -
iris$s3_w <- iris$s3 * iris$Sepal.Width #      - " -"
semmodel <- 'Sepal.Length ~ s1 + s2 + s1_w + s2_w + s3_w'
semfit <- sem(semmodel, iris)

# 3. Compare the coefficients lm vs. sem
cbind(coef(lmfit)[-1], coef(semfit)[-length(coef(semfit))])
#                                     [,1]       [,2]
# Species1                      -0.7228562 -0.7228566
# Species2                       0.1778772  0.1778772
# Speciessetosa:Sepal.Width      0.6904897  0.6904899
# Speciesversicolor:Sepal.Width  0.8650777  0.8650779  <----- equal
# Speciesvirginica:Sepal.Width   0.9015345  2.4571023  <----- not equal

1 个答案:

答案 0 :(得分:0)

问题不在于 lavaan,您只是没有正确编码 Virginica Species 的对比:

enter image description here

从第 101 行到第 150 行,您应该有 0,0,1,即:

iris[101:150,"s2_w"] <- 0
iris[101:150,"s1_w"] <- 0

重新运行原始代码:

semmodel <- 'Sepal.Length ~ s1 + s2 + s1_w + s2_w + s3_w'
semfit <- sem(model = semmodel, data = iris, estimator="ml")

# 3. Compare the coefficients lm vs. sem
cbind(coef(lmfit)[-1], coef(semfit)[-length(coef(semfit))])

并检查:

(¬_¬)# 3. Compare the coefficients lm vs. sem
(¬_¬)cbind(coef(lmfit)[-1], coef(semfit)[-length(coef(semfit))])
                                    [,1]       [,2]
Species1                      -0.7228562 -0.7228563
Species2                       0.1778772  0.1778772
Speciessetosa:Sepal.Width      0.6904897  0.6904898
Speciesversicolor:Sepal.Width  0.8650777  0.8650778
Speciesvirginica:Sepal.Width   0.9015345  0.9015345