"object not found" error in mediation analysis in R

I am doing mediation analysis in R. My mediator is a binary variable, so model.m is run by 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)

However, after I ran the above piece of code, I kept getting error:

Error in factor(PredictMt, levels = 1:m, labels = m.levels) : object 'm' not found

I checked the original source code and found that m.levels in the source code should be a variable and there isn't an object called m. In other words, m should not be an object. I don'r understand why the program recognize m as an object.

Also, the code runs totally fine on the continuous mediator. The following code works:

    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)

Solution 1:

I found the crux of the issue:

In mediate.R, you can find "For binary response models, the 'mediator' must be a numeric variable with values 0 or 1 as opposed to a factor."

After I added data$med = as.numeric(data$med)-1, problem solved.