我想从整体中选择满足某些条件的元素子集。大约有20个元素,每个元素都有多个属性。我想从一个属性的固定标准中选择五个元素提供最少差异的元素,并为另一个属性提供最高的平均值。根据标准选择和标识元素的子集
最后,我想将这个函数应用于多组20个元素。
到目前为止,我已经能够“手工”识别子集,但我希望能够返回值的索引以及返回值本身。
目标:
我想找到X1属于至少从一个固定值(55)有差异的该组的五个值的,并提供平均X2的最大值。
我想这样做多套。
##### generating example data
##### this has five groups, each with two variables x1 and x2
set.seed(271828)
grp <- gl(5,20)
x1 <- round(rnorm(100,45, 12), digits=0)
x2 <- round(rbeta(100,2,4), digits = 2)
id <- seq(1,100,1)
##### this is how the data would arrive for me to analyze
dat <- as.data.frame(cbind(id,grp,x1,x2))
的数据将到达在这种格式中,与id
作为各元素的唯一标识符。
##### pulling out the first group for demonstration
dat.grp.1 <- dat[ which(grp == 1), ]
crit <- 55
x <- t(combn(dat.grp.1$x1, 5))
y <- t(combn(dat.grp.1$x2, 5))
mean.x <- rowMeans(x)
mean.y <- rowMeans(y)
k <- (mean.x - crit)^2
out <- cbind(x, mean.x, k, y, mean.y)
##### finding the sets with the least amount of discrepancy
pick <- out[ which(k == min(k)), ]
pick
##### finding the sets with low discrepancy and high values of y (means of X2) by "hand"
sorted <- out[order(k), ]
head(sorted, n=20)
随着pick
对于值,我可以看到,X1的值是:
> pick
mean.x k mean.y
[1,] 55 47 48 48 52 50 25 0.62 0.08 0.31 0.18 0.54 0.346
[2,] 55 48 48 47 52 50 25 0.62 0.31 0.18 0.48 0.54 0.426
我想这些元素返回id
值,所以我知道我挑选元素:3,8,10,11和18(选择集合2,因为与k
的差异相同,但是y
的平均值很高ER)。
> dat.grp.1
id grp x1 x2
1 1 1 45 0.12
2 2 1 27 0.34
3 3 1 55 0.62
4 4 1 39 0.32
5 5 1 41 0.18
6 6 1 29 0.47
7 7 1 47 0.08
8 8 1 48 0.31
9 9 1 35 0.48
10 10 1 48 0.18
11 11 1 47 0.48
12 12 1 31 0.29
13 13 1 39 0.15
14 14 1 36 0.54
15 15 1 36 0.20
16 16 1 38 0.40
17 17 1 30 0.31
18 18 1 52 0.54
19 19 1 44 0.37
20 20 1 31 0.20
这样做“手工操作”现在可行,但最好将其作为“解除手脚”。
任何帮助,非常感谢。
您需要定义一个将两个标准组合成一个数字的函数。然后你可以开始考虑如何找到最佳的。 – Thierry 2012-03-20 16:37:20