The dev.off function in grDevices doesn't restore the previous graphics device when called. This function does.

safe.dev.off(which = dev.cur(), prev = dev.prev())

Arguments

which

Which device to close.

prev

Which device to set as current after closing.

Details

This function closes device which if it is not device 1, then calls dev.set(prev) if there are any devices still open.

Value

The number and name of the new active device. It will not necessarily be prev if that device isn't already open.

Author

Duncan Murdoch

Examples

# Open a graphics device
dev.new()
first <- dev.cur()

# Open a second graphics device
dev.new()
second <- dev.cur()
second
#> agg_png 
#>       4 

# Open another one, and close it using dev.off()
dev.new()
dev.off()
#> agg_png 
#>       2 
dev.cur() == second # Not the same as second!
#> agg_png 
#>   FALSE 

# Try again with safe.dev.off()
dev.set(second)
#> agg_png 
#>       4 
dev.new()
safe.dev.off()
#> agg_png 
#>       4 
dev.cur() == second
#> agg_png 
#>   FALSE 

# Close the other two devs
safe.dev.off()
#> agg_png 
#>       4 
safe.dev.off()
#> agg_png 
#>       4