r - Conditional selection of variables -
suppose i've following table:
var iter_1 iter_2 iter_3 iter_4 var1 6 8 5 7 var2 5 1 7 8 var3 3 8 8 4 var4 8 7 2 5 var5 8 7 9 2 var6 8 7 3 6 var7 4 7 4 5
i want select combinations of columns each row such there combinations equal specific sum. e.g. in case, suppose want each var combination of iter 15. in case want select var1
, iter_2
& iter_4
. var2
, iter_3
& iter_4
.
i wanted develop code such code can tell me column values select each var.
can plz suggest method? 1 don't need write code, logic can use.
thank you.
this works if sum taken columns:
data = data.frame(x = 1:3, y = 2:4, z = 5:7) sums = apply(data, 1, sum) target.val = 11 which(sums == target.val)
otherwise looks exact cover problem. http://en.wikipedia.org/wiki/exact_cover
or
you use stochastic approach, genetic algorithm. simplistic solution:
find.colsums = function(data, target, n.tries = 100) { nrows = nrow(data) max.cols = ncol(data) n.columns = sample(max.cols, n.tries, replace = true) (i in 1:n.tries){ test.cols = sample(max.cols, n.columns[i]) (row in 1:nrows){ if (sum(data[row, test.cols]) == target){ cat("match @ row:", row, "cols:", test.cols, "\n") } } } }
example:
data = data.frame(x = 1:3, y = 2:4, z = 5:7) target = 7 find.colsums(data, target)
fun big dataset:
n = 1000 min.val = 1 max.val = 30 ncols = 10 target = ((min.val + max.val) * ncols/2) data = matrix(sample(min.val:max.val, n, replace = true), ncol = ncols) find.colsums(data, target, n.tries = 1000)
Comments
Post a Comment