首页 > 解决方案 > 使用 as.factor() 自变量的中介分析

问题描述

我正在尝试进行调解分析,但我的 IV 中有一个因素。这似乎导致了一些问题。这是一个例子:

data(iris)
library(mediation)
ols.0 <- lm(Sepal.Length ~ Petal.Length + as.factor(Species), data = iris)

ols.med <- lm(Sepal.Width ~ Petal.Length + as.factor(Species), data = iris)

ols.y <- lm(Sepal.Length ~ Petal.Length + Sepal.Width + as.factor(Species), data = iris)

results1 <- mediate(ols.med, ols.y, treat="Petal.Length", mediator="Sepal.Width", boot=TRUE, sims=500)

所以我可以很好地运行 lm() 命令,但是当我运行 mediate() 命令时,我收到以下错误消息:

Running nonparametric bootstrap

Error in is.factor(x) : object 'Species' not found

运行 mediate() 命令时有没有办法处理因子变量,或者是否有我应该考虑的替代包/方法?

标签: rmediator

解决方案


最好创建as.factor外部,因为这可能会更改call属性名称。如果我们想使用as.factor里面的formula,将它包裹起来I或者在属性中进行更改

iris$Species <- as.factor(iris$Species)
ols.0 <- lm(Sepal.Length ~ Petal.Length + Species, data = iris)

ols.med <- lm(Sepal.Width ~ Petal.Length + Species, data = iris)

 ols.y <- lm(Sepal.Length ~ Petal.Length + Sepal.Width + Species, data = iris)

results1 <- mediate(ols.med, ols.y, treat="Petal.Length", 
       mediator="Sepal.Width", boot=TRUE, sims=500)



str(results1)
List of 56
 $ d0           : num 0.129
 $ d1           : num 0.129
 $ d0.ci        : Named num [1:2] 0.0642 0.21
  ..- attr(*, "names")= chr [1:2] "2.5%" "97.5%"
 $ d1.ci        : Named num [1:2] 0.0642 0.21
  ..- attr(*, "names")= chr [1:2] "2.5%" "97.5%"
 $ d0.p         : num 0
 $ d1.p         : num 0
 $ d0.sims      : num [1:500, 1] 0.111 0.137 0.197 0.116 0.215 ...
 $ d1.sims      : num [1:500, 1] 0.111 0.137 0.197 0.116 0.215 ...
 $ z0           : num 0.776
 $ z1           : num 0.776
 $ z0.ci        : Named num [1:2] 0.636 0.907
# ..

推荐阅读