为什么Cohen的kappa计算在这个列联表上的不同包中失败了?

时间:2012-08-09 10:54:03

标签: r package

我有一个列联表,我想计算Cohens的kappa - 协议水平。我尝试过使用三种不同的软件包,这些软件包在某种程度上似乎都失败了。包e1071具有专门用于列联表的功能,但似乎也失败了。下面是可重现的代码。您需要安装包concorde1071irr

# Recreate my contingency table, output with dput
conf.mat<-structure(c(810531L, 289024L, 164757L, 114316L), .Dim = c(2L, 
2L), .Dimnames = structure(list(landsat_2000_bin = c("0", "1"
), MOD12_2000_binForest = c("0", "1")), .Names = c("landsat_2000_bin", 
"MOD12_2000_binForest")), class = "table")

library(concord)
cohen.kappa(conf.mat)
library(e1071)
classAgreement(conf.mat, match.names=TRUE)
library(irr)
kappa2(conf.mat) 

我从运行中获得的输出是:

> cohen.kappa(conf.mat)
Kappa test for nominally classified data
4 categories - 2 methods
kappa (Cohen) = 0 , Z = NaN , p = NaN 
kappa (Siegel) = -0.333333 , Z = -0.816497 , p = 0.792892 
kappa (2*PA-1) = -1 

> classAgreement(conf.mat, match.names=TRUE)
    $diag
[1] 0.6708459
    $kappa
[1] NA
    $rand
[1] 0.5583764
    $crand
[1] 0.0594124
    Warning message:
In ni[lev] * nj[lev] : NAs produced by integer overflow

> kappa2(conf.mat) 
 Cohen's Kappa for 2 Raters (Weights: unweighted)
Subjects = 2 
Raters = 2 
Kappa = 0 
z = NaN 
p-value = NaN

有人可以建议为什么会失败吗?我有一个大型数据集,但由于这个表很简单,我认为这不会导致这样的问题。

2 个答案:

答案 0 :(得分:3)

在第一个功能cohen.kappa中,您需要指定您使用的是计数数据,而不仅仅是n*m主题和n评分的m矩阵。

# cohen.kappa(conf.mat,'count')
cohen.kappa(conf.mat,'count')

第二个功能更棘手。出于某种原因,您的matrix已满integer而非numericinteger无法存储真正的大数字。因此,当您将两个大数字相乘时,它会失败。例如:

i=975288 
j=1099555
class(i)
# [1] "numeric"
i*j
# 1.072383e+12
as.integer(i)*as.integer(j)
# [1] NA
# Warning message:
# In as.integer(i) * as.integer(j) : NAs produced by integer overflow

所以你需要将矩阵转换为整数。

# classAgreement(conf.mat)
classAgreement(matrix(as.numeric(conf.mat),nrow=2))

最后看一下?kappa2的文档。如上所述,它需要n*m矩阵。它只适用于您的(高效)数据结构。

答案 1 :(得分:1)

你需要具体了解那些失败的原因吗?这是一个计算统计数据的函数 - 匆忙,所以我可能会在以后清理它(kappa wiki)

kap <- function(x) {
  a <- (x[1,1] + x[2,2]) / sum(x)
  e <- (sum(x[1,]) / sum(x)) * (sum(x[,1]) / sum(x)) + (1 - (sum(x[1,]) / sum(x))) * (1 - (sum(x[,1]) / sum(x)))
  (a-e)/(1-e)
}

测试/输出:

> (x = matrix(c(20,5,10,15), nrow=2, byrow=T))
     [,1] [,2]
[1,]   20    5
[2,]   10   15
> kap(x)
[1] 0.4
> (x = matrix(c(45,15,25,15), nrow=2, byrow=T))
     [,1] [,2]
[1,]   45   15
[2,]   25   15
> kap(x)
[1] 0.1304348
> (x = matrix(c(25,35,5,35), nrow=2, byrow=T))
     [,1] [,2]
[1,]   25   35
[2,]    5   35
> kap(x)
[1] 0.2592593
> kap(conf.mat)
[1] 0.1258621