提问人:Mark Davies 提问时间:11/10/2023 更新时间:11/10/2023 访问量:44
在 for 循环中执行多个 Kruskal 测试
Perform multiple Kruskal tests in for loop
问:
我想对多个变量执行 a。我已经能够通过方差分析测试做到这一点,如下所示:kruskal_test
vars = c("Sepal.Length" , "Sepal.Width" ,"Petal.Length" , "Petal.Width")
for (i in vars) {
f <- reformulate(paste(i,'~Species'))
test = aov(data = iris, f )
print(i)
print(summary(test))
但我似乎不能对 or 使用相同的方法:rstatix::kruskal_test
kruskal.test
for (i in vars) {
f <- reformulate(paste(i,'~Species'))
test = kruskal.test(data = iris,formula= f )
test = kruskal_test(data = iris,formula= f )
print(i)
print(summary(test))
}
我收到错误: kruskal.test.default(data = iris, formula = f) 中的错误: 缺少参数“x”,无默认值
或
kruskal.test.formula(formula, data = data, ...) 中的错误: “formula”缺失或不正确
答:
1赞
jay.sf
11/10/2023
#1
在你需要这种公式,aov
> reformulate(paste('Petal.Width','~Species'))
~(Petal.Width ~ Species)
而在 中,它是kruskal.test
> reformulate('Petal.Width', 'Species')
Species ~ Petal.Width
泛型函数的方法调度机制似乎存在意外问题,表明其方法选择过程中可能存在错误 (R 4.3.2)。即使参数被命名,顺序也很重要(默认顺序是 ,我们有):kruskal.test(formula, data)
kruskal.test(data, formula)
> kruskal.test(formula=Petal.Width ~ Species, data=iris)
Kruskal-Wallis rank sum test
data: Petal.Width by Species
Kruskal-Wallis chi-squared = 131.19, df = 2, p-value < 2.2e-16
然而:
> kruskal.test(data=iris, formula=Petal.Width ~ Species)
Error in kruskal.test.default(data = iris, formula = Petal.Width ~ Species) :
argument "x" is missing, with no default
如果您直接使用该方法,它会起作用
> for (i in vars) {
+ f <- reformulate(i, 'Species')
+ test <- stats:::kruskal.test.formula(data=iris, formula=f)
+ print(test)
+ }
Kruskal-Wallis rank sum test
data: Species by Sepal.Length
Kruskal-Wallis chi-squared = 107.29, df = 34, p-value = 1.596e-09
Kruskal-Wallis rank sum test
data: Species by Sepal.Width
Kruskal-Wallis chi-squared = 47.879, df = 22, p-value = 0.001125
...
不过最好使用 lapply
:
> lapply(vars, \(v) stats:::kruskal.test.formula(data=iris, formula=reformulate(v, 'Species')))
[[1]]
Kruskal-Wallis rank sum test
data: Species by Sepal.Length
Kruskal-Wallis chi-squared = 107.29, df = 34, p-value = 1.596e-09
[[2]]
Kruskal-Wallis rank sum test
data: Species by Sepal.Width
Kruskal-Wallis chi-squared = 47.879, df = 22, p-value = 0.001125
...
评论
for
lapply(iris[vars], function(x) kruskal.test(Species ~ x, data = iris))