我想從整體中選擇滿足某些條件的元素子集。大約有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