77

How do I use the new line character in R?

myStringVariable <- "Very Nice ! I like";

myStringVariabel <- paste(myStringVariable, "\n", sep="");

The above code DOESN'T work

P.S There's significant challenges when googling this kind of stuff since the query "R new line character" does seem to confuse google. I really wish R had a different name.

Aaron Hall
  • 291,450
  • 75
  • 369
  • 312
MadSeb
  • 7,118
  • 17
  • 72
  • 117
  • 11
    That's why [RSeek](http://www.rseek.org/) is there! – nico Feb 16 '12 at 19:38
  • 4
    What is the output you're wanting? does `cat(paste('first line','\n','new line'))` do what you're expecting? R doesn't parse strings unless you ask it to. also [this SO post](http://stackoverflow.com/questions/4071586/printing-newlines-with-print-in-r) – Justin Feb 16 '12 at 19:39
  • 3
    'newline' is one word. Should help your googling. – smci Apr 08 '14 at 00:10

3 Answers3

162

The nature of R means that you're never going to have a newline in a character vector when you simply print it out.

> print("hello\nworld\n")
[1] "hello\nworld\n"

That is, the newlines are in the string, they just don't get printed as new lines. However, you can use other functions if you want to print them, such as cat:

> cat("hello\nworld\n")
hello
world
David Robinson
  • 71,331
  • 13
  • 150
  • 174
9

Example on NewLine Char:

for (i in 1:5)
  {
   for (j in 1:i)
    {
     cat(j)
    }
    cat("\n")
  }

Result:

    1
    12
    123
    1234
    12345
John Hascall
  • 8,682
  • 4
  • 46
  • 64
Areya
  • 101
  • 1
  • 2
8

You can also use writeLines.

> writeLines("hello\nworld")
hello
world

And also:

> writeLines(c("hello","world"))
hello
world
abalter
  • 7,589
  • 12
  • 75
  • 118