Search code examples
rfunctionmethodsevalr-s4

An argument working outside a function but fails inside a function in R


When outside a function, argument pbkrtest.limit = nobs(m1) below works just fine (thus, no message is generated).

But when inside the foo() function, nobs(m1) is not recognized (thus, a message is generated)! I'm really wondering what is going on?

library(lme4)
library(emmeans)
dat <- read.csv('https://raw.githubusercontent.com/hkil/m/master/z.csv')

m1 <- lmer(y~ year*group + (1|stid), data = dat)

## WORKS FINE:
emtrends(m1, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m1)) 


## BUT NOW `nobs(m)` doesn't work inside the function:
foo <- function(m){

 emtrends(m, pairwise ~ group, var = "year", infer = c(T, T), pbkrtest.limit = nobs(m))
}

## RUN:
foo(m = m1)

Solution

  • Try evaluating it in the parent.frame:

    foo <- function(m, envir = parent.frame()) {
      s <- substitute(emtrends(m, pairwise ~ group, var = "year", infer = c(TRUE, TRUE), 
        pbkrtest.limit = nobs(m)))
      eval(s, envir)
    }
    
    foo(m = m1)
    

    and report it to the developer at https://github.com/rvlenth/emmeans/issues

    Also use TRUE rather than T because T can be overridden but TRUE cannot be.