Search code examples
rcombn

Create all vector combinations summing up to a specific number in R


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


Solution

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