如何在 R 中的 table() 中添加标签

jac*_*cob 7 r

我想打印 2*2 混淆矩阵并标记它。我table()在 r 中使用。

请点击此处查看表格

我想添加预测和现实标签。任何人都可以建议我,我该怎么做?

lef*_*fft 5

这是一个与此问题中的问题类似的问题。您可以遵循这种方法,但只需使用矩阵来保存值,并将其维度名称设置为"predicted"and来简化一些事情"observed"

# create some fake data (2x2, since we're building a confusion matrix) 
dat <- matrix(data=runif(n=4, min=0, max=1), nrow=2, ncol=2, 
              dimnames=list(c("pos", "neg"), c("pos", "neg")))

# now set the names *of the dimensions* (not the row/colnames)
names(dimnames(dat)) <- c("predicted", "observed")

# and we get what we wanted
dat

# output: 
#             observed
#   predicted       pos       neg
#         pos 0.8736425 0.7987779
#         neg 0.2402080 0.6388741
Run Code Online (Sandbox Code Playgroud)

更新:@thelatemail 在评论中提出了一个很好的观点,即您可以在创建表时指定维度名称。矩阵也是如此,除了dimnames在调用 时将它们作为列表元素的名称提供matrix()。所以这里有一个更紧凑的方式:

matrix(data=runif(n=4, min=0, max=1), nrow=2, ncol=2, 
       dimnames=list(predicted=c("pos", "neg"), observed=c("pos", "neg")))
Run Code Online (Sandbox Code Playgroud)