[R] More on scan()
Thomas Lumley
tlumley at u.washington.edu
Fri Dec 20 00:47:21 CET 2002
On Thu, 19 Dec 2002 apjaworski at mmm.com wrote:
>
> Here is one way of doing this.
> (1) read the whole file in as a vector of strings one line at a time
> x <- readLines("<path to your data file>")
> (2) find the position of the "@DATA" string in your vector
> s <- which(x == "@DATA")
> (3) scan the file again skipping s lines
> scan("<path to your data file>", skip=s, sep=",", ...)
>
> You may want to consider using read.table instead of scan - it has the skip
> parameter too. Finally you could actually reuse x from (1) above by
> something like
> x <- x[-(1:s])
> loop through elements of x and use the strsplit command to extract
> numbers from each line
> I suspect that this would be more cumbersome and slower than re-reading the
> file skiiping s lines from the top.
A simpler solution that doesn't involve rereading is to use a connection
conn<-file("myfile.txt")
open(conn)
repeat({
a.line <- readLines(conn,n=1)
if (substr(a.line,1,6)=="@DATA") break
})
read.csv(conn)
close(conn)
-thomas
Thomas Lumley Asst. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
More information about the R-help
mailing list