- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a column to data.table object in R?
To add a column to data.table object, we can follow the below steps −
- First of all, create a data.table object.
- Add a column to the object using := function
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-rpois(20,5) y<-rpois(20,1) DT<-data.table(x,y) DT
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y 1: 5 1 2: 4 0 3: 4 0 4: 7 2 5: 2 2 6: 6 0 7: 3 0 8: 7 3 9: 4 0 10: 4 1 11: 6 3 12: 4 1 13: 4 0 14: 6 0 15: 5 1 16: 5 5 17: 9 0 18: 5 2 19: 5 1 20: 5 1
Add a column to the data.table object
Use := function to add a new column to DT −
library(data.table) x<-rpois(20,5) y<-rpois(20,1) DT<-data.table(x,y) DT[,z:=rpois(20,2)] DT
Output
x y z 1: 5 1 5 2: 4 0 2 3: 4 0 1 4: 7 2 3 5: 2 2 3 6: 6 0 1 7: 3 0 2 8: 7 3 2 9: 4 0 1 10: 4 1 1 11: 6 3 1 12: 4 1 1 13: 4 0 1 14: 6 0 1 15: 5 1 2 16: 5 5 0 17: 9 0 3 18: 5 2 2 19: 5 1 2 20: 5 1 1
- Related Articles
- How to add a new column to a data frame using mutate in R?
- How to add a rank column in base R of a data frame?
- How to add a column in an R data frame with consecutive numbers?
- How to add a column between columns or after last column in an R data frame?
- How to add single quotes to strings in an R data frame column?
- How to add a column in a table in MySQL?
- How to add a column to a MySQL table in Python?
- How to add a new column in an R data frame with count based on factor column?
- How to add a new column to a matrix in R?
- How to add columns with square of each column in R data frame?
- How to add a string before each numeric value in an R data frame column?
- How to add a new column to represent the percentage for groups in an R data frame?
- How to add a new column to an R data frame with largest value in each row?
- How to add suffix to column names in R?
- How to add subtotal to a table column displaying NULL in MySQL?

Advertisements