简体   繁体   中英

How can I plot an interaction in R when using a negative binomial model?

I'm new to R. I used a negative binomial model to test the effects of 2 variables (1 binary variable and 1 continuous variable) and a count response variable. I also added their interaction to the model.

Since the results from the glm.nb is minimal, I would like to plot the result somehow, especially the interaction.

I've done this to run the model:

Y<- cbind(N_Cooperations)
Model8 <- glm.nb(Y ~ Condition + NR + Condition*NR)
summary(Model8)

Call:
glm.nb(formula = Y ~ Condition + NR + Condition * NR, init.theta = 2.012332023, 
    link = log)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.2063  -0.9508  -0.1757   0.3389   2.5682  

Coefficients:
             Estimate Std. Error z value Pr(>|z|)   
(Intercept)    1.5379     0.6920   2.222  0.02626 * 
Condition     -2.9514     1.0876  -2.714  0.00665 **
NR            -0.1470     0.2065  -0.712  0.47654   
Condition:NR   0.7771     0.3170   2.451  0.01423 * 
---

Then I tried to use plot(allEffects(Model8)) from the effects package to plot the interaction, but this is the message I received:

plot(allEffects(Model8))
Error in mod.matrix[, components] : subscript out of bounds
In addition: Warning messages:
1: In factor.cols & stranger.cols :
  longer object length is not a multiple of shorter object length
2: In (!factor.cols) & stranger.cols :
  longer object length is not a multiple of shorter object length

What am I missing?

Again, I'm very new to R. Sorry in advance if this sounds silly.

Most likely you have some other variables in your environment that is throwing the error. It would be useful if you place all your variables into a data.frame. It works for me with an example dataset:

library(MASS)
library(effects)

set.seed(111)
df = data.frame(Y = rnbinom(100,mu=10,size=1),
NR = runif(100),Condition=rbinom(100,1,0.5))

fit = glm.nb(Y ~ Condition*NR,data=df)

The interaction term is specified using : and this * is used for factor crossing. See help page if you are unclear. Below I can do the summary and we get a similar output to yours:

summary(fit)

Call:
glm.nb(formula = Y ~ Condition * NR, data = df, init.theta = 1.19503151, 
    link = log)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-2.3798  -1.0970  -0.2340   0.4323   2.0848  

Coefficients:
             Estimate Std. Error z value Pr(>|z|)    
(Intercept)    1.4744     0.2978   4.952 7.36e-07 ***
Condition      0.9414     0.3973   2.369   0.0178 *  
NR             1.0294     0.5003   2.058   0.0396 *  
Condition:NR  -0.9773     0.6809  -1.435   0.1512   

Plotting it works:

plot(allEffects(fit))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM