'Error with number of variables in objective and constraints

I'm trying to set up a linear optimization using the ROI package in R, following instructions in this link: https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#introduction. However i'm getting an error when trying to implement a 'Group constraint' (https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#group_constraints). Here is my sample code

df <- data.frame(Group=rep(c('A', 'B', 'C', 'D'), each=4),
                 SubGroup=c('A.1', 'A.2', 'A.3', 'A.1', 'B.1', 'B.1', 'B.2', 'B.2', 'C.1', 'C.2', 'C.2', 'C.2', 'D.1', 'D.2', 'D.3', 'D.4'),
                 score=round(runif(16, 0, 1),2),
                 wgt=rep(1/16,16),
                 id=1:16)

data <- matrix(round(runif(256, -5, 5),3), ncol=16, byrow=TRUE)
Cov1 <- as.matrix(cov(data))

Taken from the linked article:

group_constraint <- function(r_mat, index, coef.index = 1, dir = "==", rhs) {
  ## index = (i, j)
  ## coef.index = c(a,b)
  ## rhs = c
  #x.names <- colnames(r_mat)
  N <- NCOL(r_mat)
  L <- rep(0, N)
  L[index] <- coef.index
  L_constraint(L = L, dir = dir, rhs = rhs)
}

group_1 <- group_constraint(df$score, index = c(3, 12, 13), dir = "<=", rhs = 0.5)

My optimization problem

full_invest <- L_constraint(rep(1, 16), "==", 1)

LP <- OP(objective = df$score,
          group_1,
          bounds = V_bound(ui = seq_len(16), ub = rep(0.40, 16)),
          max = TRUE)
sol1 <- ROI_solve(LP, "glpk")
sol1
x <- solution(sol1)
x

When i run this i get the following error: "Error in .check_constraints.L_constraint(constr, x) : dimension missmatch! OP has 16 variables the constraints have 13". If i change group_1 to group_1 <- group_constraint(df$score, index = c(3, 12, 16), dir = "<=", rhs = 0.6) This now works, as ncol(group_1) is 16.

Based on example 1 in the link (https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#example_1:_maximize_expected_return_subject_to_budget_normalization_and_group_constraints) I cant see where i'm going wrong with my example.

Any help would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source