I have multi group of data like:
X <- c(2,3,5,10,15)
Y <- c(4,6,23,15,12)
Z <- c(23,34,12,1,5)
and a target: target = 50
I want to know the best (for example): 2 values from X (call it X2), 4 values from Y (Y4) and 3 values from Z (Z3) that if I sum them I get sum(X2) + sum(Y4) + sum(Z3) = 50
(or the closest to 50).
Is there a solution to this problem?
The best way to use combinations is to use the function I've found on stackoverflow (can't find the post)
getVariant <- function(id, vars) {
if (!is.list(vars)) stop('vars needs to be a list!')
nv <- length(vars)
lims <- sapply(vars, length)
if (any(id > prod(lims))) stop('id above the number of combinations!')
res <- vector("list", nv)
for(i in nv:2) {
f <- prod(lims[1:(i-1)])
res[[i]] <- vars[[i]][(id - 1)%/%f + 1]
id <- (id - 1)%%f + 1
}
res[[1]] <- vars[[1]][id]
names(res) <- names(vars)
return(as.data.frame(res))
}
It returns the combination number "id"... Is there a way to use it to get all the combinations and thus get the sum I want?
Edit: The data I've provided is just an example… My end goal is to reproduce it on a large data.