How to store values in a vector with nested functions

♀尐吖头ヾ 提交于 2020-01-06 21:07:15

问题


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


回答1:


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)



回答2:


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)
 }


来源:https://stackoverflow.com/questions/35107568/how-to-store-values-in-a-vector-with-nested-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!