这是一个很好的问题,因为 R 因使用许多略有不同的方法来完成类似的任务而臭名昭著。
功能print
用于简单地打印到 R 控制台。例如:
# a sample vector
tmp<-c("foo","bar","baz")
tmp
# [1] "foo" "bar" "baz"
print(tmp)
#[1] "foo" "bar" "baz"
还值得注意的是print
加载其他包后可以获得新的打印方式,例如xtable
包裹。
The cat
函数连接传递给它的所有条目,并以更类似于您可能更习惯的命令行或 shell(例如 bash)的方式打印它们。例如:
cat(tmp)
# foo bar baz
像paste
函数,它还可以包含分隔符,并允许 R 发挥其他技巧:
cat(tmp,sep = "|")
# foo|bar|baz
# handy for creating complex regular expressions
# create some LaTeX markup
FigureFilepath<-"/path/to/figure/i.jpg"
cat("\\includegraphics[width=0.9\\linewidth,height=0.9\\textheight,keepaspectratio]{", FigureFilepath, "}\n", sep="")
# \includegraphics[width=0.9\linewidth,height=0.9\textheight,keepaspectratio]{/path/to/figure/i.jpg}
正如所暗示的,如果您在环境中使用 R,例如在 LaTeX 文档中,这会很方便knitr
并想要打印特殊格式的文本。
The write
函数是 cat 的包装器,它打印到文件并对矩阵进行一些特殊处理(此处未显示):
write(tmp,file = "output.txt")
file.show("output.txt")
# foo
# bar
# baz
虽然OP没有提到这一点,但我认为有必要提及paste
函数,包括它的表兄弟paste0
. The paste
函数还将项目打印到控制台,这些项目在视觉上看起来类似于print
, e.g.:
paste(tmp)
# [1] "foo" "bar" "baz"
然而,也存在一些显着的差异。您还可以组合来自不同向量的元素,并指定分隔符:
paste(tmp,c("one","two"),sep = "~")
# [1] "foo~one" "bar~two" "baz~one"
# Note how the second element is recycled here!
你也可以collapse
将所有内容与另一个指定分隔符连接在一起的输出:
paste(tmp,c("one","two"),sep = "~",collapse = "|")
# [1] "foo~one|bar~two|baz~one"
如果您只是想要一个快速简单的方法,您可以使用paste0
不使用分隔符,但也可以支持collapse
.
paste0(tmp,c("one","two"))
# [1] "fooone" "bartwo" "bazone"
重要的是,输出paste
and paste0
可以保存为对象或在另一个函数中使用,这与cat
根据理查德的评论。
x<-paste(tmp,c("one","two"),sep = "~")
x
# [1] "foo~one" "bar~two" "baz~one"
如果您尝试保存输出,这是控制台输出print
or cat
进入一个对象:
> x<-print("yes")
[1] "yes"
> x
[1] "yes"
> x<-cat("yes")
yes
> x
NULL
大多数 R 初学者通常会遇到的另一个症结是使用print
and paste
在 for 循环内。控制台输出为paste
在 a 内执行时不显示for
循环,如下所示:
for(i in 1){
paste("This is paste")
print("This is print")
cat("This is cat")
}
# [1] "This is print"
# This is cat
The sink
函数只是将 R 控制台输出转移到文件中。
sink("output.txt")
cat("hello")
cat("\n")
cat("world")
print(tmp)
sink()
# hello
# world[1] "foo" "bar" "baz"
请注意,两者之间写入控制台的任何内容sink()
命令将被写入文件,这可能是不可取的。
The writeLines
函数可以与“连接”类型对象一起使用,以便将输出发送到其他地方,通常是发送到文件。不像sink
,它只会将指定的项目写入文件。
fileConn<-file("output.txt")
writeLines(tmp,fileConn)
cat("This is test text")
print("Hello world")
close(fileConn)
file.show("output.txt")
# foo
# bar
# baz
您可以为此提出一些创造性的用途,例如在脚本末尾创建系统会话日志
fileConn<-file("syslog.txt")
writeLines(capture.output(system('uname -srv',intern=T),sessionInfo()), fileConn)
close(fileConn)
# file.show("syslog.txt")
# <too long to fit here!>
对于其中一些函数以它们的方式工作的原因,在本博客中也有一些很好的解释:http://arrgh.tim-smith.us/atomic.html http://arrgh.tim-smith.us/atomic.html