[R] How to emulate perl style of reading files ?

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jul 3 16:16:56 CEST 2008


On 7/3/2008 9:35 AM, Daren Tan wrote:
> I tried the following, obviously it didn't work. Hope you get my point, how to do it in R ? My objective is to read a large fasta file (but not storing the entire data into memory) , and compute some sequence composition statistics. 
>  
> while(a <- readLines("test1") != EOF) print(a)

The normal way to do this in R is simply

a <- readLines("test1")

and then process all of the lines in a, but if you don't want them all 
in memory at once, you can use some sort of loop as follows.  You need 
to open a connection to the file, then read one line (or a few lines) at 
a time until your condition is met.  For your specific example,

con <- file("test1", "r")
while ( length(a <- readLines(con, 1)) ) print(a)
close(con)

Duncan Murdoch



More information about the R-help mailing list