【问题标题】:R: Combination of Anova-test (aov), for-Loop and paste results in errorR:Anova-test (aov)、for-Loop 和 paste 的组合导致错误
【发布时间】:2021-10-29 11:36:35
【问题描述】:

我已经构建了一个 for 循环,用于对一组因变量和自变量进行 Anova 测试。为了遍历这些变量,这些变量都位于我的数据框main 中,我创建了两个具有因变量和自变量的向量(分别为DependentVariablesAnova 和IndependentVariablesAnova)。

我还加入了粘贴功能,以便相应地命名结果测试。

for(i in 1:length(DependentVariablesAnova)){
  for(j in 1:length(IndependentVariablesAnova)){
    paste("Anova", c(DependentVariablesAnova[i]), c(IndependentVariablesAnova[j])) <- aov(c(DependentVariablesAnova[i]) ~ c(IndependentVariablesAnova[j]), data = main)
  }
}

上述代码导致以下错误消息:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels
In addition: Warning message:
In storage.mode(v) <- "double" :
 Show Traceback
 
 Rerun with Debug
 Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels 

我假设我的问题有一个相当简单的快速解决方案。如果不是这种情况并且需要工作样本,请随时告诉我。

【问题讨论】:

  • 我不知道aov 函数是做什么的,但可以肯定的是,像paste(...) &lt;- ... 这样的函数是行不通的。 paste(..) 调用返回一个字符向量(其参数的串联),所以你不能给它赋值!
  • 请提供示例数据并显示您的预期输出(是aov 输出的summary/tidy 版本吗?)。见minimal reproducible example。

标签: r loops for-loop anova


【解决方案1】:

这是一种使用来自purrr 包的map 的方法。
如果您愿意,也可以在基本 R 中使用 apply 中的相同方法,尽管这会使标记 DV 变得更加困难。

library(tidyverse)

map_df(dvs, function(dv) {
  map_df(ivs, function(iv) {
    frm <- as.formula(paste(dv, "~", iv))
    aov(frm, data = main) %>% broom::tidy(.)
  })
}, .id = "dv")

输出

# A tibble: 8 x 7
  dv    term         df  sumsq meansq statistic p.value
  <chr> <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
1 w     x             2  1.53   0.764     0.827  0.440 
2 w     Residuals    97 89.6    0.923    NA     NA     
3 w     z             2  3.54   1.77      1.96   0.146 
4 w     Residuals    97 87.5    0.903    NA     NA     
5 y     x             2  5.49   2.74      3.13   0.0481
6 y     Residuals    97 85.0    0.876    NA     NA     
7 y     z             2  0.992  0.496     0.538  0.586 
8 y     Residuals    97 89.5    0.923    NA     NA     

数据:

n <- 100
main <- tibble(w = rnorm(n), 
               x = sample(letters[1:3], n, replace = TRUE) %>% as.factor,
               y = rnorm(n),
               z = sample(letters[4:6], n, replace = TRUE) %>% as.factor)

dvs <- c("w", "y") %>% set_names()
ivs <- c("x", "z")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多