简体   繁体   English

dataframe 中加权平均值的引导跨行

[英]Bootstrap of weighted mean in dataframe across rows

I have a question regarding bootstrapping of a weighted mean.我有一个关于加权平均值自举的问题。

Depending on how my data is structured, I sometimes want to bootstrap across columns and sometimes across rows.根据我的数据结构,有时我想跨列引导,有时跨行引导。

In another post ( bootstrap weighted mean in R ), the following code was provided to bootstrap the weighted mean across columns:在另一篇文章( R 中的引导加权平均值)中,提供了以下代码来引导跨列的加权平均值:

library(boot)

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])

This works perfectly (check: weighted.mean(mtcars[,7], mtcars[,6]).这非常有效(检查:weighted.mean(mtcars[,7], mtcars[,6])。

However, I now also want to bootstrap across rows, which I thought the following code would do:但是,我现在还想跨行引导,我认为下面的代码会这样做:

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

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

Unfortunately this is not working, and I don't know what I should change?不幸的是,这不起作用,我不知道我应该改变什么?

Many thanks in advance.提前谢谢了。

You could define your bootstrap-function like this:你可以像这样定义你的引导函数:

samplewmean2 <- function(d, i, j) {
  elements2use <- sample(1:length(d), length(d), replace=T)
  k <- d[, elements2use]
  v <- j[, elements2use]
  return(weighted.mean(k, v))   
}

And then apply the bootstrap like this:然后像这样应用引导程序:

results_qsec2 <- boot(data= t(mtcars[,  7, drop = FALSE]), 
                      statistic = samplewmean2, 
                      R=10, 
                      j = t(mtcars[,6  , drop = FALSE]),
                      stype="i")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM