Using colClasses to Load Data More Quickly in R

September 5, 2013

(This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers)

Specifying a colClasses argument to read.table or read.csv can save time on importing data, while also saving steps to specify classes for each variable later.

For example, loading a 893 MB took 441 seconds to load when not using colClasses, but only 268 seconds to load when using colClasses. The system.time function in base can help you check your own times.

Without specifying colClasses:

   user  system elapsed 
441.224 8.200 454.155

When specifying colClasses:

   user  system elapsed 
268.036 6.096 284.099

The classes you can specify are: factor, character, integer, numeric, logical, complex, and Date. Dates that are in the form %Y-%m-%d or Y/%m/%d will import correctly. This tip allows you to import dates properly for dates in other formats.

system.time(largeData <- read.csv("huge-file.csv",
header = TRUE,
colClasses = c("character", "character", "complex",
"factor", "factor", "character", "integer",
"integer", "numeric", "character", "character",
"Date", "integer", "logical")))

If there aren’t any classes that you want to change from their defaults, you can read in the first few rows, determine the classes from that, and then import the rest of the file:

sampleData <- read.csv("huge-file.csv", header = TRUE, nrows = 5)
classes <- sapply(sampleData, class)
largeData <- read.csv("huge-file.csv", header = TRUE, colClasses = classes)

If you aren’t concerned about the time it takes to read the data file, but instead just want the classes to be correct on import, you have the option of only specifying certain classes:

smallData <- read.csv("small-file.csv", 
header = TRUE,

> class(smallData$variableName)
[1] "character"

Citations and Further Reading

This post is one part of my series on dealing with large datasets.

To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)