cat
and print
both seem to offer a "print" functionality in R.
x <- 'Hello world!\n' cat(x) # Hello world! print(x) # [1] "Hello world!\n"
My impression is that cat
most resembles the typical "print" function. When do I use cat
, and when do I use print
?
cat() function in R Language is used to print out to the screen or to a file. Syntax: cat(…, file = “”, sep = ” “, fill = FALSE, labels = NULL, append = FALSE)
paste0 () — this function concatenates the input values in a single character string. The difference between: paste and paste0 is that paste function provides a separator operator, whereas paste0 does not. print ()- Print function is used for printing the output of any object in R.
R print() Function In the above example, we have used the print() function to print a string and a variable. When we use a variable inside print() , it prints the value stored inside the variable.
Special Characters in Strings The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.
cat
is valid only for atomic types (logical, integer, real, complex, character) and names. It means you cannot call cat
on a non-empty list or any type of object. In practice it simply converts arguments to characters and concatenates so you can think of something like as.character() %>% paste()
.
print
is a generic function so you can define a specific implementation for a certain S3 class.
> foo <- "foo" > print(foo) [1] "foo" > attributes(foo)$class <- "foo" > print(foo) [1] "foo" attr(,"class") [1] "foo" > print.foo <- function(x) print("This is foo") > print(foo) [1] "This is foo"
Another difference between cat
and print is returned value. cat
invisibly returns NULL
while print
returns its argument. This property of print
makes it particularly useful when combined with pipes:
coefs <- lm(Sepal.Width ~ Petal.Length, iris) %>% print() %>% coefficients()
Most of the time what you want is print
. cat
can useful for things like writing a string to file:
sink("foobar.txt") cat('"foo"\n') cat('"bar"') sink()
As pointed by baptiste you can use cat
to redirect output directly to file. So equivalent of the above would be something like this:
cat('"foo"', '"bar"', file="foobar.txt", sep="\n")
If you want to write lines incrementally you should use append
argument:
cat('"foo"', file="foobar.txt", append=TRUE) cat('"bar"', file="foobar.txt", append=TRUE)
Compared to sink
approach it is far to verbose for my taste, but it is still an option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With