Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading