从矩阵创建列联表

时间:2016-02-18 00:44:28

标签: r

我有一个像这样的矩阵:

       country cLabel
  [1,]       3      1
  [2,]       6      2
  [3,]       8      1
  [4,]       5      2
  [5,]       5      2
  [6,]       8      2
  [7,]       8      2
  [8,]       8      2
  [9,]       8      2
 [10,]       4      2
 [11,]       6      2
 [12,]       3      2
 [13,]       5      2
 [14,]       5      1

country的值为1-8,cLabel的值为1-2。如何为此打印列联表?我试过print(table(myMatrix))

正在打印

 1   2   3   4   5   6   7   8 
60 277  31  32  83  39  24  44 

和我想要的是打印每个国家/地区的值(1-8)以及这8个值中的每一个有多少1和2。

1 个答案:

答案 0 :(得分:1)

我想某处有重复。

# Turn your matrix into a data.frame, easier to manipulate and to create labels
myDataFrame <- as.data.frame(myMatrix)

# Add factors to coutry, from 1 to 8. This will add missing levels to the final result
myDataFrame$country <- factor(myDataFrame$country, 1:8)

# Table
table(myDataFrame)
#        cLabel
# country 1 2
#       1 0 0
#       2 0 0
#       3 1 1
#       4 0 1
#       5 1 3
#       6 0 2
#       7 0 0
#       8 1 4
相关问题