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 o
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.
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.
You can do this:
cat("File not supplied.\nUsage: ./program F=filename\n")
Notice that cat
has a return
value of NULL
.
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))