cat
并且print
似乎都在提供R的"打印"功能
x <- 'Hello world!\n'
cat(x)
# Hello world!
print(x)
# [1] "Hello world!\n"
Run Code Online (Sandbox Code Playgroud)
我的印象是,cat
大多数类似于典型的"打印"功能.我什么时候使用cat
,何时使用print
?
zer*_*323 32
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"
Run Code Online (Sandbox Code Playgroud)
cat
和print 之间的另一个区别是返回值.cat
无形返回NULL
而print
返回它的参数.这个属性print
使它在与管道结合时特别有用:
coefs <- lm(Sepal.Width ~ Petal.Length, iris) %>%
print() %>%
coefficients()
Run Code Online (Sandbox Code Playgroud)
大多数时候你想要的是print
.cat
可以用于将字符串写入文件的内容:
sink("foobar.txt")
cat('"foo"\n')
cat('"bar"')
sink()
Run Code Online (Sandbox Code Playgroud)
正如baptiste所指出的,您可以使用将输出直接重定向到文件.所以相当于上面的内容将是这样的:cat
cat('"foo"', '"bar"', file="foobar.txt", sep="\n")
Run Code Online (Sandbox Code Playgroud)
如果你想逐步写行,你应该使用append
参数:
cat('"foo"', file="foobar.txt", append=TRUE)
cat('"bar"', file="foobar.txt", append=TRUE)
Run Code Online (Sandbox Code Playgroud)
与sink
方法相比,我的口味远非冗长,但它仍然是一种选择.
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"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
在某些情况下,重要的是在控制台中按原样返回输出,例如,当您要复制粘贴输出时.在这些情况下,你真的不想返回一个字符向量.我发现这是一个有用的策略,在这些情况下结合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
Run Code Online (Sandbox Code Playgroud)
使用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"
Run Code Online (Sandbox Code Playgroud)