关注此问题R: from a vector, list all subsets of elements so their sum just passes a value
我试图找到一种方法来将print命令给出的值存储在矢量或矩阵中,但我找不到任何方法。 代码是:
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]))
}
}
}
非常感谢提前。
我尝试了这段代码,但我得到了最后一笔费用
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)
}
}
}
感谢
答案 0 :(得分:0)
试试这个:
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)
答案 1 :(得分:0)
您的解决方案中的问题是“返回”声明的位置。解决方案可能是:
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)
}