Skip to content
Prev 300064 / 398502 Next

read.table with numeric row names

scan() or readLines() will read as many lines of the file as you want.
Use the file() function to open a "file connection" so a subsequent
read.table() will start where scan() or readLines() finished.  E.g.,

  > tfile <- tempfile()
  > cat(file=tfile, " 2.5  3.6  7.1  7.9 
  +  100  3      4      2    3 
  +  200  3.1  4      3      3 
  +  300  2.2  3.3  2    4
  + ") # now tfile looks like your example file
  > read.table(header=TRUE, tfile) # easy way, but not what you want
      X2.5 X3.6 X7.1 X7.9
  100  3.0  4.0    2    3
  200  3.1  4.0    3    3
  300  2.2  3.3    2    4
  > fileConn <- file(tfile, open="r")
  > scan(fileConn, what=0.0, nlines=1)
  Read 4 items
  [1] 2.5 3.6 7.1 7.9
  > read.table(header=FALSE, fileConn)
     V1  V2  V3 V4 V5
  1 100 3.0 4.0  2  3
  2 200 3.1 4.0  3  3
  3 300 2.2 3.3  2  4
  > str(.Last.value)
  'data.frame':   3 obs. of  5 variables:
   $ V1: int  100 200 300
   $ V2: num  3 3.1 2.2
   $ V3: num  4 4 3.3
   $ V4: int  2 3 2
   $ V5: int  3 3 4
   > close(fileConn) # clean up

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com