34

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.

user438383
  • 5,716
  • 8
  • 28
  • 43
mmyoung77
  • 1,343
  • 3
  • 14
  • 22
  • yes, I'm aware of using `\n`, but I would prefer not to have to add that for every line of this very long SQL script. No other option? – mmyoung77 Oct 18 '17 at 20:50
  • 2
    You can write that SQL to file and read it from R – Michał Stolarczyk Oct 18 '17 at 20:51
  • Do you want to add line breaks or remove them? Would single quotes be what you want, i.e. `'` indtead of `"`? – emilliman5 Oct 18 '17 at 20:52
  • I submitted an edit to clarify that the question is not about how to break a character string over multiple lines of code without introducing line breaks into the string. However, I was unsure whether the question intended to include how to print a string that contains line breaks (which the accepted answer covers) or only how to code the string without manually adding "\n" between lines. The Python example seems to only do the 2nd. I was also unsure if “to be evaluated later” imposed some additional constraint that printing does not. – randy Dec 20 '21 at 22:09

1 Answers1

45

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'
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294