If I have a string that contains line breaks, how can I code it in R without manually adding \n
between lines and then print it with the line breaks? There should be multiple lines of output; each line of the original string should print as a separate line.
This is an example of how to do the task in Python:
string = """ Because I could Not stop for Death He gladly stopped for me """
Example use case: I have a long SQL code with a bunch of line breaks and sub-commands. I want to enter the code as a single string to be evaluated later, but cleaning it up by hand would be difficult.
The easiest way to create a multi-line comment in RStudio is to highlight the text and press Ctrl + Shift + C. You can just as easily remove the comment by highlighting the text again and pressing Ctrl + Shift + C.
There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.
While you can use the \n escape character to put a newline into a string, it is often easier to use multiline strings. A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.
Special Characters in Strings The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.
Nothing special is needed. Just a quote mark at the beginning and end.
In R:
x = "Because I could Not stop for Death He gladly stopped for me" x # [1] "Because I could\nNot stop for Death\nHe gladly stopped for me" cat(x) # Because I could # Not stop for Death # He gladly stopped for me
In Python:
>>> string = """ ... Because I could ... Not stop for Death ... He gladly stopped for me ... """ >>> string '\n\tBecause I could\n\tNot stop for Death\n\tHe gladly stopped for me\n'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With