我喜欢在一个数据帧的多个列上运行多个单向ANOVA。我这样做的方法是使用for循环。我的数据框架的第一列包含组。为了提供一个可重复的例子,我在这里取虹膜数据集。我想使用rstatix::anova_test()而不是f.ex。aov(),因为rstatix::anova_test()是管道友好的,似乎是一个更好的选择,不平衡的数据(就像我有它),也允许定义的平方和类型的方差。
当我用aov()编写for循环时,它可以工作。不幸的是,到目前为止,我在rstatix::anova_test()方面做类似的工作都失败了。有人能帮我吗?
data <- iris %>% relocate(Species, .before = Sepal.Length)
# Define object which will receive the results
results <- NULL
results <- as.data.frame(results)对于aov(),它可以工作。
for(i in 2:ncol(data)){
# Put the name of the variable in first column of results object
results[i-1,1] <- names(data)[i]
# ANOVA test iterating through each column of the data frame and save output in a temporary object.
temp_anova_results <- broom::tidy(aov(data[,i] ~ Species, data = data))
# write ANOVA p value in second column of results object
results[i-1,2] <- temp_anova_results$p.value[1]
rm(temp_anova_results)
} 出于几个原因,我喜欢使用rstatix::anova_test(),但未能获得正确的for循环,我尝试了一个示例:
for(i in 2:ncol(data)){
# Put the name of the variable in first column of results object
results[i-1,1] <- names(data)[i]
# ANOVA test iterating through each column of the data frame and save output in a temporary object.
temp_anova_results <- data %>% anova_test(data[,i] ~ Species, type = 3)
# write ANOVA p value in second column of results object
results[i-1,2] <- temp_anova_results$p[1]
rm(temp_anova_results)
} data %>% anova_test(data[,i] ~ Species)似乎是问题所在,但在为i插入数字时(如f.ex ),它在for循环之外工作。data %>% anova_test(data[,2] ~ Species)
发布于 2022-07-09 11:57:08
也许其他人有一个更好的答案,但我能让它工作的唯一方法是从列名构建公式,即用以下方式替换anova_test行:
temp_anova_results <- data %>% anova_test(formula(paste0(names(dat)[i],"~","Species")))我不知道为什么你的方法行不通。即使在循环之外,使用i而不是数字常量也会中断anova_test函数调用。
https://stackoverflow.com/questions/72920778
复制相似问题