Suppress custom dplyr warnings while allowing other warnings through

I have a function in a package that I want to call in a dplyr grouped mutate call (inside another function). The function has a tryCatch statement in it because some errors are expected, and I want to turn them into warnings. The problem is that when a function inside mutate() generates a warning, it also triggers a dplyr warning (helpfully indicating in which group the error occured) which I would like to suppress in this case. Here is a contrived toy example:

library(dplyr, warn.conflicts = FALSE)

dat <- data.frame(a = letters[1:3], b = 1:3)

user_facing_function <- function(x) {
  x %>% 
    group_by(a) %>% 
    mutate(b2 = make_b2(b))  
}

make_b2 <- function(x) {
  tryCatch(if (x > 2) stop() else x*2,
           error = function(e) {
             warning("This is the only warning I want", call. = FALSE)
             NA_real_
           })
}

user_facing_function(dat)

#> # A tibble: 3 x 3
#> # Groups:   a [3]
#>   a         b    b2
#>   <chr> <int> <dbl>
#> 1 a         1     2
#> 2 b         2     4
#> 3 c         3    NA
#> Warning message:
#>   Problem with `mutate()` input `b2`.
#> ℹ This is the only warning I want
#> ℹ Input `b2` is `make_b2(b)`.
#> ℹ The error occurred in group 3: a = "c"

<sup>Created on 2021-02-17 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0)</sup>

Is there a way to turn off the dplyr-generated warning messages and just have my custom warning message?

Thanks in advance!
Andy

So far the best I have come up with is to also wrap the mutate call in tryCatch to capture and edit the warning message with regex... but that seems really inelegant.

Hi,

If you don't mind the "warning" message being before the output, you can just transform the warning into a message. Same colour, but no other warnings...

library(dplyr, warn.conflicts = FALSE)

dat <- data.frame(a = letters[1:3], b = 1:3)

user_facing_function <- function(x) {
  x %>% 
    group_by(a) %>% 
    mutate(b2 = make_b2(b))
}

make_b2 <- function(x) {
  tryCatch(if (x > 2) stop() else x*2,
           error = function(e) {
             message("This is the only warning I want")
             NA_real_
           })
}

user_facing_function(dat)
#> This is the only warning I want
#> # A tibble: 3 x 3
#> # Groups:   a [3]
#>   a         b    b2
#>   <chr> <int> <dbl>
#> 1 a         1     2
#> 2 b         2     4
#> 3 c         3    NA

Created on 2021-02-18 by the reprex package (v1.0.0)

PJ

Thanks @pieterjanvc - I do want to keep it as a warning.

I decided to work around this by checking for the error condition and throw the warning outside of the mutate() call

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.