How to Convert Data Frame to Data Table in R

Here are two ways to convert DataFrame to DataTable in R:

  1. Using the setDT() function
  2. Using the as.data.table() function

Method 1: Using the setDT() function

The best and easiest way to convert a data frame to a data table is to use the “setDT()” function. The setDT() function accepts a data frame as an argument and returns the data table.

library("data.table")

df <- data.frame(
      students = c("Michael", "Justin", "Taylor", "Selena", 
                   "Michael", "Michael", "Taylor"),
      marks = c(90, 80, 85, 75, 89, 87, 89),
      levels = c(10, 7, 8, 7, 6, 8, 5)
)

print(df)

cat("----After converting from data frame to data table----", "\n")

dt <- setDT(df)
print(dt)

Output

   students  marks  levels
1   Michael   90      10
2   Justin    80       7
3   Taylor    85       8
4   Selena    75       7
5   Michael   89       6
6   Michael   87       8
7   Taylor    89       5

----After converting from data frame to data table----

   students  marks  levels
1:  Michael   90      10
2:  Justin    80       7
3:  Taylor    85       8
4:  Selena    75       7
5:  Michael   89       6
6:  Michael   87       8
7:  Taylor    89       5

Method 2: Using as.data.table() function

Another way to convert a data frame to a data table is to use the as.data.table() function from the data.table package.

library("data.table")

df <- data.frame(
   students = c("Michael", "Justin", "Taylor", "Selena", 
                "Michael", "Michael", "Taylor"),
   marks = c(90, 80, 85, 75, 89, 87, 89),
   levels = c(10, 7, 8, 7, 6, 8, 5)
)

print(df)

cat("----After converting from data frame to data table----", "\n")

dt <- as.data.table(df)

print(dt)

Output

   students  marks  levels
1   Michael   90      10
2   Justin    80       7
3   Taylor    85       8
4   Selena    75       7
5   Michael   89       6
6   Michael   87       8
7   Taylor    89       5

----After converting from data frame to data table----

   students  marks  levels
1:  Michael   90      10
2:  Justin    80       7
3:  Taylor    85       8
4:  Selena    75       7
5:  Michael   89       6
6:  Michael   87       8
7:  Taylor    89       5

That’s it!

Leave a Comment