How to store values in a vector with nested functi

2019-09-05 18:38发布

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

2条回答
做自己的国王
2楼-- · 2019-09-05 18:52

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)
 }
查看更多
狗以群分
3楼-- · 2019-09-05 18:59

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)
查看更多
登录 后发表回答