简体   繁体   中英

Bootstrap of weighted means in R

I have a data frame with 27 samples divided in 3 strata. I want to replicate 500 times a weighted mean, where the mean is calculate among the random selection of 3 samples for stratum and the weight is the relative area of the strata.

My idea was to create a loop of selection for each stratum and to compute the mean. I am able to compute the simple mean of the selection but I am not able to compute the weighted mean (I have no idea how to extract the weight and the value together):

#data
DF<-data.frame(v= c(16,42,63,15,42,63,85,16,43),
              s= c(1,3,2,2,1,3,3,1,2),
                  w=c(0.2,0.5,0.3,0.3,0.2,0.5,0.5,0.2,0.3),
                  stringsAsFactors=T)
#simple mean
x<-c()
for (i in 1:3){
  x.tm<-sample(subset(DF$v,DF$s==i),2,replace=T)
  x<-c(x,x.tm)
  d<-mean(x)}

furthermore, I'm confused about the replicate function and the way to insert the weighted mean inside it. For example, trying with the simple mean I have obtained an empty list:

t<-replicate(500,{
  for (i in 1:3){
  x.tm<-sample(subset(DF$v,DF$s==i),2, replace=T)
  x<-c(x,x.tm)
  d<-mean(x)
  }
  })

I have also tried using the boot::boot command but the result was the same.

This is a possible way.

A function selecting 3 samples for s =1,2,3 and provides the weighted.mean between v and w

fun<-function(DF) { 

  s<-c(1,2,3)
  DF_sub_1<-DF[as.numeric(as.character(DF$s))==s[1],]
  DF_sub_2<-DF[as.numeric(as.character(DF$s))==s[2],]
  DF_sub_3<-DF[as.numeric(as.character(DF$s))==s[3],]

  x.tm_1<-sample(nrow(DF_sub_1),2,replace=T)
  x.tm_2<-sample(nrow(DF_sub_2),2,replace=T)
  x.tm_3<-sample(nrow(DF_sub_3),2,replace=T)

  DF_sample<-rbind(DF_sub_1[x.tm_1,],DF_sub_2[x.tm_2,],DF_sub_3[x.tm_3,])

  out<-weighted.mean(DF_sample[,1],DF_sample[,3])

  return(out)  
}

500 time replication

output<-replicate(500,fun(DF))

500 samples with weighted mean of the 3 samples

output
  [1] 46.00 41.15 58.70 51.50 61.70 49.00 58.70 61.70 50.60 49.00 44.70 46.25 46.40 52.80 67.20 32.90 36.55
 [18] 47.95 42.05 45.35 40.75 57.10 40.75 44.70 51.85 48.90 40.10 43.75 54.40 53.20 47.95 51.50 51.90 47.30
 [35] 58.30 54.50...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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