Thursday, September 5, 2013

Using colClasses to Load Data More Quickly in R

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)
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:


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.

4 comments:

  1. Also, if you've downloaded a dataset with lots of columns and only need some of them, using a colClass of NULL for unwanted columns will stop them being loaded and save time too.

    ReplyDelete
  2. That's a great tip, thanks! I've always used this solution for that problem: http://stackoverflow.com/a/2194154 I wonder which one is faster. Hopefully I'll get a chance to test it out and post a follow-up.

    ReplyDelete
  3. I was taking a class on coursera and found this --

    A quick an dirty way to figure out the classes of each column is the following:
    initial <- read.table("datatable.txt", nrows = 100)
    classes <- sapply(initial, class)
    tabAll <- read.table("datatable.txt",colClasses = classes)

    ReplyDelete