[R] Scanning data files line-by-line

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Apr 30 15:13:26 CEST 2003


On Wed, 30 Apr 2003, R A F wrote:

> Maybe I'm missing something.  When I do readLines( "file", n = 1) and
> repeat, it always reads the first line of "file".  I've to be able to
> advance to the next line, no?

You need to open the connection first.  readLines( "file", n = 1)
opens file "file", reads a line and then closes "file".  It has no idea
that you want to keep reading the same file.

> I'll take a look at the command file(), as someone else suggested.

It's open() you need, as in

con <- file("file")
open(con)
for(i in 1:10) print(readLines(con, n=1))
close(con)

In C you would need to (f)open a file to read it line-by-line, just as 
here.

The first two lines can be collapsed to

con <- file("file", "r")


> 
> Thanks.
> 
> >From: Duncan Murdoch <dmurdoch at pair.com>
> >To: "R A F" <raf1729 at hotmail.com>
> >CC: R-help at stat.math.ethz.ch
> >Subject: Re: [R] Scanning data files line-by-line
> >Date: Wed, 30 Apr 2003 08:26:26 -0400
> >
> >On Wed, 30 Apr 2003 11:51:00 +0000, you wrote:
> >
> > >Hi all, is there a way to read a data file into R line-by-line, akin
> > >to what fscanf does in C, say?
> > >
> > >It seems that "scan" and "read.table" both read the entire data file
> > >in at once, whereas "readLines" allows one to read a file partially,
> > >but doesn't quite read line-by-line either.
> >
> >That's what readLines(con, n=1) is supposed to do; in what way does it
> >not quite work?
> >
> >Duncan
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list