我有一个数据集,包括1个问题(Q1-Q10)。我想提取成对Stuart-Maxwell测试的P值,并将它们打印在带有列名称标题的矩阵中,以便我可以检测哪个P值指的是哪个成对比较。我收到了专家的帮助,如何运行测试并提取结果,我试图用标题制作矩阵,但我失败了。如果有人可以修改我的代码,我感激不尽。
data <- data.frame(Q1=sample(1:5, 20, replace=T),
Q2=sample(1:5, 20, replace=T),
Q3=sample(1:5, 20, replace=T),
Q4=sample(1:5, 20, replace=T),
Q5=sample(1:5, 20, replace=T),
Q6=sample(1:5, 20, replace=T),
Q7=sample(1:5, 20, replace=T),
Q8=sample(1:5, 20, replace=T),
Q9=sample(1:5, 20, replace=T),
Q10=sample(1:5, 20,replace=T) ) #fake data
Labels<- names(data)
# Matrix to store the result
enter code here
groups <- unique( Labels )
result <- matrix(NA, nc=length(groups), nr=length(groups))
colnames(result) <- rownames(result) <- groups
# Loop
for( g1 in groups ) {
for( g2 in groups ) {
result[ g1, g2 ] <-
sapply(labels <-combn(groups, 2, simplify = FALSE), function(i) {
require(irr)
xtab <- table(data[,i[1]], data[,i[2]])
test <- try(stuart.maxwell.mh(xtab))
ifelse(class(test) == "try-error", NA, test$p)
})
}
}
result
答案 0 :(得分:2)
你很亲密。你只是混淆了两种方法。您应该将sapply
与combn
或双for-loop
一起使用。在您的情况下,基于您想要的输出for-loop
似乎更容易:
require(irr)
data <- data.frame(Q1=sample(1:5, 20, replace=T),
Q2=sample(1:5, 20, replace=T),
Q3=sample(1:5, 20, replace=T),
Q4=sample(1:5, 20, replace=T),
Q5=sample(1:5, 20, replace=T),
Q6=sample(1:5, 20, replace=T),
Q7=sample(1:5, 20, replace=T),
Q8=sample(1:5, 20, replace=T),
Q9=sample(1:5, 20, replace=T),
Q10=sample(1:5, 20,replace=T) ) #fake data
# Loop
labels<- names(data)
groups <- unique(labels)
result <- matrix(NA, nc=length(groups), nr=length(groups))
colnames(result) <- labels
rownames(result) <- labels
for( g1 in groups ) {
for( g2 in groups ) {
xtab <- table(data[,g1], data[,g2])
test <- try(stuart.maxwell.mh(xtab), silent = TRUE)
pval <- ifelse(class(test) == "try-error", NA, test$p)
result[g1, g2] <- pval
}
}
输出:
> result
Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8
Q1 NA 0.05881900 0.26298902 NA 0.7790233 0.5177394 0.73754470 0.30610257
Q2 0.0588190 NA 0.58635825 NA 0.1005838 0.3678794 0.17078180 0.05626191
Q3 0.2629890 0.58635825 NA 0.3173105 0.3916252 0.2541583 0.09984288 0.07472086
Q4 0.3173105 0.36787944 NA NA NA NA NA NA
Q5 0.7790233 0.10058381 0.39162518 0.2231302 NA 0.3114032 0.14247485 0.17708783
Q6 0.5177394 0.36787944 0.25415830 NA 0.3114032 NA 0.21636999 1.00000000
Q7 0.7375447 0.17078180 0.09984288 NA 0.1424749 0.2163700 NA 0.41099506
Q8 0.3061026 0.05626191 0.07472086 0.3173105 0.1770878 1.0000000 0.41099506 NA
Q9 0.6712714 0.53408090 0.16832466 0.3173105 0.2110881 0.2635971 0.28933534 0.31414685
Q10 0.2220359 0.38332585 0.05941603 1.0000000 0.1652989 0.2578472 0.23889094 0.08826479
#the output is truncated