代码之家  ›  专栏  ›  技术社区  ›  rnorouzian

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

  •  1
  • rnorouzian  · 技术社区  · 7 年前

    我有一个简单的方差分析模拟功能。然而,我想知道为什么我的 replicate() 命令不生成数字表?

    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?
    

           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 
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   akrun    7 年前

    输出是一个 list str

    str(replicate(5, fun()))
    

    replicate 也可以选择返回 列表 matrix

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

    注意,输出将具有 anova data.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