[R] Iterating over file lines

Albert Vernon Smith avsmith at gmail.com
Tue Oct 13 23:27:20 CEST 2009


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.

Thanks,
-albert




More information about the R-help mailing list