如何将data.table对象转换为R中的矩阵?
data.table对象与R中的数据帧非常相似,因此,将data.table对象转换为矩阵并不困难。我们只需要使用as.matrix函数并将data.table对象存储到属于该矩阵的新对象中,否则R将无法将data.object转换为矩阵。例如,如果我们有一个data.table对象DT,然后将其转换为矩阵,则应使用以下示例代码-
DT_matrix<-as.matrix(DT)
加载data.table包-
library(data.table)
创建一个data.table对象-
示例
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
输出结果
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]是
让我们看另一个例子-
示例
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
输出结果
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
将data.table对象转换为矩阵对象-
示例
DT2_matrix<-as.matrix(DT2) DT2_matrix
输出结果
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]是