4

There are many ways to display text in R: cat, print, write, writeLines, sink, message, and other alternatives that I can't remember now. There are other questions here and elsewhere on the internet comparing some of them, but they usually cover only two or three. There must be a table or chart available somewhere to briefly summarize the differences between all of them. Yes, I checked the manual and I can't tell the difference between most of them.

Update: After I posted this question, there was a very similar one by someone else that got an excellent response: Why is message() a better choice than print() in R for writing a package? . Since this question is closed, I can't mark it as duplicate or add an answer, so I am just leaving this note.

Community
  • 1
  • 1
burger
  • 5,683
  • 9
  • 40
  • 63
  • 3
    This is kind of a lazy question... You just thrown here a bunch of functions names and expect someone to write a thesis for you that will cover all the aspects/use cases/etc. for some imaginary internet points in return. I think you should at least show some effort on your side. Unless you are looking for some off site tutorials- in that case this is OT here. – David Arenburg Mar 17 '16 at 15:44
  • 1
    It would be awesome that if the answer is no, this doesn't exist, that you could do it and put it up somewhere for the community. – cory Mar 17 '16 at 15:46
  • 3
    The only one of those that most users use/need often is `print` (which quite often is called only implicitly). Your question should not be how these functions compare, but which function to use if you want to do something specific that differs from normal printing to the console. – Roland Mar 17 '16 at 15:51
  • I don't agree that this is a lazy question. I decided to ask it after searching for some variation of it countless times. There are other questions that ask when to use a certain function and there are often several correct answers that suggest different ones. I don't want to just copy and paste without understanding. Would it be better to rename the question to "Why does R have so many ways to print"? – burger Mar 17 '16 at 20:25
  • To anyone who comes here, about a month after I posted this question, there was a very similar one posted by someone else that was deemed appropriate and got a lot of votes: http://stackoverflow.com/questions/36699272/why-is-message-a-better-choice-than-print-in-r-for-writing-a-package – burger May 17 '17 at 17:22

1 Answers1

3

This is a good question, since R is rather notorious for having many slightly different ways to accomplish similar tasks.

The function print is used to simply print to the R console. For example:

# a sample vector
tmp<-c("foo","bar","baz")
tmp
# [1] "foo" "bar" "baz"

print(tmp)
#[1] "foo" "bar" "baz"

It is also notable that print can gain new printing methods after other packages are loaded, such as the xtable package.

The cat function concatenates all the entries passed to it and prints them in a way more akin to the command line or shell (e.g. bash) that you might be more used to. For example:

cat(tmp)
# foo bar baz

Like the paste function, it can also include separators, and allows R to pull of other tricks:

cat(tmp,sep = "|")
# foo|bar|baz
# handy for creating complex regular expressions

# create some LaTeX markup
FigureFilepath<-"/path/to/figure/i.jpg"
cat("\\includegraphics[width=0.9\\linewidth,height=0.9\\textheight,keepaspectratio]{", FigureFilepath, "}\n", sep="")
# \includegraphics[width=0.9\linewidth,height=0.9\textheight,keepaspectratio]{/path/to/figure/i.jpg}

As implied, this can be handy if you are using R in an environment such as within a LaTeX document with knitr and want to print specially formatted text.

The write function is a wrapper for cat which prints to a file and has some special treatment of matrices (not shown here):

write(tmp,file = "output.txt")
file.show("output.txt")
# foo
# bar
# baz

While the OP did not mention it, I think it is important to mention the paste function, including its cousin paste0. The paste function also prints items to the console that can visually appear similar to print, e.g.:

paste(tmp)
# [1] "foo" "bar" "baz"

However, there are some notable differences. You can also combine elements from different vectors, and specify a separator:

paste(tmp,c("one","two"),sep = "~")
# [1] "foo~one" "bar~two" "baz~one"
# Note how the second element is recycled here!

You can also collapse the output to concatenate everything together with yet another specified separator:

paste(tmp,c("one","two"),sep = "~",collapse = "|")
# [1] "foo~one|bar~two|baz~one"

If you just want a quick and simple one, you can use paste0 which does not use a separator, but can also support collapse.

paste0(tmp,c("one","two"))
# [1] "fooone" "bartwo" "bazone"

Importantly, the output of paste and paste0 can be saved as an object or used within another function, unlike cat as per Richard's comment.

x<-paste(tmp,c("one","two"),sep = "~")
x
# [1] "foo~one" "bar~two" "baz~one"

Here is the console output if you try to save the output of print or cat into an object:

> x<-print("yes")
[1] "yes"
> x
[1] "yes"
> x<-cat("yes")
yes
> x
NULL

Another sticking point that most R beginners will usually run into is the usage of print and paste within a for loop. The console output of paste is not shown when executed within a for loop, as shown here:

for(i in 1){
  paste("This is paste")
  print("This is print")
  cat("This is cat")
}
# [1] "This is print"
# This is cat

The sink function simply diverts the R console output, usually to a file.

sink("output.txt")
cat("hello")
cat("\n")
cat("world")
print(tmp)
sink()
# hello
# world[1] "foo" "bar" "baz"

Note that anything written to the console between the two sink() commands will be written to the file, which might not be desirable.

The writeLines function can be used with a 'connection' type object in order to send output elsewhere, often to a file. Unlike sink, it will only write the specified items to the file.

fileConn<-file("output.txt")
writeLines(tmp,fileConn)
cat("This is test text")
print("Hello world")
close(fileConn)
file.show("output.txt")
# foo
# bar
# baz

You can come up with some creative uses for this, such as creating system session logs at the end of your scripts

fileConn<-file("syslog.txt")
writeLines(capture.output(system('uname -srv',intern=T),sessionInfo()), fileConn)
close(fileConn)
# file.show("syslog.txt")
# <too long to fit here!>

There are some nice explanations for the reasoning behind why some of these functions work the way they do in this blog as well: http://arrgh.tim-smith.us/atomic.html

user5359531
  • 3,217
  • 6
  • 30
  • 55
  • 1
    All of that stuff about `paste` is not relevant for the question. `paste` doesn't print at all. It *returns* a character vector (which is then printed by a call to `print` if you don't use `cat`, `message`, `warning`, `write` et al.). – Roland Mar 18 '16 at 07:36
  • Great point Roland, thanks for the clarification. It is very common for beginners to mistakenly use `paste` to print to the console, thus I included it in my explanation on some ways to "print" text in R. – user5359531 Mar 18 '16 at 15:21