How to import last 100 rows using read.csv() in R

Improvement on @lauratboyer's answer if you want to include headers too:

# read headers only
column_names <- as.vector(t(read.csv("your.csv", header=FALSE, colClasses='character', nrows=1)))

# then last n lines
l2keep <- 10
nL <- R.utils::countLines("your.csv")
df <- read.csv("your.csv", header=FALSE, col.names=column_names, skip=nL-l2keep)

If you are on a *nix system, you are better off using the tail -n 100 command to take the last 100 rows. Anything implemented in R would be slower and potentially much slower is your file is truly huge.

If you are using Windows, you may want to take a look at this SO question.


The package R.utils has a function called countLines(). You could do:

l2keep <- 10
nL <- countLines("your.csv")
df <- read.csv("your.csv", header=FALSE, skip=nL-l2keep)

You could use the nrows and skip arguments in read.csv. E.g. if you have a file with 10000 rows and you would only like to import the last 100 rows you could try this:

read.csv("yourfile.csv",nrows=100,skip=9900)

But if it is speed you want, you're probably better off with the solutions given by @Ananda Mahto and @ktdrv

Tags:

Csv

Import

R