Here are two ways to convert DataFrame to DataTable in R:
- Using the setDT() function
- 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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.