Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between cat and print?

Tags:

r

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?

like image 289
Simon Kuang Avatar asked Aug 05 '15 22:08

Simon Kuang


People also ask

What does cat () mean in R?

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)

What is the difference between print and paste in R?

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.

What is print 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.

How do I print a new line in R?

Special Characters in Strings The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.


1 Answers

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.

like image 156
zero323 Avatar answered Oct 09 '22 02:10

zero323