为什么 replicate() 在 R 中不产生数字输出?

Why replicate() doesn't produce numeric output in R?

我有一个简单的方差分析模拟函数。但是,我想知道为什么我的 replicate() 命令没有生成数字 table?

fun <- function(eta.sq = .25, groups = 4, n = 10, bet.var = 10){

 with.var = bet.var*(1/eta.sq - 1)  
        N = groups*n
sim.means = rnorm(n = groups, mean = 0, sd = sqrt(bet.var))
 sim.data = data.frame(group = gl(groups, 1, length = N),
                   response = rnorm(N, sim.means, sqrt(with.var)))
sim.anova = anova(aov(response ~ group, sim.data))
}
# Problem part:
t(replicate(5, fun())) # Why I don't get a numeric table?

这是我得到的 table:

       Df        Sum Sq    Mean Sq   F value   Pr(>F)   
[1,] Integer,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2
[2,] Integer,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2
[3,] Integer,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2
[4,] Integer,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2
[5,] Integer,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2 

如果我们查看 str

,则输出为 list
str(replicate(5, fun()))

replicate 也可以选择 return 一个 list 而不是将其简化为 matrix

lst <- replicate(5, fun(), simplify = FALSE)
do.call(rbind, lst)

注意输出将有 anovadata.frame 作为 类


但是,如果我们需要 tidy 方法

library(broom)
library(dplyr)
replicate(5, tidy(fun()), simplify = FALSE) %>%
       bind_rows
#       term df     sumsq    meansq statistic      p.value
#1      group  3  347.4035 115.80116  4.745358 6.868048e-03
#2  Residuals 36  878.5094  24.40304        NA           NA
#3      group  3  110.6498  36.88326  1.007709 4.005809e-01
#4  Residuals 36 1317.6389  36.60108        NA           NA
#5      group  3  324.2699 108.08996  3.356833 2.930515e-02
#6  Residuals 36 1159.1992  32.19998        NA           NA
#7      group  3 1432.8601 477.62004 12.968940 6.745457e-06
#8  Residuals 36 1325.8078  36.82799        NA           NA
#9      group  3  840.2489 280.08298  6.961525 8.193557e-04
#10 Residuals 36 1448.3876  40.23299        NA           NA