Question

Here is some code that tries to compute the marginal effects of each of the predictors in a model (using the effects package) and then plot the results. To do this, I am looping over the "term.labels" attribute of the glm terms object).

library(DAAG)
library(effects)

formula = pres.abs ~ altitude + distance + NoOfPools + NoOfSites + avrain + meanmin + meanmax
summary(logitFrogs <- glm(formula = formula, data = frogs, family = binomial(link = "logit")))


par(mfrow = c(4, 2))
for (predictorName in attr(logitFrogs$terms, "term.labels")) {
    print(predictorName)
    effLogitFrogs <- effect(predictorName, logitFrogs)
    plot(effLogitFrogs)
}

This produces no picture at all. On the other hand, explicitly stating the predictor names does work:

effLogitFrogs <- effect("distance", logitFrogs)
plot(effLogitFrogs)

What am I doing wrong?

Was it helpful?

Solution

Although you call function plot(), actually it calls function plot.eff() and it is lattice plot and so par() argument is ignored. One solution is to use function allEffects() and then plot(). This will call function plot.efflist(). With this function you do not need for loop because all plots are made automatically.

effLogitFrogs <- allEffects(predictorName, logitFrogs)
plot(effLogitFrogs)

EDIT - solution with for loop

There is "ugly" solution to use with for() loop. For this we need also package grid. First, make as variables number of rows and columns (now it works only with 1 or 2 columns). Then grid.newpage() and pushViewport() set graphical window.

Predictor names are stored in vector outside the loop. Using functions pushViewport() and popViewport() all plots are put in the same graphical window.

  library(lattice)
  library(grid)

  n.col=2
  n.row= 4 
  grid.newpage()      
  pushViewport(viewport(layout = grid.layout(n.row,n.col)))

  predictorName <- attr(logitFrogs$terms, "term.labels")

  for (i in 1:length(predictorName)) {
    print(predictorName[i])
    effLogitFrogs <- effect(predictorName[i], logitFrogs)
    pushViewport(viewport(layout.pos.col=ceiling(i/n.row), layout.pos.row=ifelse(i-n.row<=0,i,i-n.row)))
    p<-plot(effLogitFrogs)
    print(p,newpage=FALSE)
    popViewport(1)
  }

OTHER TIPS

add print to your loop resolve the problem.

 print(plot(effLogitFrogs))

plot call plot.eff , which create the plot without printing it.

allEffects generete an object of type eff.list. When we try to plot this object, its calls plot.efflist function which prints the plot so no need to call print like plot.eff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top