[R] iteration introspection?

Gabor Grothendieck ggrothendieck at myway.com
Sat Aug 7 17:59:10 CEST 2004


Gabor Grothendieck <ggrothendieck <at> myway.com> writes:

: 
: Cere Davis <cere <at> u.washington.edu> writes:
: 
: > 
: > Hi everyone,
: > 
: > I want to perform a regex substitution on line #1 in a file based on the 
: > contents of line #2.  same is true for line 11 and line 12 etc...
: > 
: > With the look at each line of a file rolling forward method it seems to 
: > me that I will not be able to use iterators like 'each' for this 
: > operation unless I am able to manipulate or even know of the position of 
: > the file pointer from within the iterator block but I don't know of a 
: > way to do this.
: > 
: > Does anyone know how I can learn what the value of my iterator is within 
: >   a loop?
: 
: Assuming you want to process the lines in pairs read them all in
: and then loop:

Sorry. There was an error in this.  Here it is corrected:
 
    lines <- readLines("my.txt")
    n <- length(lines)
    for( i in seq(1,n,2)) {
       # process line[i] and line[i+1] ...
    }
 
: Or if you want to read them in a pair at a time:
: 
:    con <- file("my.txt", "r")
:    while(length(line <- readLines(con, 1))) {
:       next.line <- readLines(con, 1)
:       stopifnot(length(next.line))
:       # process line and next.line
:    }
:    close(con)
: 
: If you want to read them in one by one rather than in pairs then
: have a look at ?pushBack




More information about the R-help mailing list