Sorry in advance if the answer (1) is trivial; or (2) out there but I haven't been able to solve this issue or find and answer online. Any pointers will be much appreciated!
I am in need of a piece of code that can run through a vector and return all possible subsets of elements whose cumulative sum passes a threshold value.
Note that I do not want only the subsets that give me exactly the threshold. The cumulative sum can be above the threshold, as long as the algorithm stops adding an extra element if the value has been achieved already.
# A tiny example of the kind of input data.
# However, note that efficiency is an issue
# (I need to replicate the example in a large dataset)
v <- seq(1, 3) # My vector
threshold <- 3 # My threshold value
# I would like to get a list with the combinations
# 1 2
# 1 3
# 2 3
# 3
This piece of code works but is the clunkiest solution on earth...
for (i in 1: length(v)){
thisvalue <- v[i]
if (thisvalue >=threshold) {
cat (v[i], "\n",sep="\t")
} else {
for (j in (i+1): length(v)){
thisvalue <- v[i]+v[j]
if (thisvalue >=threshold) {
cat (c(v[i], v[j]), "\n",sep="\t")
} else {
for (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")
}
}
}
}
}
}