首页 > 解决方案 > Taking a set of values with a equal or similar mean in R

问题描述

I am working with R.

I have two sets of values. They look like this.

setA     setB 
 .88      .55
 .67      .45
 .25      .35
 .40      .18
 .50      .05
 .70      .90
 .40      .25
 .57      .27
 .69      .21
 .90      .30

I took five values of the setA...

setA
.88
.40
.90
.57
.70

The mean of this set of words is 0.69.

Is there a way to select values of the setB that will have the same or very similar mean to 0.69?

So, I need a "random" sample of setB that will end up with a mean equal or around 0.69.

(In reality I have 800 values in setA, so is very difficult to select the values of the setB by just looking at them).

标签: r

解决方案


一种危险的低效方法,特别是如果您有不仅有 2 位小数的大型集合,则可能只是在 while 循环中进行随机抽样。

exact_match <- function(setA, setB) {
  mean_setA_sample <- mean(sample(setA, 5))
  mean_setB_sample <- 0
  setB_sample <- c()
  iterations <- 0
  while (mean_setB_sample != mean_setA_sample) {
    setB_sample <- sample(setB, 5)
    mean_setB_sample <- mean(setB_sample)
    iterations <- iterations + 1
  }
  print(iterations)
  print(setB_sample)
  print(mean_setA_sample)
  print(mean_setB_sample)
}

close_match <- function(setA, setB, difference) {
  mean_setA_sample <- mean(sample(setA, 5))
  mean_setB_sample <- 0
  setB_sample <- c()
  iterations <- 0
  while (abs(mean_setB_sample-mean_setA_sample) > difference) {
    setB_sample <- sample(setB, 5)
    mean_setB_sample <- mean(setB_sample)
    iterations <- iterations + 1
  }
  print(iterations)
  print(setB_sample)
  print(mean_setA_sample)
  print(mean_setB_sample)
}

编辑 我已经更新了函数并包含了一个紧密匹配的解决方案。


推荐阅读