Search code examples
rwarningsr-package

How do you format a multiline R message with linebreaks?


Based on this excellent question and replies, I learned you could use message(strwrap(<some message>)) to make the messages in the R package you write flow in the IDE nicely. But how do I go a step beyond reflow to a somewhat formatted message?

The accepted answer there suggests

message(strwrap(prefix = " ", initial = "", 
  "If you got to this point in the code, it means 
the matrix was empty. Calculation continues but you should consider
 re-evaluating an earlier step in the process"))

Which solves the OP's concern about maintaining spaces at newlines. But what if I wanted "Calculation continues" to actually start a new line, perhaps with a hard return between?


Solution

  • As indicated in the comments, adding initial = "\n" means new sentences begin on a new line:

    message(strwrap(prefix = "\n", initial = "", 
                    "If you got to this point in the code, it means 
    the matrix was empty. Calculation continues but you should consider
     re-evaluating an earlier step in the process"))
    

    outputting:

    If you got to this point in the code, it means the matrix was empty.
    Calculation continues but you should consider re-evaluating an earlier step in
    the process
    

    To add a hard return, one option is to add two newlines with "\n\n") in the message string:

    message(strwrap(prefix = "\n", initial = "", 
                    "If you got to this point in the code, it means 
    the matrix was empty.\n\nCalculation continues but you should consider
     re-evaluating an earlier step in the process"))
    

    outputting:

    If you got to this point in the code, it means the matrix was empty.
    
    Calculation continues but you should consider re-evaluating an earlier step in
    the process