对于数值数据,您有解决方案。但它是分类数据,你说。然后生活变得有点复杂......
首先:两个分类变量之间的关联量不是用 Spearman 等级相关性来衡量的,而是用卡方检验来衡量的。这实际上是逻辑。排名意味着您的数据中有一定的顺序。现在告诉我哪个更大,黄色还是红色?我知道,有时 R 确实对分类数据执行 spearman 等级相关。如果我编码黄色 1 和红色 2,R 会认为红色大于黄色。
所以,别管斯皮尔曼的分类数据了。我将演示 chisq-test 以及如何使用 combn() 选择列。但是您会从 Agresti 的书中受益更多:
http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937
set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)
table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction
#Let's make a matrix with tons of columns
Data <- as.data.frame(
matrix(
sample(letters[1:3],2000,replace=T),
ncol=25
)
)
# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]
# say you need to know which ones are associated with each other.
out <- apply( combn(columns,2),2,function(x){
chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
})
out <- cbind(as.data.frame(t(combn(vars,2))),out)
那么你应该得到:
> out
V1 V2 out
1 V3 V7 0.8116733
2 V3 V11 0.1096903
3 V3 V24 0.1653670
4 V7 V11 0.3629871
5 V7 V24 0.4947797
6 V11 V24 0.7259321
其中 V1 和 V2 表示它在哪些变量之间进行,“out”给出关联的 p 值。这里所有的变量都是独立的。这是您所期望的,因为我是随机创建数据的。