问题
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