0

I get the following error:

Error in UseMethod("lme") : 
  no applicable method for 'lme' applied to an object of class "character"

when running my code:

outcome = "Score"
exposures_fixed = c("Age", "Sex","BMI")
coefficients = c()
for (k in 1:length(exposures_fixed) { 
  fix_exp = exposures_fixed [k]
  Formula = paste0(outcome,"~", fix_exp)
  mixed_model= lme(fixed = Formula, random = ~1|ID, data = DB,
                   na.action = na.omit, method = "ML")
  coef = mixed_model$coefficients$fixed[2]
  coefficients = rbind(coefficients, coef)
}

I guess the problem is that Formula is a string, not a real formula. How can I fix this?

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
Sari Katish
  • 180
  • 7
  • 1
    Does this answer your question? [how to loop over string variable in R](https://stackoverflow.com/questions/73224548/how-to-loop-over-string-variable-in-r) – user438383 Aug 07 '22 at 17:07

1 Answers1

3

At the moment you have a string

Formula = paste0(outcome, "~", fix_exp)

To coerce it to a formula, you can use

formula(Formula)

Alternatively, you can directly construct a formula using

reformulate(fix_exp, outcome)

Lesson Learned: lm and glm can handle a formula in string format, but lme can't.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248