## example comparing the mean and median as an estimator
## of the P50 quantile in two symmetric distributions 

## Generate dataset  (true value is 0 in both datasets)
set.seed(231171)
n=900
x1 = rnorm(n,0,1)

x2 = rnorm(n,0,1)/sqrt(rnorm(n,0,1)^2+rnorm(n,0,1)^2)/2

hist(x1,30, xlim=c(-17 ,17))
hist(x2,30, xlim=c(-17 ,17))
show(c(mean(x1),median(x1),sd(x1)) )
show(c(mean(x2),median(x2),sd(x2)))


## size of bootstrapsample
B=10000

########################  Case 1: Normal data 

m1avg=rep(0,B)
m1med=rep(0,B)

for(b in 1:B)
{
  ind=sample(1:n,n,replace=TRUE)
  m1avg[b]=mean(x1[ind])
  m1med[b]=median(x1[ind])
}

hist(m1avg,breaks=seq(-1,1,by=0.011),xlim=c(-0.25, 0.25))
hist(m1med,breaks=seq(-1,1,by=0.011),xlim=c(-0.25, 0.25))
show(c(mean(m1avg),sd(m1avg)) )
show(c(mean(m1med),sd(m1med)))

########################  Case 2: Non-normal data  

m2avg=rep(0,B)
m2med=rep(0,B)

for(b in 1:B)
{
  ind=sample(1:n,n,replace=TRUE)
  m2avg[b]=mean(x2[ind])
  m2med[b]=median(x2[ind])
}


hist(m2avg,breaks=seq(-1,1,by=0.01),xlim=c(-0.25, 0.25))
hist(m2med,breaks=seq(-1,1,by=0.01),xlim=c(-0.25, 0.25))

show(c(mean(m2avg),sd(m2avg)) )
show(c(mean(m2med),sd(m2med)))

