Home > OS >  Capturing warning message into a variable in RR
Capturing warning message into a variable in RR

Time:10-15

I have a function draw_plot() that takes in a data frame and other parameters(through the ellipsis) and simply returns a line plot.

draw_plot <- function(data, ...){
  plot <- ggplot(data = data, mapping = aes(x = x, y = y))
  plot <- plot   do.call("geom_line", c(list(...)))
  return(plot)}


data <- tibble::tibble(x = c(1,2,3,4,5,6), y = c(5,6,7,8,9,10))
draw_plot(data, test = 2, wrong = "")

If I call the function as above, with parameters with key values which the geom_line() function doesn't recognize, it returns a warning saying 'Ignoring unknown parameters: test, wrong'.

I am hoping to improve the function to facilitate more parameters, and other ggplot geoms. (ex: draw_plot(data, stat, ...)) The stat parameter will not be valid for geom_line(). Therefore I want to capture the original warning message and append 'stat' to it. ex: 'Ignoring unknown parameters: test, wrong, stat'

To do this, is there any way that I can capture this particular warning message into a variable? p.s. I am trying to stick to base R to do this.

CodePudding user response:

Here is how you can capture the warning message -

draw_plot <- function(data, ...){
  plot <- ggplot(data = data, mapping = aes(x = x, y = y))
  plot <- tryCatch(plot   do.call("geom_line", c(list(...))), 
                   warning = function(w) {
      if(grepl('Ignoring unknown parameters', w$message)) 
        wmsg <<- as.character(w$message)
      return(NULL)
    })
  if(exists('wmsg')) print(wmsg)
  return(plot)
}
draw_plot(data, test = 2, wrong = "")
draw_plot(data)
  •  Tags:  
  • r
  • Related