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

______________________________________________
R-help@r-project.org 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.

Reply via email to