首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多列数据帧上的rstatix::anova_test()

多列数据帧上的rstatix::anova_test()
EN

Stack Overflow用户
提问于 2022-07-09 10:56:23
回答 1查看 118关注 0票数 0

我喜欢在一个数据帧的多个列上运行多个单向ANOVA。我这样做的方法是使用for循环。我的数据框架的第一列包含组。为了提供一个可重复的例子,我在这里取虹膜数据集。我想使用rstatix::anova_test()而不是f.ex。aov(),因为rstatix::anova_test()是管道友好的,似乎是一个更好的选择,不平衡的数据(就像我有它),也允许定义的平方和类型的方差。

当我用aov()编写for循环时,它可以工作。不幸的是,到目前为止,我在rstatix::anova_test()方面做类似的工作都失败了。有人能帮我吗?

代码语言:javascript
复制
data <- iris %>% relocate(Species, .before = Sepal.Length)

# Define object which will receive the results
results <- NULL
results <- as.data.frame(results)

对于aov(),它可以工作。

代码语言:javascript
复制
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循环,我尝试了一个示例:

代码语言:javascript
复制
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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-09 11:57:08

也许其他人有一个更好的答案,但我能让它工作的唯一方法是从列名构建公式,即用以下方式替换anova_test行:

代码语言:javascript
复制
temp_anova_results <- data %>% anova_test(formula(paste0(names(dat)[i],"~","Species")))

我不知道为什么你的方法行不通。即使在循环之外,使用i而不是数字常量也会中断anova_test函数调用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72920778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档