如果您知道如何计算单个 p 值,则可以将该代码放入循环中。
# Sample data
d <- data.frame(
group = paste( "group", rep(1:5, each=100) ),
value = rnorm( 5*100 )
)
# Matrix to store the result
groups <- unique( d$group )
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 ] <- t.test(
d$value[ d$group == g1 ],
d$value[ d$group == g2 ]
)$p.value
}
}
result
# group 1 group 2 group 3 group 4 group 5
# group 1 1.0000000 0.6533393 0.7531349 0.6239723 0.6194475
# group 2 0.6533393 1.0000000 0.9047020 0.9985489 0.3316215
# group 3 0.7531349 0.9047020 1.0000000 0.8957871 0.4190027
# group 4 0.6239723 0.9985489 0.8957871 1.0000000 0.2833226
# group 5 0.6194475 0.3316215 0.4190027 0.2833226 1.0000000
你也可以使用outer
:
groups <- unique( d$group )
outer(
groups, groups,
Vectorize( function(g1,g2) {
t.test(
d$value[ d$group == g1 ],
d$value[ d$group == g2 ]
)$p.value
} )
)