17.8 C
London
Sunday, June 22, 2025
HomeRImport & Export Data in RHow to Use colClasses to Quickly Import Data in R

How to Use colClasses to Quickly Import Data in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories