任何语言都需要输入输出,而且都有标准的输入(控制台键盘)输出(控制台屏幕)

一般都会有标准输入输出之外的I/O方式,比如从文件输入,输出到文件

标准输出

输出在S交互运行时要显示某一个对象的值只要键入其名字即可,如: > x <- 1:10> x[1]  1  2  3  4  5  6  7  8  9 10
这实际上是调用了print()函数,即print(x)。在非交互运行(程序)中应使用print()来输出。print()函数可以带一个digits=参数指定每个数输出的有效数字位数,可以带一个quote= 参数指定字符串输出时是否带两边的撇号,可以带一个print.gap=参数指定矩阵或数组输出时列之间的间距。
print()函数是一个通用函数,即它对不同的自变量有不同的反应。对各种特殊对象如数组、模型结果等都可以规定print的输出格式。

本文主要介绍R语言的非标准输入输出

非标准输入

运行其他的R脚本

source( ) 

# input a script
source("myfile")

非标准输出

非标准输出又叫输出重定向

非标准输出分两种情况:一种是输出文本到文件,一种是输出图像到文件

文本重定向到文件sink( ) 
# direct output to a file 
sink("myfile", append=FALSE, split=FALSE)

# return output to the terminal 
sink()

The append option controls whether output overwrites or adds to a file. The split option determines if output is also sent to the screen as well as the output file.


sink不会输出图像,输出图像需要使用图像重定向相关的函数

图形重定向
Function Output to
 pdf("mygraph.pdf") pdf file
 win.metafile("mygraph.wmf") windows metafile
 png("mygraph.png") png file
 jpeg("mygraph.jpg") jpeg file
 bmp("mygraph.bmp") bmp file
 postscript("mygraph.ps") postscript file

上面的每一个函数都是打开一个用于重定向图像的外部文件设备,打开之后正常调用各种绘图函数(为了保险起见,所有绘图函数组好用print()函数输出,因为各种绘图函数的 底层不同,但是都会支持print()),最后调用dev.off()来关闭刚刚打开的外部文件设备。

# example - output graph to jpeg file 
jpeg("c:/mygraphs/myplot.jpg")
plot(x)
dev.off()


如果你的导出图像的上述命令使用source()指令执行,或者被封装到一个函数内部的话,则需要在每一个操作图像的指令处调用print(),否则可能会输出不全,或者输出报错。