How to convert data.table object into a matrix in R?


A data.table object is very similar to a data frame in R, therefore, converting a data.table object to a matrix is not a difficult job. We just need to use as.matrix function and store the data.table object into a new object that will belong to the matrix, otherwise R will not be able to convert the data.object to a matrix. For example, if we have a data.table object DT then to convert it into a matrix, we should use the below example code −

DT_matrix<-as.matrix(DT)

Loading data.table package −

library(data.table)

Creating a data.table object −

Example

x1<-rnorm(20,1,0.04)
x2<-rnorm(20,5,1.2)
x3<-runif(20,5,10)
x4<-runif(20,1,5)
DT1<-data.table(x1,x2,x3,x4)
DT1

Output

x1 x2 x3 x4
1: 0.9785610 7.345365 8.079572 4.289080
2: 0.9787770 6.684993 6.842196 3.420399
3: 0.9936527 5.076511 6.584490 4.339317
4: 0.9585088 6.348905 5.256956 1.041050
5: 1.0172288 6.076759 6.456343 3.964968
6: 1.0199971 6.384019 6.444665 2.477480
7: 1.0027680 5.189908 6.352739 3.358625
8: 1.0013410 7.480771 6.236253 3.704360
9: 0.9638484 3.173219 6.768095 2.710411
10: 0.9771605 4.072879 5.269356 3.689747
11: 0.9768464 3.898211 8.212824 1.230352
12: 1.0322361 4.964122 8.062670 2.333302
13: 0.9730514 2.746493 7.991256 1.319675
14: 1.0157617 4.032643 7.324038 3.883257
15: 1.0167210 6.994750 5.123840 3.157113
16: 0.9526550 5.292459 8.401666 2.362798
17: 1.0022340 4.753125 6.175266 3.900407
18: 1.0456185 6.001135 8.018412 3.324448
19: 1.1422387 5.121760 5.340800 2.348761
20: 0.9269784 5.893736 5.754917 1.940769

is.matrix(DT1_matrix) 

[1] TRUE

Let’s have a look at another example −

Example

y1<-rpois(20,2)
y2<-rpois(20,5)
y3<-rpois(20,8)
y4<-rpois(20,10)
y5<-sample(0:9,20,replace=TRUE)
DT2<-data.table(y1,y2,y3,y4,y5)
DT2

Output

   y1 y2  y3   y4   y5
1: 2  5   12   12   7
2: 2  7   9    8   1
3: 2  5   3    9   2
4: 0  0   10   12   9
5: 2  3   5    8   8
6: 4  7   6   8    9
7: 2  7   8   9    0
8: 0  7   8   11   1
9: 3  6   7   8    2
10: 0  3   8  9    1
11: 2  7  9   9    2
12: 3  4  8   7   7
13: 0  1  10  14 8
14: 1  6  7   5 9
15: 3  3   12 14 6
16: 0  4   8   8 4
17: 1  7   9  13 2
18: 5  1   14  11 7
19: 1 4   14   9 6
20: 3 5   8   10 1

Converting data.table object into a matrix object −

Example

DT2_matrix<-as.matrix(DT2)
DT2_matrix

Output

     y1  y2  y3   y4 y5
[1,] 2   5   12   12 7
[2,] 2   7   9   8 1
[3,] 2   5   3   9 2
[4,] 0   0   10 12 9
[5,] 2   3   5 8 8
[6,] 4   7   6 8 9
[7,] 2   7   8 9 0
[8,] 0   7   8 11 1
[9,] 3   6   7 8 2
[10,] 0  3   8 9 1
[11,] 2  7   9 9 2
[12,] 3 4 8 7 7
[13,] 0 1 10 14 8
[14,] 1 6 7 5 9
[15,] 3 3 12 14 6
[16,] 0 4 8 8 4
[17,] 1 7 9 13 2
[18,] 5 1 14 11 7
[19,] 1 4 14 9 6
[20,] 3 5 8 10 1

is.matrix(DT2_matrix) 

[1] TRUE

Updated on: 16-Oct-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements