4

I am running an ordinary R script in which I have a self-written function. The function makes use of rm() which often produces warnings I do not want to appear in console output. Any of these solutions:

  1. hiding warnings from rm usage from this particular self-written function,
  2. hiding warnings from all usages of rm (globally for an R session)

would satisfy me.

foo.function <- function(){
  rm(foo.object)
  print("foo")
}

foo.function()
# [1] "foo"
# Warning message:
# In rm(foo.object) : object 'foo.object' not found
Marta Karas
  • 4,967
  • 10
  • 47
  • 77
  • 3
    Did you try using `suppressWarnings()`? – talat Mar 15 '16 at 17:33
  • Of course I did not :( That is correct, thank you! – Marta Karas Mar 15 '16 at 17:35
  • 1
    You could do something like `if( length(ls(pattern = 'foo.object')) == 1 ) rm(foo.object)`. – steveb Mar 15 '16 at 17:36
  • That is correct too, however the `suppressWarnings()` is more convenient for me as I have more than one object to be (potentially) removed. – Marta Karas Mar 15 '16 at 17:38
  • `suppressMessages()` can also be useful at times, as can the (ill-advised) global suppression `options(warn=-1)`. See: http://stackoverflow.com/questions/16194212/how-to-suppress-warnings-globally-in-an-r-script – dmp Mar 15 '16 at 17:42
  • 1
    it might be better to `tryCatch` warnings that you _expect_ and print those that maybe you have overlooked or dont foresee. or suppresswarnings if you dont care – rawr Mar 15 '16 at 18:01

1 Answers1

3

For these particular case of object not found, you may use something like this:

if(exists("foo.object")) rm(foo.object)

If you want to hide other warnings as well, just use suppressWarnings().