122

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
  • 14,815
  • 16
  • 74
  • 126

4 Answers4

138

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
  • 157,540
  • 25
  • 364
  • 424
  • Both `writelines` and 'cat` doesn't seem to write to a variable. I was trying to create a string variable with multiple lines. `stringvar – sjd Aug 12 '20 at 15:52
28

You can do this:

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

Notice that cat has a return value of NULL.

Shane
  • 92,684
  • 33
  • 219
  • 216
7

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,400
  • 6
  • 37
  • 51
user5699217
  • 81
  • 1
  • 2
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
  • 498
  • 3
  • 11