How to Use colClasses to Quickly Import Data in R


You can use the colClasses argument when importing a file into R to specify the classes of each column:

df <- read.csv('my_data.csv',
               colClasses=c('character', 'numeric', 'numeric'))

The benefit of using colClasses is that you can import data much faster, especially when the files are extremely large.

The following example shows how to use this argument in practice.

Example: Use colClasses When Importing Files

Suppose I have some CSV file called my_data.csv with three columns that I’d like to import into R:

I can use the following syntax to do so:

#import CSV file
df <- read.csv('my_data.csv',
               colClasses=c('character', 'numeric', 'numeric'))

#view class of each column in data frame
str(df)

'data.frame':	14 obs. of  3 variables:
 $ team    : chr  "Mavs" "Spurs" "Hornets" "Rockets" ...
 $ points  : num  91 99 104 103 105 88 89 93 96 99 ...
 $ rebounds: num  33 23 26 25 25 26 29 30 34 23 ...

Note that the number of values in the colClasses argument should match the number of columns in the data frame.

For example, if you only supply one value to the colClasses argument then each column in the data frame will have the same class:

#import CSV file
df <- read.csv('my_data.csv',
               colClasses=c('character'))

#view class of each column in data frame
str(df)

'data.frame':	14 obs. of  3 variables:
 $ team    : chr  "Mavs" "Spurs" "Hornets" "Rockets" ...
 $ points  : chr  "91" "99" "104" "103" ...
 $ rebounds: chr  "33" "23" "26" "25" ...

Notice that each column in the resulting data frame has a “character” class since we only supplied one value to the colClasses argument.

Note that you can specify the following potential classes in the colClasses argument:

  • character: “hey”, “there”, “world”
  • complex: as.complex(-1), 4i
  • numeric: as.integer(20), 3L
  • integer: 4, 12, 158
  • logical: TRUE, FALSE

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Manually Enter Raw Data in R
How to Import CSV Files into R
How to Import Excel Files into R

Leave a Reply

Your email address will not be published.