R语言基础知识学习(三):R的输入和输出函数简单介绍

常用的输出函数:cat()

常用的输入函数:scan(),readline(),readLines()

(1) cat()函数

Description

Outputs the objects, concatenating the representations. cat performs much less conversion than print.

Useage

cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,append = FALSE)

参数介绍:

...:输出对象

file:一个文件链接或者文件名,如果不写此参数,表示输出到控制台。

sep:分隔符

append:是否追加,当且仅当参数file是文件名而非链接时,此参数才有效。

例:

> cat(1:10)
1 2 3 4 5 6 7 8 9 10

把一个向量输出到控制台。

> output <- file('output.txt')       //建立链接
> class(output)                         //查看链接属性,是connection
[1] "file" "connection"
> getwd()              //获取工作目录
[1] "D:/Program Files/R/workspace"
> cat(1:100,sep='\t',file = output)  //将向量存入文件链接指向的文件中,文件在工作目录里。
> close(output)            //关闭链接。

将一个向量输出到文件中。

(2)scan()函数

Description

Read data into a vector or list from the console or file.

Usage

scan(file = "", what = double(), nmax = -1, n = -1, sep = "",quote = if(identical(sep, "\n")) "" else "'\"", dec = ".",skip = 0, nlines = 0, na.strings = "NA",
flush = FALSE, fill = FALSE, strip.white = FALSE,quiet = FALSE, blank.lines.skip = TRUE, multi.line = TRUE,comment.char = "", allowEscapes = FALSE,
fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)

例:

> x <- scan()
1: 12
2: 12
3: 23
4:
Read 3 items
>
> x
[1] 12 12 23

利用键盘输入三个数字,x里就会存储三个数字。

也可以利用scan()函数读取外部文件。例:
> y <- scan(file = 'output.txt')
Read 38 items
> y
[1] 1 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7
[17] 8 9 101 2 3 4 5 6 7 8 9 10 11 12 13 14
[33] 15 16 17 18 19 20

读取文件‘output.txt’里的数据。

(3)readline()函数

Description

readline reads a line from the terminal (in interactive use).

Usage

readline(prompt = "")

例:

> a <- readline()
hello world
> a
[1] "hello world"

与scan()不同,readline()函数只能输入一行。

 

(4)readLines()函数

Description

Read some or all text lines from a connection.

Usage

readLines(con = stdin(), n = -1L, ok = TRUE, warn = TRUE,encoding = "unknown", skipNul = FALSE)

例:

conn <- file('output.txt')
a <- readLines(conn,n=1)
a

结果:

[1] "con\t" 


b <- readLines(conn,n=5)
b

结果:

[1] "con\t"
[2] "a connection object or a character string."
[3] "n\t"
[4] "integer. The (maximal) number of lines to read. Negative values indicate that one should read up to the end of input on the connection."
[5] "ok\t"

 

posted on 2016-11-11 17:29  草堂夜归人  阅读(13664)  评论(0编辑  收藏  举报

导航