Search code examples
revalemmeans

How to evaluate a string variable as factor in the emmeans() command in R?


I would like to assign a variable with a custom factor from an ANOVA model to the emmeans() statement. Here I use the oranges dataset from R to make the code reproducible. This is my model and how I would usually calculate the emmmeans of the factor store:

library(emmeans) 
oranges$store<-as.factor(oranges$store)
model <- lm (sales1 ~ 1 + price1 + store ,data=oranges)
means<-emmeans(model, pairwise  ~ store, adjust="tukey")

Now I would like to assign a variable (lsmeanfact) defining the factor for which the lsmeans are calculated.

lsmeanfact<-"store"

However, when I want to evaluate this variable in the emmeans() function it returns an error, it basically does not find the variable lsmeanfact, so it does not evaluate this variable.

means<-emmeans(model, pairwise  ~ eval(parse(lsmeanfact)), adjust="tukey")
Error in emmeans(model, pairwise ~ eval(parse(lsmeanfact)), adjust = "tukey") : 
  No variable named lsmeanfact in the reference grid

How should I change my code to be able to evaluate the variable lsmeanfact so that the lsmeans for "plantcode" are correctly calculated?


Solution

  • You can make use of reformulate function.

    library(emmeans)
    lsmeanfact<-"store"
    
    means <- emmeans(model, reformulate(lsmeanfact, 'pairwise'), adjust="tukey")
    

    Or construct a formula with formula/as.formula.

    means <- emmeans(model, formula(paste('pairwise', lsmeanfact, sep = '~')), adjust="tukey")
    

    Here both reformulate(lsmeanfact, 'pairwise') and formula(paste('pairwise', lsmeanfact, sep = '~')) return pairwise ~ store.