0

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

Community
  • 1
  • 1
ph33
  • 3
  • 2

2 Answers2

0

Try this:

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){
      store <<- append(store, sum(c(result,x[i])))
    } else {
      recursive.subset(x, i + 1, current+x[i], threshold, c(result,x[i]))
    }
  }
}

store <- list()
inivector <- vector(mode="numeric", length=0) #initializing empty vector    
recursive.subset (v, 1, 0, threshold, inivector)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Wow!!! this code does exactly what I want!! Thanks a lot!! I tried to vote but I don´t have enough points yet! Thanks – ph33 Jan 31 '16 at 03:54
0

The problem in your solution is the position of "return" statement. The solution could be:

recursive.subset2 <-function(x, index, current, threshold, result){
  m <- NULL
  for (i in index:length(x)){
    if (current + x[i] >= threshold){
      m <- c(m, sum(c(result,x[i]))) 
    } else {
      m <- c(m, recursive.subset2(x, i + 1, current+x[i], threshold, c(result,x[i])))
    }
  }
  return(m)
 }
Pandya21
  • 61
  • 6
  • It works fine for me: `ans <- recursive.subset2(v, 1, 0, 3, 0) > ans [1] 3 4 5 3 > ans <- recursive.subset2(v, 1, 2, 2, 5) > ans [1] 6 7 8` – Pandya21 Jan 31 '16 at 15:14