我需要创建一个函数(fit.function
),该函数根据MASS(nb.glm
)的负二项模型调用具有不同公式和数据的lsmeans。
当我尝试在函数中调用lsmeans时出现以下错误:
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
似乎错误与ref.grid函数的环境有关。
有人可以帮我修复错误吗?有任何解决方法吗?
我的代码如下:
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)