1

I have a function for ploting like this:

f <- function(x,y){  

  for (i in 1:10){

    png(getwd(), height=1500, width=500)
    plot(x,y)
    dev.off()
  }
}

everything is all right when I use: f(2,3) but if I use f(2,"a") then the function is breaking before dev.off()

I can place on.exit(dev.off(), add=T) on the begening of the function but then in normal execution I will dev.off() too much 1 time.

I think the solution is to put sth like this to the function:

 on.exit(if(dev != NULL) dev.off(), add=T)

but how to check that dev != NULL ?

4
  • how to use that dev.list() This doesnt work: on.exit(if(exists(dev.list()) == T){ dev.off()}, add=T) Commented Mar 31, 2017 at 15:23
  • OK, on.exit(if(is.null(dev.list()) == F){ dev.off()}, add=T) this is OK ? Commented Mar 31, 2017 at 15:25
  • a is nothing, f(2,a) should return mistake. Commented Mar 31, 2017 at 15:29
  • while (!is.null(dev.list())) dev.off() Commented Dec 10, 2018 at 23:35

1 Answer 1

1

Simply use the following technique:

if (length(dev.list()!=0) {dev.off()}

this is actually an efficient technique to check the returning values of many other functions too, for instance, to check if grep finds something:

if(length(grep("me","I am not here"))==0) {print("not found")}

hope it helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Where would you put the missing ) in your first line? It seems to me that if (length(dev.list()!=0)) and if (length(dev.list())!=0) (before and after !=0) gives the same result.
In fact, do we need to do the !=0? The if function interprets the output of length as a boolean. E.g. length(1:3) will return TRUE.
I missed putting the second close parenthesis in the If section after !=0 which should be exactly!=0))
This was a trick litterally independent of the output type of function as it works out by checking the length of output. So, if you need to check an actual value then it won’t work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.