19

I am trying to suppress warnings by using the suppressWarnings() function.

Surprisingly, it removes warnings when used normally, but it fails to do so when you use the pipe %>% operator.

Here is some example code :

library(magrittr)

c("1", "2", "ABC") %>% as.numeric()
# [1]  1  2 NA
# Warning message:
# In function_list[[k]](value) : NAs introduced by coercion

c("1", "2", "ABC") %>% as.numeric() %>% suppressWarnings
# [1]  1  2 NA
# Warning message:
# In function_list[[i]](value) : NAs introduced by coercion

suppressWarnings(c("1", "2", "ABC") %>% as.numeric())
# [1]  1  2 NA

Why does it work with parenthesis but not with pipe operator ? Is there a specific syntax I should use to make it work ?

Axeman
  • 32,068
  • 8
  • 81
  • 94
Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92
  • 5
    Another workaround could be `c("1", "2", "ABC") %>% {suppressWarnings(as.numeric(.))}` – talat Sep 15 '17 at 12:35
  • 7
    I don't expect there is a way to do what you are trying to do. The pipe operator takes the object returned by the preceding call and pushes it forward to the succeeding call. Warnings are not part of the objects; they are cast when they occur, and cannot be passed from one function to the next. I think the most readable solution is to wrap `suppressWarnings` around the full chain of calls. – Benjamin Sep 15 '17 at 12:47
  • I guess you would have same problem with `try` (to capture errors) – Cath Sep 15 '17 at 12:50
  • I think @Benjamin answers the first question very well and thus make the second one irrelevant. Thanks sir ! – Dan Chaltiel Sep 15 '17 at 12:58
  • if occurring in an RMarkdown script, you could add `warning = FALSE` to the chunk options. – Sam Firke May 04 '18 at 16:35

1 Answers1

19

One solution would be to use the %T>% pipes to modify options (from magrittr, not included in dplyr!)

c("1", "2", "ABC") %T>% {options(warn=-1)} %>% as.numeric() %T>% {options(warn=0)}

You could also use purrr::quietly, not so pretty in this case...

library(purr)
c("1", "2", "ABC") %>% {quietly(as.numeric)}() %>% extract2("result")
c("1", "2", "ABC") %>% map(quietly(as.numeric)) %>% map_dbl("result")

for the sake of completeness, here are also @docendo-discimus 's solution and OP's own workaround

c("1", "2", "ABC") %>% {suppressWarnings(as.numeric(.))} 
suppressWarnings(c("1", "2", "ABC") %>% as.numeric())

And I'm stealing @Benjamin's comment as to why the original try doesn't work :

Warnings are not part of the objects; they are cast when they occur, and cannot be passed from one function to the next

EDIT:

The linked solution will allow you to just write c("1", "2", "ABC") %W>% as.numeric

Custom pipe to silence warnings

Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167