取一个具有特定均值的样本

take a sample that has a specific mean

假设我有一个像 {1,2,3, ..., 23} 这样的总体,我想生成一个样本,使样本的均值等于 6。

我尝试使用 sample 函数,使用自定义概率向量,但没有成功:

population <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23)
mean(population)
minimum <- min(population)
maximum <- max(population)
amplitude <- maximum - minimum 
expected <- 6
n <- length(population)
prob.vector = rep(expected, each=n)
for(i in seq(1, n)) {
  if(expected > population[i]) {
    prob.vector[i] <- (i - minimum) / (expected - minimum)
  } else {
    prob.vector[i] <- (maximum - i) / (maximum - expected)
  }
}
sample.size <- 5
sample <- sample(population, sample.size, prob = prob.vector)
mean(sample)

样本的均值大约是总体的均值(在 12 左右摆动),我希望它在 6 左右。

一个好的样本是:

问题与sample integer values in R with specific mean不同,因为我有一个特定的人口,我不能随便生成任意实数,它们必须在人口内。

概率向量图:

你可以试试这个:

m = local({b=combn(1:23,5);
           d = colMeans(b);
           e = b[,d>5.5 &d<6.5];
           function()sample(e[,sample(ncol(e),1)])})
m()
[1] 8 5 6 9 3
m()
[1]  6  4  5  3 13

细分:

b=combn(1:23,5) # combine the numbers into 5
d = colMeans(b) # find all the means
e = b[,d>5.5 &d<6.5] # select only the means that are within a 0.5 range of 6
sample(e[,sample(ncol(e),1)]) # sample the values the you need