[Rd] head() for files

Gorjanc Gregor Gregor.Gorjanc at bfro.uni-lj.si
Fri Jul 25 14:46:29 CEST 2008

>> I was thinking about using the head and tail functions also for files i.e.
>> show me the first/last few lines of a file. For example:
>> zz <- file("ex.data", "w")  # open an output file connection
>> cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
>> cat("One more line\n", file = zz)
>> close(zz)
>> readLines("ex.data")
>> head.character <- function(x, n=6, ...) readLines(con=x, n=n, ...)
>> head.character("ex.data")
>> As can be seen, this is essentially a wrapper for readLines, but a handy one.
>> Of course, S3 "linking" is needed, perhaps also for class "connection".
>> I am not prefectly satisfied with it as I would like to see printout line by line.
>> Any ideas?
> I think you should have called it head.connection, and then
> head(file("ex.data"))

Yes, but typing head(file("ex.data")) is not that different than readLines(file="ex.data").
However, I do agree that head would work with "character" and "connection" classes.

> would sort of work.  The problems with this are open connections:  what
> should it do on one of those?  Seeking to the start would make sense,
> but not all connections can do that.

Hmm, I am not sure about that since I do not use them often. After a quick look at
?file, I think that file(), url(), gzfile(), bzfile() should work out of the box - see showcases
bellow. unz() can not work without passing a filename, but that is a matter of unz() and
not head.

I also do not know anything about fifos, while pipe could also be useful - btw. I can not find
example for pipe() in ?pipe although the docs say

"For pipe the description is the command line to be piped to or from (see the Examples). This
command line is run in the shell specified by the COMSPEC environment variable."

Regards, gregor

## Some showcases for head()

head.character <- head.connection <- function(x, n=6, ...) readLines(con=x, n=n, ...)
tmp <- function(x)
    cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file=x, sep = "\n")
    cat("One more line\n", file=x)


## file()
zz <- file("ex.data", "w"); tmp(zz)

## url()

## gzfile()
zz <- gzfile("ex.gz", "w"); tmp(zz)

## bzfile()
zz <- bzfile("ex.bz2", "w"); tmp(zz)

## unz()

More information about the R-devel mailing list