[R] Reading from files

Marc Schwartz MSchwartz at medanalytics.com
Thu May 2 04:51:23 CEST 2002


> Hi,
> 
> I am a novice to R and have a question here. Is it possible to read a
> single line from a file into a vector or list etc? If so, is it
possible
> to read comma separated values?
> Eg:
> 1000,x,y,z
> 1001,s,d,f
> 
> How do I read the first line only i.e. 1000,x,y,z from the file and
that
> too so that I get separate storage for 1000, x, y and z?
> 
> Thanks in advance.
> Saket.

Review the "nrows" option for the read.csv function (?read.csv).  It
lets you specify how many rows to read from a delimited file.  In the
help file the option is listed for read.table, but it applies to
read.csv as well. The differences between the variations of read.* are
the default values.

For read.csv, the default value for nrows is -1, which reads in all
rows. The default delimiter for read.csv is ",". Also, the default value
for the "header" option is TRUE, which indicates that the first row in
your file contains column names. If your data is structured as you
define above, set header = FALSE.

Thus, to read in the first line only, add in "nrows = 1" to the
arguments, such that the command would be:

> V <- read.csv(FileName, nrows = 1, header = FALSE, ....)

Note that the option "skip = x" lets you tell the function to skip a
certain number of rows before starting the read. 

The combination of skip and nrows let's you read in a specific subset of
rows from a larger file.  For example to read in rows 6 through 10, you
would use:

> V <- read.csv(FileName, skip = 5, nrows = 5, header = FALSE, ...)

Hope that helps.

Marc Schwartz


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list