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

Updated on: 13-Aug-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements