简体   繁体   中英

R solver optimization

I am new to R solver and I want to have a simple example in R for the below problem:

I have four columns which I calculate the individual sums as the illustrated sample example below:

在此处输入图片说明

The problem I want to solve in R:

Find the optimal lines that satisfies, simultaneously , the below statements:

  1. For the first two columns (a, b) the individual summations to be more close to 0
  2. The sums of (c, d) to be more close to 5

I do not have restrictions of which package solver to use. It could be helpful to have an example of R code for this!

EDIT

For the same solution I would like to apply some rules:

  1. I want the sum(c) > sum(d) AND sum(d) < (static number, like 5)
  2. Also, if I want the sums to fall into a range of numbers and not just static numbers, how the solution could it be written?

Using M defined reproducibly in the Note at the end we find the b which minimizes the following objective where b is a 0/1 vector:

sum((b %*% M - c(0, 0, 5, 5))^2)

1) CVXR Using the CVXR package we get a solution c(1, 0, 0, 1, 1) which means choose rows 1, 4 and 5.

library(CVXR)

n <- nrow(M)
b <- Variable(n, boolean = TRUE)

pred <- t(b) %*% M
y <- c(0, 0, 5, 5)

objective <- Minimize(sum((t(y) - pred)^2))
problem <- Problem(objective)
soln <- solve(problem)

bval <- soln$getValue(b)
zapsmall(c(bval))
## [1] 1 0 0 1 1

2) Brute Force Alternately since there are only 5 rows there are only 2^5 possible solutions so we can try them all and pick the one which minimizes the objective. First we compute a matrix solns with 2^5 columns such that each column is one possible solution. Then we compute the objective function for each column and take the one which minimizes it.

n <- nrow(M)

inverse.which <- function(ix, n) replace(integer(n), ix, 1)
L <- lapply(0:n, function(i) apply(combn(n, i), 2, inverse.which, n))
solns <- do.call(cbind, L)
pred <- t(t(solns) %*% M)
obj <- colSums((pred - c(0, 0, 5, 5))^2)
solns[, which.min(obj)]
## [1] 1 0 0 1 1

Note

M <- matrix(c(.38, -.25, .78, .83, -.65,
.24, -.35, .44, -.88, .15,
3, 5, 13, -15, 18,
18, -7, 23, -19, 7), 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM