scan - Reads vectors of data which all have the same mode, for example
all numbers or all character strings. Each element needs to be separated from
the others by one or more blanks, or the sep= argument can be used to
specify a different separator. If the first argument to scan is a file,
it will read from that file; if the first argument is empty, it reads data from
the terminal, ended by a completely blank line. By default, scan
expects to see numbers - if you're using it to read strings, use the what="
argument.
For example, scan be used to create a vector of color names, as an alternative
to using the c function:
> mycolors = scan(,what='')
1: red blue yellow green orange
6:
Read 5 items
> mycolors
[1] "red" "blue" "yellow" "green" "orange"
scan can also be used to create numeric matrices, by passing the call to
scan to the matrix function. Suppose the file mat.dat
looks like this:
7 19 12 15
8 9 17 4
52 12 9 7
12 9 40 13
We could read this matrix into R as follows:
> mymat = matrix(scan('mat.dat'),ncol=4,byrow=TRUE)
Read 16 items
> mymat
[,1] [,2] [,3] [,4]
[1,] 7 19 12 15
[2,] 8 9 17 4
[3,] 52 12 9 7
[4,] 12 9 40 13
Note the use of byrow=TRUE to overide R's default of
reading matrices by columns.
Connections
In addition to reading files, R provides a set of functions known as connections.
(Type "?connections" in R to learn about all the possibilities.) One very
handy type of connection is the textConnection. This allows you to paste
text into an R session, just as if it came from a file. For example, recall the
previous example of reading a file with scan to create a matrix. We can
reproduce that example without needing a file, by cutting and pasting the data into
a call to textConnection:
> thedata = textConnection('7 19 12 15
+ 8 9 17 4
+ 52 12 9 7
+ 12 9 40 13
+ ')
> mymat = matrix(scan(thedata),ncol=4,byrow=TRUE)
Read 16 items
> mymat
[,1] [,2] [,3] [,4]
[1,] 7 19 12 15
[2,] 8 9 17 4
[3,] 52 12 9 7
[4,] 12 9 40 13
This makes it very easy to run examples that you may find online, and saves
the trouble of creating a file when you just need to read in a small amount of data.