Re: [R] Read last line of a file

From: Petr Savicky <>
Date: Wed, 04 May 2011 11:34:36 +0200

On Wed, May 04, 2011 at 02:17:29AM -0700, Joel wrote:
> Hi dear R users.
> I got a file that I need to extract the third column (or word) of the last
> line of files that has a diffrent amounts of rows.
> It works with
> x<-read.tables("file")
> x[1,3]
> This returns the proper result but as the files is large this takes time and
> uses memory that is just unneccery.
> p<-read.table(textConnection(system("tail -1 file",intern=TRUE)))
> p[1,3]
> This also returns the proper result but then requires the system to be unix
> based witch is quite silly if you ask me. Would rather just use R commands.
> So Im wondering if anyone of you got a better way of reading the last line
> of a file and extracting the third column (or word) of that line.


The following reads the file into memory, but it is more efficient than read.table(), since it does no parsing of the file as a whole.

  x <- readLines("file")
  strsplit(x[length(x)], " +")[[1]][3]

Hope this helps.

Petr Savicky. mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Thu 05 May 2011 - 06:25:03 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 05 May 2011 - 07:00:05 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive