Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df <- cbind(expand.grid(shop=1:3,supply=1:2),distance=c(2.8,5.4,1.4,4.2,3.0,6.3))
- df["Entry"] <- 1:dim(df)[[1]]
- shop.mat <- table(df$shop,df$Entry)
- shop.mat
- 1 2 3 4 5 6
- 1 1 0 0 1 0 0
- 2 0 1 0 0 1 0
- 3 0 0 1 0 0 1
- supply.mat <- table(df$supply,df$Entry)
- supply.mat
- 1 2 3 4 5 6
- 1 1 1 1 0 0 0
- 2 0 0 0 1 1 1
- N_supply <- dim(supply.mat)[[1]]
- N_shop <- dim(shop.mat)[[1]]
- N_entry <- dim(df)[[1]]
- constr.mat <- NULL
- dir <- NULL
- rhs <- NULL
- constr.mat <- rbind(constr.mat,cbind(shop.mat,matrix(0,N_shop,N_supply)))
- dir <- c(dir,rep("==",N_shop))
- rhs <- c(rhs,rep(1,N_shop))
- obj <- c(aggregate(distance~Entry,df,c)[["distance"]],rep(0,N_supply))
- constr.mat <- rbind(constr.mat,cbind(supply.mat,-diag(table(df$supply))))
- dir <- c(dir,rep("<=",N_supply))
- rhs <- c(rhs,rep(0,N_supply))
- constr.mat <- rbind(constr.mat,c(rep(0,N_entry),rep(1,N_supply)))
- dir <- c(dir,"<=")
- rhs <- c(rhs,2)
- require(lpSolve)
- sol <- lp("min", obj, constr.mat, dir, rhs, all.bin = TRUE,num.bin.solns = 1, use.rw=FALSE, transpose.constr=TRUE)
- sol$solution
- [1] 1 0 1 0 1 0 1 1
- sol$objval
- [1] 7.2
- selected_Entry <- dimnames(shop.mat)[[2]][as.logical(sol$solution[1:N_entry])]
- selected_Entry
- [1] "1" "3" "5"
- df[df$Entry %in% selected_Entry,]
- shop supply distance Entry
- 1 1 1 2.8 1
- 3 3 1 1.4 3
- 5 2 2 3.0 5
- constr.mat %*% sol$solution
- [,1]
- 1 1
- 2 1
- 3 1
- 1 -1
- 2 -2
- 2
- constr.mat %*% c(1,1,1,0,0,0,1,1)
- [,1]
- 1 1
- 2 1
- 3 1
- 1 0
- 2 -3
- 2
- constr.mat <- rbind(constr.mat,cbind(supply.mat,-diag(table(df$supply))),cbind(supply.mat,-diag(table(df$supply))))
- dir <- c(dir,rep("<=",N_supply),rep(">=",N_supply))
- rhs <- c(rhs,rep(0,N_supply),1-table(df$supply))
- paste(t(unlist(constr.mat %*% sol$solution)),dir,rhs)
- [1] "1 == 1" "1 == 1" "1 == 1" "-1 <= 0"
- [5] "-2 <= 0" "2 <= 2" "-1 <= 0" "-2 <= 0"
- [9] "-1 >= -2" "-2 >= -2"
- paste(t(unlist(constr.mat %*% c(1,1,1,0,0,0,1,1))),dir,rhs)
- [1] "1 == 1" "1 == 1" "1 == 1" "0 <= 0"
- [5] "-3 <= 0" "2 <= 2" "0 <= 0" "-3 <= 0"
- [9] "0 >= -2" "-3 >= -2"
Add Comment
Please, Sign In to add comment