How to repeat a whole data.table object in R?



To repeat a whole data.table object in R, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use rep function to repeat the data.table object.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,2)
DT<-data.table(x,y,z)
DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x y  z
1:  3 3  4
2:  2 5  0
3:  2 6  1
4:  1 4  1
5:  3 6  1
6:  2 5  1
7:  1 1  3
8:  4 4  2
9:  2 3  1
10: 2 5  3
11: 2 4  2
12: 3 11 1
13: 0 3  2
14: 1 4  3
15: 4 4  1
16: 3 6  3
17: 1 3  2
18: 2 5  3
19: 1 1  1
20: 1 7  5

Repeat the data.table object

Using rep function to repeat the data.table object DT two times −

library(data.table)
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,2)
DT<-data.table(x,y,z)
DT[rep(1:nrow(DT),2),]

Output

    x y  z
1:  3 3  4
2:  2 5  0
3:  2 6  1
4:  1 4  1
5:  3 6  1
6:  2 5  1
7:  1 1  3
8:  4 4  2
9:  2 3  1
10: 2 5  3
11: 2 4  2
12: 3 11 1
13: 0 3  2
14: 1 4  3
15: 4 4  1
16: 3 6  3
17: 1 3  2
18: 2 5  3
19: 1 1  1
20: 1 7  5
21: 3 3  4
22: 2 5  0
23: 2 6  1
24: 1 4  1
25: 3 6  1
26: 2 5  1
27: 1 1  3
28: 4 4  2
29: 2 3  1
30: 2 5  3
31: 2 4  2
32: 3 11 1
33: 0 3  2
34: 1 4  3
35: 4 4  1
36: 3 6  3
37: 1 3  2
38: 2 5  3
39: 1 1  1
40: 1 7  5
    x y  z

Advertisements