R scan Function


scan() function read data from screen or file.

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


• file: the name of a file, if "", then read in from stdin
• what: type of data, including logical, integer, numeric, complex, character, raw
• what: the type of what gives the type of data to be read. The supported types are logical, integer, numeric, complex, character, raw and list. If what is a list, it is assumed that the lines of the data file are records each containing length(what) items (‘fields’) and the list components should have elements which are one of the first six types listed or NULL, see section ‘Details’ below.
• nmax: integer: the maximum number of data values to be read, or if what is a list, the maximum number of records to be read. If omitted or not positive or an invalid value for an integer (and nlines is not set to a positive value), scan will read to the end of file.
• n: integer: the maximum number of data values to be read, defaulting to no limit. Invalid values will be ignored.
More auguments see read.table().

Following is a csv file example.



> x <- scan("ordermatrix.csv",what="character",skip=1,quiet=TRUE);
> x

[1] "r1,1,0,1,0,0,1,0,2" "r2,1,2,5,1,2,1,2,1" "r3,0,0,9,2,1,1,0,1"
[4] "r4,0,0,2,1,2,0,0,0" "r5,0,2,15,1,1,0,0,0" "r6,2,2,3,1,1,1,0,0"
[7] "r7,2,2,3,1,1,1,0,1"


> x <- scan("ordermatrix.csv",what="character",quiet=TRUE);
> x

[1] ",t1,t2,t3,t4,t5,t6,t7,t8" "r1,1,0,1,0,0,1,0,2"
[3] "r2,1,2,5,1,2,1,2,1" "r3,0,0,9,2,1,1,0,1"
[5] "r4,0,0,2,1,2,0,0,0" "r5,0,2,15,1,1,0,0,0"
[7] "r6,2,2,3,1,1,1,0,0" "r7,2,2,3,1,1,1,0,1"


> x <- scan("ordermatrix.csv",skip=1,nlines=1);

Read 1 item


> x

[1] "r1,1,0,1,0,0,1,0,2"


Read into a list:

> x <- scan("ordermatrix.csv",skip=1,
+ what = list("","","","","","","","",""))

[[1]]
[1] "r1,1,0,1,0,0,1,0,2"
[[2]]
[1] "r2,1,2,5,1,2,1,2,1"
[[3]]
[1] "r3,0,0,9,2,1,1,0,1"
[[4]]
[1] "r4,0,0,2,1,2,0,0,0"
[[5]]
[1] "r5,0,2,15,1,1,0,0,0"
[[6]]
[1] "r6,2,2,3,1,1,1,0,0"
[[7]]
[1] "r7,2,2,3,1,1,1,0,1"
[[8]]
[1] ""
[[9]]
[1] ""


Read data from screen if let the file name "", or just without any parameter:

> x <- scan("",what="int")
1: 43 #input 43 from the screen
2:
Read 1 item
> x

[1] "43"


> x <- scan("",what="int")
1: 43 #input 43 from the screen
2: 22
3: 67
4:
Read 3 items
> x

[1] "43" "22" "67"


Large data can be scanned in by just copy and paste, for example paste from EXCEL.

> x <- scan()

Then use "ctrl+v" to paste the data, the data type will be automatically determined.