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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM