首页 > 解决方案 > 多次随机采样向量以进行分组并进行方差分析

问题描述

我的设置参数有 50 个随机生成的数字。我想将50个随机数随机抽样成10组5个(不替换)

我想将 10 个组存储为矩阵/数据框并对这些组运行 ANOVA 测试,然后重复整个过程 1000 次,存储每次迭代的 F、F Critical、P 值。

我有以下

samp <- rnorm(50,3.47,0.0189) # 50 samples, mean of 3.47 and SD of 0.0189

for (i in 1:10){
  x <- sample(samp, 5, replace = F)
}

x <- #all my random samples

我通常在数据位于列表中时使用的方差分析代码,第二列标识组

Samp_lm <- lm(Samp_lm ~ factor(group), data = x) 
AnovaResults <- anova(Samp_lm)

criticalValues <- cbind(AnovaResults, 'F Critical Value' = qf(1 - 0.05, test.Aov[1, 1], test.Aov[2, 1]))
AnovaStats <- cbind(criticalValues[1,4],criticalValues[1,5],criticalValues[1,6]

不知道从这里去哪里。

标签: rdataframerandomsampling

解决方案


以下是我如何使用dplyrpurrr包重构您的代码。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(purrr)
set.seed(345)
samp <- rnorm(50,3.47,0.0189)

do_sampling <- function(vec, n_groups, iterations = 1000){
  #hacky 
  group_size <- length(vec)/n_groups
  if(group_size%%1!=0) stop("group sizes are uneven")
  
  #from purrr
  map_dfr(1:iterations, function(i){
    data <- tibble(
      samp = vec,
      groups = factor(sample(rep(1:group_size, each = n_groups)))
    )
    
    samp_lm <- lm(samp ~ groups, data = data)
    AnovaResults <- anova(samp_lm)
    bind_cols(
      as_tibble(AnovaResults[1,c("F value","Pr(>F)")]),
      tibble(
        `F Critical Value` = qf( 1 - 0.05, AnovaResults[1,1], AnovaResults[2,1]),
        iteration = i
      )
    )
  })
}

do_sampling(samp, 10)
#> # A tibble: 1,000 x 4
#>    `F value` `Pr(>F)` `F Critical Value` iteration
#>        <dbl>    <dbl>              <dbl>     <int>
#>  1     0.117  0.976                 2.58         1
#>  2     0.445  0.775                 2.58         2
#>  3     1.12   0.359                 2.58         3
#>  4     0.914  0.464                 2.58         4
#>  5     5.04   0.00192               2.58         5
#>  6     0.964  0.437                 2.58         6
#>  7     1.19   0.327                 2.58         7
#>  8     1.77   0.151                 2.58         8
#>  9     0.399  0.808                 2.58         9
#> 10     0.955  0.441                 2.58        10
#> # … with 990 more rows

reprex 包于 2021-05-11 创建(v1.0.0)

最后,看看inferanova 上的包装小插图。可能对你有帮助


推荐阅读