[R] Reading a csv file row by row

Henrik Bengtsson hb at stat.berkeley.edu
Fri Apr 6 17:10:43 CEST 2007


On 4/6/07, Yuchen Luo <realityrandom at gmail.com> wrote:
> Hi, my friends.
> When a data file is large, loading the whole file into the memory all
> together is not feasible. A feasible way  is to read one row, process it,
> store the result, and read the next row.
> In Fortran, by default, the 'read' command reads one line of a file, which
> is convenient, and when the same 'read' command is executed the next time,
> the next row of the same file will be read.
> I tried to replicate such row-by-row reading in R.I use scan( ) to do so
> with the "skip= xxx " option. It takes only seconds when the number of the
> rows is within 1000. However, it takes hours to read 10000 rows. I think it
> is because every time R reads, it needs to start from the first row of the
> file and count xxx rows to find the row it needs to read. Therefore, it
> takes more time for R to locate the row it needs to read.

Yes, to skip rows scan() needs to locate every single row (line
feed/carriage return).  The only gain you get is that it does not have
to parse and store the contents of those skipped lines.

One solution is to first go through the file and register the file
position of the first character in every line, and then make use of
this in subsequent reads.  In order to do this, you have to work with
an opened connection and pass that to scan instead.  Rough sketch:

con <- file(pathname, open="r")

# Scan file for first position of every line
rowStarts <- scanForRowStarts(con);

# Skip to a certain row and read a set of lines:
seek(con, where=rowStarts, origin="start", rw="r)
data <- scan(con, ..., skip=0, nlines=rowsPerChunk)


That's the idea.  The tricky part is to get scanForRowStarts()
correct.  After reading a line you can always query the connection for
the current file position using:

  pos <- seek(con, rw="r")

so you could always iterate between readLines(con, n=1) and pos <-
c(pos, seek(con, rw="r")), but there might be a faster way.



> Is there a solution to this problem?
> Your help will be highly appreciated!
>         [[alternative HTML version deleted]]
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list