Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

r - What is the difference between cat and print?

cat and print both seem to offer a "print" functionality in R.

x <- 'Hello world!
'
cat(x)
# Hello world!
print(x)
# [1] "Hello world!
"

My impression is that cat most resembles the typical "print" function. When do I use cat, and when do I use print?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
')
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="
")

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...