constraints - R: from a vector, list all subsets of elements so their sum just passes a value -
sorry in advance if answer (1) trivial; or (2) out there haven't been able solve issue or find , answer online. pointers appreciated!
i in need of piece of code can run through vector , return possible subsets of elements cumulative sum passes threshold value.
note not want subsets give me threshold. cumulative sum can above threshold, long algorithm stops adding element if value has been achieved already.
# tiny example of kind of input data. # however, note efficiency issue # (i need replicate example in large dataset) v <- seq(1, 3) # vector threshold <- 3 # threshold value # list combinations # 1 2 # 1 3 # 2 3 # 3 this piece of code works clunkiest solution on earth...
for (i in 1: length(v)){ thisvalue <- v[i] if (thisvalue >=threshold) { cat (v[i], "\n",sep="\t") } else { (j in (i+1): length(v)){ thisvalue <- v[i]+v[j] if (thisvalue >=threshold) { cat (c(v[i], v[j]), "\n",sep="\t") } else { (k in (i+2): length(v)){ thisvalue <- v[i]+v[j]+v[k] if (thisvalue >=threshold) { cat(c(v[i],v[j],v[k]),"\n",sep="\t") } } } } } }
this may option:
library(utils) v <- seq (1,5) v.len <- length(v) threshold <- 3 (count in seq(1,v.len)) { print(paste("subset length",count)) combinations <- combn(v,count) out <- combinations[,apply(combinations, 2, sum)>=threshold] print (out) } above produces following output:
[1] "subset length 1" [1] 3 4 5 [1] "subset length 2" [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 2 2 2 3 3 4 [2,] 2 3 4 5 3 4 5 4 5 5 [1] "subset length 3" [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 1 1 2 2 2 3 [2,] 2 2 2 3 3 4 3 3 4 4 [3,] 3 4 5 4 5 5 4 5 5 5 [1] "subset length 4" [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 2 [2,] 2 2 2 3 3 [3,] 3 3 4 4 4 [4,] 4 5 5 5 5 [1] "subset length 5" [1] 1 2 3 4 5 so you'd need output / decide store etc.
Comments
Post a Comment