Following with this question R: from a vector, list all subsets of elements so their sum just passes a value
I´m trying to find a way to store the values given by the print command in a vector or matrix but I can´t find any way to do it. The code is:
v<-c(1,2,3)
threshold <- 3 # My threshold value
recursive.subset <-function(x, index, current, threshold, result){
for (i in index:length(x)){
if (current + x[i] >= threshold){
print(sum(c(result,x[i])))
} else {
recursive.subset(x, i + 1, current+x[i], threshold, c(result,x[i]))
}
}
}
Many thanks in advance.
I tried this code but I just get the last sum
recursive.subset <-function(x, index, current, threshold, result){
for (i in index:length(x)){
if (current + x[i] >= threshold){
return(sum(c(result,x[i])))
} else {
m<-recursive.subset(x, i + 1, current+x[i], threshold, c(result,x[i]))
c(m,m)
}
}
}
thanks
The problem in your solution is the position of "return" statement. The solution could be:
Try this: