【问题标题】:How to bootstrap weighted mean in a loop in r如何在r中的循环中引导加权平均值
【发布时间】:2022-01-14 23:19:34
【问题描述】:

我想在 for 循环中运行加权平均值的引导程序(我认为我不能使用“应用”,因为它涉及加权平均值)。我只需要将生成的标准错误存储在数据框中。另一篇文章提供了如何在 bootstrap (bootstrap weighted mean in R) 中计算加权平均值的代码,并且运行良好:

library(boot)
 
mtcarsdata = mtcars #dataframe for data 
mtcarsweights = rev(mtcars) #dataframe for weights

samplewmean <- function(d, i, j) {
  d <- d[i, ]
  w <- j[i, ]
  return(weighted.mean(d, w))   
}

results_qsec <- sd(boot(data= mtcarsdata[, 6, drop = FALSE], 
                     statistic = samplewmean, 
                     R=10000, 
                     j = mtcarsweights[, 6 , drop = FALSE])[[2]], na.rm=T)
results_qsec

然后循环运行它,我尝试了:

outputboot = matrix(NA, nrow=11, ncol=1)
for (k in 1:11){
  outputboot[1,k] = sd(boot(data= mtcarsdata[, k, drop = FALSE], 
                       statistic = samplewmean, 
                       R=10000, 
                       j = mtcarsweights[, k, drop = FALSE])[[2]], na.rm=T)
}
outputboot

但这不起作用。第一个输出甚至不正确。我怀疑代码不能使用两个迭代器:一个用于循环列,另一个用于带替换的采样。

我希望任何人都可以提供一些帮助。

【问题讨论】:

  • 所以你基本上不仅要引导一列,还要引导所有 mtcars 列并获得它们的加权平均值?
  • 只要你能计算出什么。在每一列的一个步骤中,您可以使用applymap 和朋友。这应该是加权平均的情况

标签: r for-loop statistics-bootstrap weighted-average


【解决方案1】:

这将计算由mtcarsweights 加权的表mtcarsdata 每一列的所有引导程序的标准差。

由于我们可以一步计算结果,我们可以使用apply和朋友(这里:purrr:map_dbl

library(boot)
library(purrr)

set.seed(1337)

mtcarsdata <- mtcars # dataframe for data
mtcarsweights <- rev(mtcars) # dataframe for weights

samplewmean <- function(d, i, j) {
  d <- d[i, ]
  w <- j[i, ]
  return(weighted.mean(d, w))
}

mtcarsdata %>%
  ncol() %>%
  seq() %>%
  map_dbl(~ {
    # .x is the number of the current column
    sd(boot(
      data = mtcarsdata[, .x, drop = FALSE],
      statistic = samplewmean,
      R = 10000,
      j = mtcarsweights[, .x, drop = FALSE]
    )[[2]], na.rm = T)
  })
#>  [1]  0.90394218  0.31495232 23.93790468  6.34068205  0.09460257  0.19103196
#>  [7]  0.33131814  0.07487754  0.07745781  0.13477355  0.27240347

reprex package (v2.0.1) 于 2021 年 12 月 10 日创建

【讨论】:

    猜你喜欢
    • 2018-02-24
    • 2021-08-31
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2012-06-14
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多