In case the combination are ok:
target <- 20
lapply(seq_len(sum(cumsum(sort(x$quantity)) <= target)), function(n) {
y <- combn(x$quantity, n)
y[,colSums(y) == target]
})
#[[1]]
#integer(0)
#
#[[2]]
# [,1] [,2]
#[1,] 1 4
#[2,] 19 16
#
#[[3]]
# [,1] [,2]
#[1,] 1 4
#[2,] 3 3
#[3,] 16 13
#
#[[4]]
#[1] 1 4 12 3
...and to get the row:
lapply(seq_len(sum(cumsum(sort(x$quantity)) <= target)), function(n) {
y <- combn(x$quantity, n)
y <- y[,colSums(y) == target, drop = FALSE]
if(length(y) > 0) {apply(y, 2, match, x$quantity)}
})
#[[1]]
#NULL
#
#[[2]]
# [,1] [,2]
#[1,] 2 3
#[2,] 5 9
#
#[[3]]
# [,1] [,2]
#[1,] 2 3
#[2,] 7 7
#[3,] 9 8
#
#[[4]]
# [,1]
#[1,] 2
#[2,] 3
#[3,] 4
#[4,] 7
... and somehow like the expected output:
lapply(seq_len(sum(cumsum(sort(x$quantity)) <= target)), function(n) {
y <- combn(x$quantity, n)
y <- y[,colSums(y) == target, drop = FALSE]
if(length(y) > 0) {apply(y, 2, function(i) {x[match(i, x$quantity),]})}
})
#[[1]]
#NULL
#
#[[2]]
#[[2]][[1]]
# id quantity
#2 2 1
#5 5 19
#
#[[2]][[2]]
# id quantity
#3 3 4
#9 9 16
#
#
#[[3]]
#[[3]][[1]]
# id quantity
#2 2 1
#7 7 3
#9 9 16
#
#[[3]][[2]]
# id quantity
#3 3 4
#7 7 3
#8 8 13
#
#
#[[4]]
#[[4]][[1]]
# id quantity
#2 2 1
#3 3 4
#4 4 12
#7 7 3
Data:
x <- structure(list(id = 1:10, quantity = c(11L, 1L, 4L, 12L, 19L, 10L, 3L, 13L, 16L
, 14L)), class ="data.frame", row.names = c(NA,-10L))