object not found in mediation model

51 Views Asked by At

I have to plan a simple mediation model - https://cran.r-project.org/package=mediation

library(mediation)

mediation_model = lm(as.numeric(Age) ~ as.numeric(condition), data = GRA)
tab_model(mediation_model)

model = lm(as.numeric(note) ~ as.numeric(condition) + as.numeric(Age), data = GRA)
tab_model(model)

result <- mediate(mediation_model,model,sims = 120,mediator="as.numeric(Age)",treat="as.numeric(condition)",boot = TRUE)

And it generates this error:

Running nonparametric bootstrap

Error in eval(predvars, data, env) : object 'Age' not found

I taped 'manes(GRA)' and I found 'Age'. The lm works well, I don't know where the mistake is.

1

There are 1 best solutions below

0
r2evans On

I'll formalize the comments.

Any steps you perform on the data within the formula are not carried forward for any post-model analysis. This means that when you run mediate, the versions of note, condition, and Age are their original class within your GRA data; the coefficients in model suggest that they should be numeric, but number-like operations are not working.

As a counter-point, in many ML and forecasting (in R) pipelines, the "feature engineering" or pre-conditioning steps are recorded in a sense, so that when you apply that ML/forecasting model to new data, the steps are repeated on the new data. This is a novel and great way to handle modeling, but unfortunately lm and friends are not based on that architecture.

(Disclaimer: I don't know mediate and don't have it installed, I'm not speaking to the correctness of your regression or its use.)

Convert the columns into a frame (either overwriting GRA or saving to a new frame, GRA2 below), and then don't worry about as.numeric(.) in either of your calls to lm(.) or mediate(.) (or any other model-using function):

GRA2 <- GRA |>
  transform(
    note = as.numeric(note),
    condition = as.numeric(condition),
    Age = as.numeric(Age)
  )
mediation_model = lm(Age ~ condition, data = GRA2)
model = lm(note ~ condition + Age, data = GRA2)
result <- mediate(mediation_model, model, sims = 120,
                  mediator="Age", treat="condition", boot = TRUE)

Also, there are other ways to convert those three columns, this is just one. My point is not that you must use transform, feel free to use whatever R code you want to pre-convert the three columns into a frame, and then use that frame in calls to lm and mediate.