【问题标题】:Creating contingency table from matrix从矩阵创建列联表
【发布时间】:2016-02-18 00:44:28
【问题描述】:

我有一个这样的矩阵:

       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。

【问题讨论】:

  • table(as.data.frame(myMatrix))。为什么它被存储为矩阵?

标签: r


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2017-04-15
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多