1

I need to make a function (fit.function) that calls lsmeans with different formulas and data based on a negative binomial model fit from MASS (nb.glm).

I get the following error when I try to call lsmeans inside the function:

Error in terms.formula(formula, data = data) : 
'data' argument is of the wrong type
Error in ref.grid(object = list(coefficients = c(1.69377906086784, 
2.30790181649084,  : 
Perhaps a 'data' or 'params' argument is needed

It seems like the error has something to do with the environment of the ref.grid function.

Could anyone help me to fix the error? Any idea for a workaround?

My code is as follows:

library(lsmeans)
library(MASS)
df1 <-data.frame(y=rnbinom(100,size=0.75,mu =5 ), x="A")
df2 <-data.frame(y=rnbinom(100,size=0.75,mu =50 ), x="B")
df3 <-data.frame(y=rnbinom(100,size=0.75,mu =500 ), x="C")

df <- rbind(df1,df2,df3)

nb.fit<-function(formula,data){
  glm.nb(formula,data=data)
}

fit.function <- function(formula, data){
  lsmeans(glm.nb(formula, data = data), "x", adjust = "tuckey")
}

# lsmeans are calcultated when both lsmeans and glm.nb are explicitly called
main.fit <- lsmeans(glm.nb(y ~ x,data=df), "x", adjust = "tuckey")
main.fit

CLD <- cld(main.fit, type= "response")
plot(CLD)

# no problem wrapping glm.nb into nb.fit
class(glm.nb(y ~ x,df))
nb.model <-nb.fit(y ~ x,df)
class(nb.model)

# The Error appears once I wrap lsmeans into fit.function

func.fit <- fit.function(y ~ x,df)
faustovrz
  • 71
  • 4
  • You might need a `assign(data, .GlobalEnv)` in your function - similar problems arise with nls and others. – Remko Duursma Sep 13 '17 at 01:29
  • Try what the error message suggests: adding the data as an argument to your function, and adding `data = data` to the `lsmeans` call. – Russ Lenth Sep 13 '17 at 13:05
  • Thank you @RemkoDuursma and @rvl both suggestions worked, I'll pass the `data` argument to lsmeans instead of making a global variable. – faustovrz Sep 13 '17 at 17:42
  • BTW, you always need to pass the data argument when using glm.nb models. That is documented in ?models. – Russ Lenth Sep 16 '17 at 14:24

0 Answers0