Francis Smart
Francis Smart

Reputation: 4055

Supress single warning/error message

I would like to prevent a function from warning me.

>for (v in c("1", "a2", "aaa", 10)) 
  if (is.na(as.numeric(v))) 
    cat("\nWarning:", paste(v, "cannot be coerced into a number"))

Warning: a2 cannot be coerced into a number
Warning: aaa cannot be coerced into a number
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion

I would like only my warnings to be displayed: Warning: a2 cannot be coerced into a number and Warning: aaa cannot be coerced into a number.

I assume there are two ways to do this.
1. Override the warning that R uses. 2. Suppress the warning that R uses.

Help with either would be informative but I am more interested in suppressing the warning system.

Thanks for any help you can provide! Francis

Upvotes: 3

Views: 221

Answers (1)

bartektartanus
bartektartanus

Reputation: 16080

Here you go:

for (v in c("1", "a2", "aaa", 10)) 
    if (is.na(suppressWarnings(as.numeric(v))))
        warning(paste(v, "cannot be coerced into a number"))

suppressWarnings evaluates expression and ignores warnings.

warning generates your own warning :)

Upvotes: 3

Related Questions