[R] Solving an optimization problem: selecting an "optimal" subset

Bart Joosen bartjoosen at hotmail.com
Sat Jan 30 17:48:21 CET 2010


Here some kind of a brute force attack:

#brute force solution, only working with relative small subsets:
n <- 200
elem <- 3
target <- 200

x <- rnorm(n,100,10)
x.combinations <- combn(x,elem)
sums <- apply(x.combinations,2,function(x) (sum(x)-target)^2)
ans <- (x.combinations[,which.min(sums)])

#seems to work for larger subsets:
require(gtools)
x.combinations <- combinations(n, elem)
sums <- apply(x.combinations,1,function(sel) (sum(x[sel])-target)^2)
print(x[x.combinations[which.min(sums),]])


Although it takes a lot of computation time, you are sure you will find the
minimum.

Bart
-- 
View this message in context: http://n4.nabble.com/Solving-an-optimization-problem-selecting-an-optimal-subset-tp1446084p1457514.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list