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
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
Maybe Matching Threads
- problem with while loop with next (was RE: file connection, w hile, readLines and browser)
- RE: problem with while loop with next
- Binary AGI Scripts
- An example (was RE: file connection, while, readLines and bro wser)
- file connection, while, readLines and browser