Convert data.frame to data.table in R (Example)

 

In this tutorial you’ll learn how to change a data.frame to data.table class in R.

The content of the article is structured as follows:

Let’s dig in…

 

Introducing Example Data

Let’s first create some example data in R.

data <- data.frame(x1 = letters[1:4],    # Example data
                   x2 = 3,
                   x3 = 1:4)
data                                     # Print data
#   x1 x2 x3
# 1  a  3  1
# 2  b  3  2
# 3  c  3  3
# 4  d  3  4

As you can see based on the previous output of the RStudio console, the example data contains four rows and three columns. Let’s check the data type of our data by using the class function:

class(data)                              # Check class
# "data.frame"

It’s a data.frame!

 

Example: Convert data.frame to data.table Using setDT Function

The following R programming code shows how to change the data.frame class to the data.table class in R. First, we need to install and load the data.table package:

install.packages("data.table")           # Install and load data.table
library("data.table")

Now, we can use the setDT function of the data.table package to convert a data.frame to a data.table as follows:

setDT(data)                              # Convert data.frame to data.table

Let’s have a look at the structure of our data:

data                                     # Print updated data
#    x1 x2 x3
# 1:  a  3  1
# 2:  b  3  2
# 3:  c  3  3
# 4:  d  3  4

As you can see, the values are the same as in our original data.frame. Let’s also check the class:

class(data)                              # Check class
# "data.table" "data.frame"

It’s a data.table!

 

Video & Further Resources

Would you like to learn more about the conversion of data.frames to data.tables? Then you might want to watch the following video of my YouTube channel. I explain the contents of this article in the video tutorial:

 

The YouTube video will be added soon.

 

Furthermore, you may have a look at some of the other articles on my website:

 

You learned in this tutorial how to set a data.frame matrix as a data.table in R. Let me know in the comments section below, in case you have additional questions. Furthermore, please subscribe to my email newsletter in order to receive updates on the newest tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top