[R] Iterating over file lines

Duncan Murdoch murdoch at stats.uwo.ca
Tue Oct 13 23:50:35 CEST 2009


On 13/10/2009 5:27 PM, Albert Vernon Smith wrote:
> I am attempting to iterate over a file, processing it line by line.
> In my function below, I am only getting the first item over and over
> and over again from my test file rather than subsequent lines.  How
> can I modify this to read lines sequentially?
> 
> ==
> 
> iteratefile <- function(file) {
>   f.con <- file(file)
>   on.exit(close(f.con))
>   while( length(readln <- readLines(f.con, 1)) > 0 ) {
>      x <- unlist(strsplit(readln, " "))
>      print(x[1])
>    }
>    return(invisible())
> }
> 
> iteratefile("test.txt")
> 
> ==
> 
> I am working with version 2.9.2 on Mac OS X 10.5.  My code is based on
> examples I've taken from the mailing list, and I'm still only getting
> the top line.  I'm not sure what I'm doing wrong.

You didn't open f.con at the start, so it gets reopened every time you 
call readLines.  You should use

f.con <- file(file, open="rt")

Duncan Murdoch




More information about the R-help mailing list