R: from a vector, list all subsets of elements so their sum just passes a value

不问归期 提交于 2019-12-02 10:00:38

This may be an option:

library(utils)
v <- seq (1,5)
v.len <- length(v)
threshold <- 3
for (count in seq(1,v.len))
{
  print(paste("subset length",count))
  combinations <- combn(v,count)
  out <- combinations[,apply(combinations, 2, sum)>=threshold]
  print (out)
}

above produces following output:

[1] "subset length 1"
[1] 3 4 5
[1] "subset length 2"
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    2    2    2    3    3     4
[2,]    2    3    4    5    3    4    5    4    5     5
[1] "subset length 3"
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    1    1    2    2    2     3
[2,]    2    2    2    3    3    4    3    3    4     4
[3,]    3    4    5    4    5    5    4    5    5     5
[1] "subset length 4"
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    2
[2,]    2    2    2    3    3
[3,]    3    3    4    4    4
[4,]    4    5    5    5    5
[1] "subset length 5"
[1] 1 2 3 4 5

so you'd need to do something with the output / decide where to store it etc.

icco

I found a solution within my limited coding skills that might be inefficient but it is feasible and neater than writing endless loops.

The function was inspired by the java code found at Find all subsets of a set that sum up to n

recursive.subset <-function(x, index, current, threshold, result){
  for (i in index:length(x)){
    if (current + x[i] >= threshold){
      cat (result, x[i], "\n",sep="\t") 
    } else {
      recursive.subset(x, i + 1, current+x[i], threshold, c(result,x[i]))
    }
  }
}

To call the function, just

inivector <- vector(mode="numeric", length=0) #initializing empty vector
recursive.subset (v, 1, 0, threshold, inivector)

So I get

1 2
1 3
2 3
3

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