【问题标题】:Call sapply on vector of densities?在密度向量上调用 sapply?
【发布时间】:2021-11-26 05:42:03
【问题描述】:

我正在使用 dweibull 和 dunif 等函数生成一组密度。我希望能够使用 sapply 提取他们的时刻。当我在单个分布上调用均值函数时,我得到了预期的平均值。但是当我使用 sapply 执行此操作时,它似乎对密度中的每个单独值调用 mean()(即,对于我提供给 dweibull 或 dunif 的每个 x 值。有没有办法在这里获得正确的行为?谢谢!

weib <- dweibull(seq(from=0, to=25, length=100), shape=1, scale=5)
unif <- dunif(seq(from=1, to=10, length=100), min=1, max=10)
mean(weib) #Works!
dists <- c(weib, unif)
means <- sapply(dists, mean) #Returns a very long list of values, not the mean of weib and unif

【问题讨论】:

    标签: r statistics


    【解决方案1】:

    您应该将数据存储在列表中。 c(weib, unif) 创建单个组合向量并使用 sapply(dists, mean) 返回单个数字的平均值,即数字本身。

    dists <- list(weib, unif)
    means <- sapply(dists, mean) 
    

    【讨论】:

    • 这成功了!任何解释为什么在这种情况下会有所不同?谢谢!
    • 我在答案中添加了一些解释。
    【解决方案2】:

    你也可以使用数据框

    dists <- data.frame(weib, unif)
    sapply(dists, mean)
          weib       unif 
    0.04034828 0.11111111 
    lapply(dists,mean)
    $weib
    [1] 0.04034828
    
    $unif
    [1] 0.1111111
    apply(dists, 2,mean)
          weib       unif 
    0.04034828 0.11111111 
    

    【讨论】:

      【解决方案3】:

      我们可能会使用map

      dists <- list(weib, unif)
      library(purrr)
      means <- map_dbl(dists, mean)
      

      【讨论】:

        猜你喜欢
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多