cat
仅对原子类型(逻辑、整数、实数、复数、字符)和名称有效。这意味着你不能打电话cat
在非空列表或任何类型的对象上。在实践中,它只是将参数转换为字符并连接,这样你就可以想到类似的东西as.character() %>% paste()
.
print
是一个通用函数,因此您可以为某个 S3 类定义特定的实现。
> 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"
之间的另一个区别cat
并打印返回值。cat
无形中回归NULL
while print
返回其参数。此属性为print
与管道结合使用时特别有用:
coefs <- lm(Sepal.Width ~ Petal.Length, iris) %>%
print() %>%
coefficients()
大多数时候你想要的是print
. cat
对于将字符串写入文件之类的事情很有用:
sink("foobar.txt")
cat('"foo"\n')
cat('"bar"')
sink()
As pointed https://stackoverflow.com/questions/31843662/what-is-the-difference-between-cat-and-print/31843744#comment51610245_31843744 by baptiste https://stackoverflow.com/users/471093/baptiste您可以使用cat
将输出直接重定向到文件。所以上面的等价物是这样的:
cat('"foo"', '"bar"', file="foobar.txt", sep="\n")
如果你想增量地写行,你应该使用append
争论:
cat('"foo"', file="foobar.txt", append=TRUE)
cat('"bar"', file="foobar.txt", append=TRUE)
相比sink
就我的口味而言,这种方法过于冗长,但它仍然是一种选择。