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