考虑以下数据框:
type = c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D')
val1 = c(.35, .36, .35, .22, .27, .25, .88, .9, .87, .35, .35, .36)
val2 = c(.35, .35, .37, .40, .42, .46, .9, .91, .82, .36, .36, .36)
df = data.frame (type, val1, val2)
我有四个类别(称为类型;A、B、C 和 D)。可以对每种类型的三个观测值进行平均以创建类型多元均值(由 val1 和 val2 的均值组成)。我想使用 Hotelling 的测试来比较所有可能的类型组合(AB、AC、AD、BC、BD、CD),以确定哪种类型均值(如果有)相同。我可以将其硬编码为:
a = filter (df, type == "A") [,2:3]
b = filter (df, type == "B") [,2:3]
c = filter (df, type == "C") [,2:3]
d = filter (df, type == "D") [,2:3]
然后对每个指定的类型对运行 Hotelling 的 T2 测试:
library('Hotelling')
hotelling.test(a, b, shrinkage=FALSE)
hotelling.test(b, c, shrinkage=FALSE)
hotelling.test(a, c, shrinkage=FALSE)
#And so on
考虑到我的实际数据集有 55 种不同的类型,这显然非常低效且不切实际。我知道答案在于 for 循环,但我很难弄清楚如何告诉 hotelling.test 比较所有可能类型组合的 val1/val2 多元均值。我对创建 for 循环非常陌生,希望有人能给我指出正确的方向。
比较所有类型后,理想情况下我能够获得一个输出,显示 Hotelling 测试 p 值 >0.05 的类型对,这意味着这两种类型可能是重复的。在示例数据帧中,类型 A 和 D 返回 p 值 >0.05,而其他比较的 p 值<0.05。
最佳答案
我们可以使用combn
来创建成对组合、数据集子集并应用函数
library(Hotelling)
outlst <- combn(as.character(unique(df$type)), 2,
FUN = function(x) hotelling.test(subset(df, type == x[1], select = -1),
subset(df, type == x[2], select = -1)), simplify = FALSE)
names(outlst) <- combn(as.character(unique(df$type)), 2, FUN = paste, collapse = "_")
outlst[1]
#$A_B
#Test stat: 36.013
#Numerator df: 2
#Denominator df: 3
#P-value: 0.007996
关于r - 如何循环遍历 R 中所有可能的因子水平比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60139980/