Search code examples
rpivot-table

Cross tabulation in R


I have a data set consisting of subjects scored by two raters. I would like to obtain a crosstab of cases where rater agreement was found.

# Column names
pro <- c("P1", "P2", "P3", "P4", "P5")

# Rows
R1 <- c("Poor", "Acceptable", "Acceptable", "Good", "Acceptable")
R2 <- c("Poor", "Acceptable", "Good", "Good", "Acceptable")

# Data
data1 <- rbind(R1, R2)
colnames(data1) <- pro
as.data.frame(data1)

Desired Result (R1's ratings in the rows, R2's ratings in the columns):

Poor Acceptable Good
1 0 0
0 2 1
0 0 1

Solution

  • For cross tabulation there is xtabs :

    xtabs(~R1 + R2)
    

    To have the rows and columns order in the question, use

    levs <- c("Poor", "Acceptable", "Good")
    R1 <- factor(R1, levels = levs)
    R2 <- factor(R2, levels = levs)
    xtabs(~R1 + R2)