Search code examples
rwarnings

Using cat() inside warning() puts the message before the warning


I used cat() to create a warning message, but in the result the warning message comes before the "Warning message:" part. Is there a different way to create this warning message so that it is printed after "Warning message:"?

This is what the output looks like:

> acceptable_classes <- c(
+   "character", 
+   "gg", 
+   "ggplot", 
+   "data.frame", 
+   "flextable"
+ )
> 
> # This prints the correct way:
> if(TRUE){
+   warning("Some result is not an acceptable class.")
+ }
Warning message:
Some result is not an acceptable class. 
> 
> # This prints backwards:
> if(TRUE){
+   warning(
+     cat(
+       "Some result is not an acceptable class.",
+       "Acceptable classes are:", 
+       acceptable_classes, 
+       sep = "\n"
+     )
+   )
+ }
Some result is not an acceptable class.
Acceptable classes are:
character
gg
ggplot
data.frame
flextable
Warning message:

Solution

  • As mentioned in comments, you should avoid using cat, use paste instead, for example:

    acceptable_classes <- letters[1:5]
    
    if(TRUE){
      warning(
        paste(
          "Some result is not an acceptable class.",
          "Acceptable classes are:", 
          paste(acceptable_classes, collapse = ", "), 
          sep = "\n"
        )
      )
    }
    

    The result is:

    Warning message:
    Some result is not an acceptable class.
    Acceptable classes are:
    a, b, c, d, e