Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple-line strings in R?

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.

like image 406
mmyoung77 Avatar asked Oct 18 '17 20:10

mmyoung77


People also ask

How do you write multiple lines in R?

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.

How can you create multi line strings?

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.

Can strings have multiple lines?

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.

How do I print to the next line in R?

Special Characters in Strings The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.


1 Answers

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' 
like image 127
Gregor Thomas Avatar answered Sep 21 '22 22:09

Gregor Thomas