【发布时间】:2015-10-28 21:18:04
【问题描述】:
cat 和 print 似乎都在 R 中提供了“打印”功能。
x <- 'Hello world!\n'
cat(x)
# Hello world!
print(x)
# [1] "Hello world!\n"
我的印象是cat 最类似于典型的“打印”功能。什么时候用cat,什么时候用print?
【问题讨论】:
标签: r
cat 和 print 似乎都在 R 中提供了“打印”功能。
x <- 'Hello world!\n'
cat(x)
# Hello world!
print(x)
# [1] "Hello world!\n"
我的印象是cat 最类似于典型的“打印”功能。什么时候用cat,什么时候用print?
【问题讨论】:
标签: r
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 和 print 之间的另一个区别是返回值。 cat 不可见地返回 NULL 而 print 返回其参数。 print 的这个属性使它在与管道结合使用时特别有用:
coefs <- lm(Sepal.Width ~ Petal.Length, iris) %>%
print() %>%
coefficients()
大多数时候你想要的是print。 cat 可用于将字符串写入文件之类的事情:
sink("foobar.txt")
cat('"foo"\n')
cat('"bar"')
sink()
作为baptiste 的pointed,您可以使用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 的方法相比,这对于我的口味来说过于冗长,但它仍然是一种选择。
【讨论】:
?cat 和 ?print
file 和append=TRUE 有点乏味。
print 与sink 一起使用。
cat 允许您输出精确的字符串。我知道您可以使用print 和quote=FALSE 来避免字符串引号和嵌入式引号转义,但是有没有办法避免长度为1 的字符的向量表示?我的意思是没有领先的[1] 像print('"foo"', quote=FALSE).
cat 和print 之间的本质区别是它们返回的对象的类。这种差异对您可以对返回的对象做什么具有实际影响。
print 返回一个字符向量:
> print(paste("a", 100* 1:3))
[1] "a 100" "a 200" "a 300"
> class(print(paste("a", 100* 1:3)))
[1] "a 100" "a 200" "a 300"
[1] "character"
cat 返回一个 NULL 类的对象。
> cat(paste("a", 100* 1:3))
a 100 a 200 a 300
> class(cat(paste("a", 100* 1:3)))
a 100 a 200 a 300[1] "NULL"
在某些情况下,在控制台中按原样返回输出很重要,例如当您想要复制粘贴输出时。在这些情况下,您真的不想返回字符向量。在这些情况下,我发现将print 和cat 结合起来是一种有用的策略:使用print 创建对象,使用cat 将其打印到控制台。
> output <- print(paste("a", 100* 1:3)) # use print to create the object
> cat(output) # use cat to print it *as is* to your console
a 100 a 200 a 300
使用xtable 包在 R 中打印 LaTeX 表格:
> require(xtable)
> df <- data.frame(a = 1, č = 5) # dataframe with foreign characters
> output <- print(xtable(df), include.rownames = FALSE)
> output <- gsub("č", "c", output) # replace foreign characters before
> # copying to LaTeX
> cat(output)
\begin{table}[ht]
\centering
\begin{tabular}{rr}
\hline
a & c \\
\hline
1.00 & 5.00 \\
\hline
\end{tabular}\end{table}
> print(output)
[1] "\\begin{table}[ht]\n\\centering\n\\begin{tabular}{rr}\n
\hline\na & c \\\\ \n \\hline\n1.00 & 5.00 \\\\ \n
\\hline\n\\end{tabular}\n\\end{table}\n"
【讨论】: