1

I am calling the lmer function from the lme4 package. The function works if I hard code the column names. If I refer to it as a variable, though, it throws an error. My ultimate goal is to call a string that includes '+' between each column name.

Here is an example lmer call:

colnames(df)
COL_A, COL_B, COL_D

This works:

output <- lmer(COL_A ~ 1 + COL_B + 1|COL_D, df, REML = FALSE, verbose = TRUE)

This does not:

var_a <- COL_A
var_b <- COL_B
var_c <- COL_D

output <- lmer(var_a ~ 1 + var_b + 1|var_c, df, REML = FALSE, verbose = TRUE)

Error that comes up:

Error in model.frame.default(data = df, drop.unused.levels = TRUE,  : 
  variable lengths differ (found for 'var_b')

If this can be figured out it would be awesome.

My ultimate goal though is to call the function as a string, so something like this:

form_lmer<-"COL_A ~ 1 + COL_B + 1|COL_D"

output <- lmer(form_lmer, df, REML = FALSE, verbose = TRUE)

Has anyone encountered this sort of thing before?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
nak5120
  • 4,089
  • 4
  • 35
  • 94
  • Does [this](https://stackoverflow.com/a/46616150/6574038) help? – jay.sf May 22 '18 at 17:25
  • 2
    `output <- lmer(as.formula(form_lmer), df, REML = FALSE, verbose = TRUE)`? – Tung May 22 '18 at 17:31
  • Did you mean `var_a <- "COL_B"` or `var_a <- df$COL_B` or something else? `var_a <- COL_B` will only work if there's already a `COL_B` variable living in your global environment ... – Ben Bolker May 22 '18 at 17:53
  • By the way, your final specification (in terms of `form_lmer`) does actually work, although I wouldn't recommend it ... – Ben Bolker May 22 '18 at 17:56
  • @BenBolker why ? – denis May 22 '18 at 17:58
  • it's a little bit safer to make the formula an actual formula, which has an appropriate environment associated with it. There's a small chance that something weird could happen downstream. (I think we've fixed most of those edge cases, but I'm never 100% sure ...) – Ben Bolker May 22 '18 at 18:05
  • @Tung can you please put yours as an answer? That worked great. – nak5120 May 22 '18 at 18:22
  • Actually @Tung, I'm getting an error in the last part for 1|COL_D in the formula – nak5120 May 22 '18 at 18:32
  • Error in parse(text = x, keep.source = FALSE) : :1:50: unexpected numeric constant – nak5120 May 22 '18 at 18:33
  • @nak5120: can you share your data using `dput()` so folks can actually test – Tung May 22 '18 at 18:43
  • nevermind figured out the issue, dumb mistake. Can you put that as an answer please the: `output <- lmer(as.formula(form_lmer), df, REML = FALSE, verbose = TRUE)` – nak5120 May 22 '18 at 20:12

1 Answers1

0

You can do

output<-lmer(paste0(var_a, "~ 1 + ",var_b," + 1|",var_c), df, REML = FALSE, verbose = TRUE)
denis
  • 5,580
  • 1
  • 13
  • 40
  • I would recommend `form <- reformulate(c(var_b,sprintf("(1|%s)",var_c)),response=var_a)`; not particularly different, but maybe a little more elegant. – Ben Bolker May 22 '18 at 18:06