Site icon R-bloggers

Using colClasses to Load Data More Quickly in R

[This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
< !-- HTML generated using hilite.me -->
Without specifying colClasses:

< !-- HTML generated using hilite.me -->
   user  system elapsed 
441.224   8.200 454.155 

When specifying colClasses: < !-- HTML generated using hilite.me -->

   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:
< !-- HTML generated using hilite.me -->
sampleData <- read.csv("huge-file.csv", header = TRUE, nrows = 5)
classes <- sapply(sampleData, class)
largeData <- read.csv("huge-file.csv", header = TRUE, colClasses = classes)
str(largeData)

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:

< !-- HTML generated using hilite.me -->
smallData <- read.csv("small-file.csv", 
 header = TRUE,
 colClasses=c("variableName"="character"))


> 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.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.