35

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.

4
  • 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, 2017 at 20:50
  • 2
    You can write that SQL to file and read it from R Oct 18, 2017 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, 2017 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, 2021 at 22:09

1 Answer 1

46

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'
1
  • Between this, and Michal Stolarczyk's comment above, consider this question answered. Thanks!
    – mmyoung77
    Oct 18, 2017 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.