R:在用户自定义函数中使用中介时出现未定义的列错误

时间:2019-05-18 15:08:25

标签: r

我正在使用R的mediation包进行一系列中介分析。因为模型彼此非常相似,所以我写了一个函数 将会发生变化的是中介变量,结果变量和数据集。该功能如下:

    library(mediation)
    data("framing", package = "mediation")
    covList <- list("age", "educ", "gender", "income")

    meBrokenFunction <- function(MEDIATOR, OUTCOME, DATA) {

      treatOnMed <- lm(DATA[[MEDIATOR]] ~ treat + age + educ + gender + income, data = DATA)

      medOnOut <- glm(DATA[[OUTCOME]] ~ DATA[[MEDIATOR]] + treat + age + educ + gender + income, data = DATA, family = binomial("probit"))

      expt <- mediate(treatOnMed, medOnOut, sims = 100, 
                      treat = "treat", mediator = MEDIATOR, 
                      covariates = covList, robustSE = TRUE)
      expt
    }  
    set.seed(2019)
    test_first <- meBrokenFunction("emo", "cong_mesg", framing)

运行此函数时,出现以下错误:

Error in `[.data.frame`(y.data, , mediator) : undefined columns selected 

但是,如果我在不使用编写的函数的情况下运行代码,则一切都会按预期进行。

test_treatOnMed <- lm(emo ~ treat + age + educ + gender + income, 
                        data = framing)
test_treatOnOut <- glm(cong_mesg ~ treat + age + educ + gender + income,
                        data = framing, family = binomial("probit"))
test_medOnOut <- glm(cong_mesg ~ emo + treat + age + educ + gender + income,
                        data = framing, family = binomial("probit"))

test_second <- mediate(test_treatOnMed, test_medOnOut, sims = 100, 
                  treat = "treat", mediator = "emo", 
                  covariates = covList, robustSE = TRUE)

该错误似乎在中介函数中,尤其是在mediator = MEDIATOR处,但我不明白为什么它不起作用或我是否错误地解决了问题。

1 个答案:

答案 0 :(得分:0)

在公式中,我们可能需要paste而不是DATA[[MEDIATOR]]

lm(paste(MEDIATOR,  "~ treat + age + educ + gender + income"), data = DATA)

类似地glm

-完整代码

meFixedFunction <- function(MEDIATOR, OUTCOME, DATA) {

      treatOnMed <- lm(paste(MEDIATOR,  
          "~ treat + age + educ + gender + income"), data = DATA)

      medOnOut <- glm(paste(OUTCOME, "~", MEDIATOR,
         "+ treat + age + educ + gender + income"), data = DATA, 
             family = binomial("probit"))

      expt <- mediate(treatOnMed, medOnOut, sims = 100, 
                      treat = "treat", mediator = MEDIATOR, 
                      covariates = covList, robustSE = TRUE)
      expt
    }  

-测试

set.seed(2019)
test_first <- meFixedFunction("emo", "cong_mesg", framing)