-1

I am trying to create a matrix with two combinations of the same vector that sum up to 2300. I am using thecombnfunction in R, see the code below:

  vector <- 400:1900
  combinations <- combn(vector, 2, function(x) subset(x, sum(x)==2300))

Unfortunately, this code is not working. I get the following error:

Error in combn(r2, 2, function(x) subset(x, sum(x) == 2300)) : 
  dims [product 1125750] do not match the length of object [0]

Do anyone know what i did wrong? Many thanks,

Gion

Gion Mors
  • 313
  • 1
  • 3
  • 20
  • 1
    Take a look at [this post](http://stackoverflow.com/questions/38081651/how-to-find-all-the-possible-k-integers-which-sum-of-them-equals-to-a-certain-nu/38082278). I think it may be helpful. – lmo Jul 12 '16 at 16:29

1 Answers1

1

Try this:

combinations <- combn(vector,2,function(x) ifelse(sum(x[1], x[2])==2300, 
list(c(x[1],x[2])), list(c(0,0))))

res <- combinations[lapply(combinations, sum)>0]

head(res)

# [[1]]
# [1]  400 1900

# [[2]]
# [1]  401 1899

# [[3]]
# [1]  402 1898

# [[4]]
# [1]  403 1897

# [[5]]
# [1]  404 1896

# [[6]]
# [1]  405 1895

If you want to get a matrix of that:

matrix(unlist(res), ncol = 2, byrow = TRUE)
989
  • 12,579
  • 5
  • 31
  • 53