我在 R 中进行中介分析。我的中介是一个二元变量,因此model.m
由glm
.
set.seed(2022)
data = data.frame(ID = as.character(seq(1,100,1)),group = seq(1,100,1),
iris[1:100,],day1 = rnorm(100), day2 = rnorm(100), day3 = rnorm(100))
data$med = as.factor(ifelse(data$Petal.Width>0.3&data$Petal.Width<1.2,1,0))
data_long <- data %>%
pivot_longer(cols = day1:day3, names_to = "day", values_to = "y") %>%
mutate(day = as.numeric(gsub("day", "", day))) %>%
dplyr::select(ID, day, Sepal.Length, everything()) %>%
as.data.frame(.)
formula <- as.formula(Sepal.Length ~ Species + med + Petal.Length + Sepal.Width + day + (day | group))
out.fit <- lme4::lmer(formula = formula,
data = data_long,
control = lme4::lmerControl(optimizer = "bobyqa",
optCtrl = list(maxfun = 2e5)))
formula_2 <- as.formula(med ~ Species + Petal.Length + Sepal.Width)
med.fit <- glm(formula = formula_2,
data = data,
family = "binomial")
result <- mediate(med.fit, out.fit, treat = "Species",
treat.value = "setosa", control.value = "versicolor",
mediator = "med",
sims = 100)
但是,在我运行上面的代码之后,我不断收到错误:
Error in factor(PredictMt, levels = 1:m, labels = m.levels) :
object 'm' not found
我查看了原始源代码,发现m.levels
源代码中应该是一个变量,并且没有一个名为m
. 换句话说,m
不应该是一个对象。我不明白为什么程序将其识别m
为对象。
此外,代码在连续调解器上运行得很好。以下代码有效:
formula <- as.formula(Sepal.Length ~ Species + Petal.Width + Petal.Length + Sepal.Width + day + (day | group))
out.fit <- lme4::lmer(formula = formula,
data = data_long,
control = lme4::lmerControl(optimizer = "bobyqa",
optCtrl = list(maxfun = 2e5)))
formula_2 <- as.formula(Petal.Width ~ Species + Petal.Length + Sepal.Width)
med.fit <- lm(formula = formula_2,
data = data)
result <- mediate(med.fit, out.fit, treat = "Species",
treat.value = "setosa", control.value = "versicolor",
mediator = "Petal.Width",
sims = 100)