146

I am trying to print a multiline message in R. For example,

print("File not supplied.\nUsage: ./program F=filename",quote=0)

I get the output

File not supplied.\nUsage: ./program F=filename

instead of the desired

File not supplied.
Usage: ./program F=filename
highBandWidth
  • 16,751
  • 20
  • 84
  • 131

5 Answers5

154

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • 1
    Both `writelines` and 'cat` doesn't seem to write to a variable. I was trying to create a string variable with multiple lines. `stringvar <- writeLines("line1\nline2")` doesn't assign. `stringvar ` returns still null Any alternative? – sjd Aug 12 '20 at 15:52
30

You can do this:

cat("File not supplied.\nUsage: ./program F=filename\n")

Notice that cat has a return value of NULL.

Shane
  • 98,550
  • 35
  • 224
  • 217
10

Using writeLines also allows you to dispense with the "\n" newline character, by using c(). As in:

writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))

This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.

user3071284
  • 6,955
  • 6
  • 43
  • 57
user5699217
  • 111
  • 1
  • 3
2

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))
mikey
  • 1,066
  • 9
  • 17
1

If I'm using a loop I like to use print(noquote("")) to print a newline after each iteration.

pete-may
  • 59
  • 1
  • 3