Cohen’s kappa

ckappa.factor R Documentation

Description

The kappa()-function computes Cohen’s \(\kappa\), a statistic that measures inter-rater agreement for categorical items between two vectors of predicted and observed factor() values. The weighted.ckappa() function computes the weighted \(\kappa\)-statistic.

If \(\beta \neq 0\) the off-diagonals of the confusion matrix are penalized with a factor of \((y_{+} - y_{i,-})^\beta\). See below for further details.

Usage

## S3 method for class 'factor'
ckappa(actual, predicted, beta = 0, ...)

## S3 method for class 'factor'
weighted.ckappa(actual, predicted, w, beta = 0, ...)

## S3 method for class 'cmatrix'
ckappa(x, beta = 0, ...)

ckappa(...)

weighted.ckappa(...)

Arguments

actual

A vector of <factor>- of length \(n\), and \(k\) levels.

predicted

A vector of <factor>-vector of length \(n\), and \(k\) levels.

beta

A <numeric> value of length 1 (default: 0). If set to a value different from zero, the off-diagonal confusion matrix will be penalized.

Arguments passed into other methods

w

A <numeric>-vector of length \(n\). NULL by default.

x

A confusion matrix created cmatrix().

Value

If micro is NULL (the default), a named <numeric>-vector of length k

If micro is TRUE or FALSE, a <numeric>-vector of length 1

Calculation

\[ \frac{\rho_p - \rho_e}{1-\rho_e} \]

where \(\rho_p\) is the empirical probability of agreement between predicted and actual values, and \(\rho_e\) is the expected probability of agreement under random chance.

Examples

# 1) recode Iris
# to binary classification
# problem
iris$species_num <- as.numeric(
  iris$Species == "virginica"
)

# 2) fit the logistic
# regression
model <- glm(
  formula = species_num ~ Sepal.Length + Sepal.Width,
  data    = iris,
  family  = binomial(
    link = "logit"
  )
)

# 3) generate predicted
# classes
predicted <- factor(
  as.numeric(
    predict(model, type = "response") >` 0.5
  ),
  levels = c(1,0),
  labels = c("Virginica", "Others")
)

# 3.1) generate actual
# classes
actual <- factor(
  x = iris$species_num,
  levels = c(1,0),
  labels = c("Virginica", "Others")
)

# 4) evaluate model performance with
# Cohens Kappa statistic
cat(
  "Kappa", ckappa(
    actual    = actual,
    predicted = predicted
  ),
  "Kappa (penalized)", ckappa(
    actual    = actual,
    predicted = predicted,
    beta      = 2
  ),
  "Kappa (weigthed)", weighted.ckappa(
    actual    = actual,
    predicted = predicted,
    w         = iris$Petal.Length/mean(iris$Petal.Length)
  ),
  sep = "\n"
)