4

I have a script that essentially boils down to

model <- lm(d$o ~ d$t * d$w)
plot(model)

When I run these commands in interactive mode (RStudio), plot will create four graphs. The user has to advance to the next graph by pressing enter.

Now, I want to run the commands in (almost) non-interactive mode and the plot command to display only the first two graphs. The user of the script of course should still be required to mouse click or press enter after the R environment has displayed the first and second graph.

How could I achieve this?

Edit

It has been suggested that I use the which parameter (being described in ?plot.lm). Yet, if I change the respective line to

plot(model, which=1)

the script aborts with

Error in box(...) : invalid 'which' argument
Calls: plot -> plot.default -> localBox -> box
In addition: Warning messages:
1: In plot.window(...) : "which" is not a graphical parameter
2: In plot.xy(xy, type, ...) : "which" is not a graphical parameter
3: In axis(side = side, at = at, labels = labels, ...) :
  "which" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
  "which" is not a graphical parameter
Execution halted
René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293
  • 2
    Probably `which` argument of `plot`. –  Jul 03 '15 at 07:13
  • 1
    ...as described in the very first sentence in the help text: "Six plots (selectable by `which`)". – Henrik Jul 03 '15 at 07:25
  • Yes, right, that is in `?plot.lm` of which I was hitherto unaware. Thanks for pointing me to this direction. – René Nyffenegger Jul 03 '15 at 07:29
  • Do you get the error if you run the command interactively? Alternatively, you could plot things "manually" yourself. For example, the residual plot can be done by `plot(model$fitted.values, model$residuals, xlab = "Fitted Values", ylab = "Residuals", type = "n"); panel.smooth(model$fitted.values, model$residuals, col = "red"); points(model$fitted.values, model$residuals); abline(h = 0, lty = 3, col = "grey") `. Look at `str(model)` for all the elements in the `lm` object and `getAnywhere(plot.lm)` to see how the function is doing each plot. (not very straighforward, but might get you there...) – hugot Jul 03 '15 at 08:07
  • Your `plot` call dispatches to `plot.default`, whereas it should to `plot.lm`. Probably your `model` object is not of class `lm` somehow. Try `plot.lm` directly? – tonytonov Jul 03 '15 at 08:20

2 Answers2

4

Try this:

plot(model, which=1:2). 

This has worked for me.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
1

We don't know your data. But this works!

n=50
d=data.frame(o=rnorm(n,10,3),t=1:n,w=rep(c("A","B","C"),length.out=n))
model <- lm(d$o ~ d$t * d$w)
plot(model)
op=par(mfrow=c(2,2))
for(i in 1:4)plot(model, which=i)
par(op)

enter image description here

Robert
  • 5,038
  • 1
  • 25
  • 43