[R] How to read last (incomplete) line from gzfile()?

Stephen Eglen S.J.Eglen at damtp.cam.ac.uk
Sun Apr 20 19:35:07 CEST 2008


Hi,

I have some text files that do not have trailing \n on the last
(incomplete) line; how do I read in the last line?

e.g. here is a test case: [linux + R version 2.6.1 (2007-11-26) ]


z <- gzfile("short.gz", open="w")
cat("7\n5\n3", file=z)
close(z)

z <- gzfile('short.gz')
readLines(z)

[1] "7" "5"

readLines would indicate that for blocking connections (which I assume
this is), the last line (containing 3) would be read in, and a warning
would be generated.  I get the desired behaviour if I use a file() on
a file that is not compressed:

y <- file("short", open="w")
cat("7\n5\n3", file=y)
close(y)

y <- file('short')
readLines(y)

[1] "7" "5" "3"
Warning message:
In readLines(y) : incomplete final line found on 'short'

What am I missing? 

Thanks, Stephen



More information about the R-help mailing list