Tae-Sung Shin
Tae-Sung Shin

Reputation: 20620

How to pause for each plot when running R function

First, you need effects and lme4 packages to run the scripts below with

library(effects)
library(lme4)

I have following script

 devAskNewPage(ask=TRUE)

 fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), sleepstudy,
          REML = 0, verbose = TRUE)
 plot(effect("Day",fm8))
 qqmath(ranef(fm8))

If I run the script manually, R asks Click or ENTER for next page after each graph. But when I run following function,

somefunc<-function () 
{
 devAskNewPage(ask=TRUE)
 fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), sleepstudy,
          REML = 0, verbose = TRUE)
 plot(effect("Day",fm8))
 qqmath(ranef(fm8))

}

R only asks Click or ENTER for next page for the last plot. How can I make it ask for each plot in the function?

Upvotes: 2

Views: 2371

Answers (1)

joran
joran

Reputation: 173737

If plotting them together is acceptable, you might try this:

library(gridExtra)
somefunc<-function () 
{
 fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), sleepstudy,
          REML = 0, verbose = TRUE)
 p1 <- plot(effect("Day",fm8))
 p2 <- qqmath(ranef(fm8))$Subject
 class(p1) <- 'trellis'
 grid.arrange(p1,p2,nrow = 2)
}

The effects package messes with the class of the resulting plot, the confuses grid.arrange, so I had to change it back. I feel like grid.arrange ought to be more clever about that.

I can only speculate as to what's going wrong with devAskNewPage. The effect plotting code is pretty elaborate. It's quite possible that it is manipulating the graphics device in a way that overrides that setting.

Edit

I'm a bit surprised, but Ben Bolker's comment is right (i.e. this is a version/example of R FAQ 7.22, "Why do lattice/trellis graphics not work?", because the effects package calls lattice::xyplot internally). This works as the OP's asked:

somefunc<-function () 
{
 devAskNewPage(ask=TRUE)
 fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), sleepstudy,
          REML = 0, verbose = TRUE)
 p1 <- plot(effect("Day",fm8))
 p2 <- qqmath(ranef(fm8))$Subject
 print(p1)
 print(p2)
}

Upvotes: 4

Related Questions