采取具有特定均值的样本

时间:2018-11-18 22:45:05

标签: r sample

假设我有一个{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附近。

一个好的例子是:

  • {3,5,6,8,9},均值= 6.2
  • {2,3,4,8,9},均值= 5.6

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

概率向量的图: plot

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

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