'How to apply function to split data frame and combine the results for use as constraint
I have the below code that will work to create 'group' constraints on A.1, A.2 and B.2. What i want to do is to create constraints for each of the subgroups i have in my data.
library(ROI)
library("ROI.plugin.glpk")
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)
score <- as.matrix(t(df$score))
subA1 <- filter(df, SubGroup %in% 'A.1')
A.1 <- t(as.matrix(subA1$id))
subB1 <- filter(df, SubGroup %in% 'B.1')
B.1 <- t(as.matrix(subB1$id))
subA2 <- filter(df, SubGroup %in% 'A.2')
A.2 <- t(as.matrix(subA2$id))
A.1
group_constraintxxx <- function(r_mat, index, coef.index = 1, dir, rhs) {
N <- NCOL(r_mat)
L <- rep(0, N)
L[index] <- coef.index
L_constraint(L = L, dir = dir, rhs = rhs)
}
group_A.1 <- group_constraintxxx(score, index = A.1, dir = ">=", rhs = 0.15)
group_B.1 <- group_constraintxxx(score, index = c(B.1), dir = ">=", rhs = 0.25)
group_A.2 <- group_constraintxxx(score, index = c(A.2), dir = ">=", rhs = 0.25)
consts_AB <- rbind(group_A.1, group_B.1, group_A.2)
typeof(consts_AB)
consts_AB
full_invest <- L_constraint(rep(1, 16), "==", 1)
LP <- OP(objective = score,
rbind(full_invest, consts_AB),
maximum = TRUE)
sol1 <- ROI_solve(LP, solver = "glpk")
sol1
x <- solution(sol1)
x
This works and you can see that consts_AB is 'An object containing 3 linear constraints. However i am trying to get all subgroups (using split) then apply the group_constraintxxx formula to each one.
This is what i have so far for this:
by_group <- split(df, df$SubGroup)
as.matrix(t(by_group$C.2[,5]))
grp_constraint <- function(x) {
group_constraintxxx(score, index = c(as.matrix(t(x$id))), dir = "<=", rhs = 0.15)
}
consts <- lapply(by_group,grp_constraint)
consts
You can see that consts is 11 objects containing 1 linear constraint each, rather than 'an object containing 11 linear constraints', and i think this is causing the error i get when i try to include consts in the LP optimization as here:
LP <- OP(objective = score,
rbind(full_invest, consts),
maximum = TRUE)
sol1 <- ROI_solve(LP, solver = "glpk")
sol1
x <- solution(sol1)
x
This is the error i get with the above "Error: TYPE_MISMATCH in rbind.constraint object ... doesn't inherit from constraint! Call: rbind(deparse.level, ...)"
Anyone with any experience of something similar, or any suggested solutions 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 |
|---|
