Skip to content

Instantly share code, notes, and snippets.

@clayford
Created November 21, 2023 15:09
Show Gist options
  • Save clayford/600f6225e5d6d3316a64556ba1e70f8e to your computer and use it in GitHub Desktop.
Save clayford/600f6225e5d6d3316a64556ba1e70f8e to your computer and use it in GitHub Desktop.
For loops to count concordant and discordant pairs
# Table 2.8, Agresti (2002) p. 57
M <- as.table(rbind(c(1, 3, 10, 6),
c(2, 3, 10, 7),
c(1, 6, 14, 12),
c(0, 1, 9, 11)))
dimnames(M) <- list(`income` = c("<15", "15-25", "25-40", ">40"),
`job satisfaction` = c("VD", "LD", "MS","VS"))
# count concordant pairs
n <- nrow(M)
m <- ncol(M)
row.x <- row(M)
col.x <- col(M)
C <- numeric(length = (nrow(M)-1) * (ncol(M)-1))
k <- 1
for(i in 1:(n-1)){
for(j in 1:(m-1)){
C[k] <- M[i,j] * sum(M[row.x > i & col.x > j])
k <- k + 1
}
}
Concordant <- sum(C)
# count discordant pairs
D <- numeric(length = (nrow(M)-1) * (ncol(M)-1))
k <- 1
for(i in 1:(n-1)){
for(j in 2:m){
D[k] <- M[i,j] * sum(M[row.x > i & col.x < j])
k <- k + 1
}
}
Discordant <- sum(D)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment