猫与印花有什么区别?

Sim*_*ang 33 r

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无形返回NULLprint返回它的参数.这个属性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()有文件参数时,为什么会使用sink()? (2认同)
  • @baptiste它有,但是如果你想编写多行同时传递“file”和“append=TRUE”,那就有点乏味了。 (2认同)

Ann*_*e N 5

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)

在某些情况下,重要的是在控制台中按原样返回输出,例如,当您要复制粘贴输出时.在这些情况下,你真的不想返回一个字符向量.我发现这是一个有用的策略,在这些情况下结合printcat:使用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)

  • print(通常)返回输入中给出的值.因此:class(print(1:3))将返回一个整数. (2认同)