R中的bootstrap加权平均值

时间:2017-09-15 03:31:14

标签: r statistics-bootstrap

我知道如何引导矢量的平均值:

library(boot)
samplemean <- function(x, d) {
  return(mean(x[d]))
}
results_qsec <- boot(data=mtcars$qsec, statistic = samplemean, R=1000)

但我如何引导加权平均值,考虑到例如值mtcars$qsec,这些值的权重是mtcars$wt

2 个答案:

答案 0 :(得分:2)

诀窍是指定weighted.mean的权重作为...的{​​{1}}参数的一部分。在这里,我使用boot作为权重,并将其作为数据框传递,以匹配j参数。

你走了:

data =

返回:

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

results_qsec <- boot(data= mtcars[, 7, drop = FALSE], 
                     statistic = samplewmean, 
                     R=10000, 
                     j = mtcars[, 6 , drop = FALSE])

与:比较:

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = mtcars[, 7, drop = FALSE], statistic = samplewmean, 
    R = 10000, j = mtcars[, 6, drop = FALSE])


Bootstrap Statistics :
    original       bias    std. error
t1* 17.75677 0.0006948823   0.3046888

答案 1 :(得分:1)

这是如何:

samplewmean <- function(data, d) {
  return(weighted.mean(x=data[d,1], w=data[d,2]))
}

results_qsec <- boot(data=mtcars[,c(7,6)], statistic = samplewmean, R=1000)