# NOT RUN {
data(hazell.vegetables)
dat <- hazell.vegetables
# }
# NOT RUN {
require(linprog)
# colMeans(dat[ , -1])
# 252.8333 442.6667 283.8333 515.8333
# Maximize c'x for Ax=b
A <- rbind(c(1,1,1,1), c(25,36,27,87), c(-1,1,-1,1))
cvec <- c(253, 443, 284, 516) # avg profit per acre
colnames(A) <- names(cvec) <- cc(carrot,celery,cucumber,pepper)
rownames(A) <- c('land','labor','rotation')
bvec <- c(200,10000,0)
const.dir <- c("<=","<=","<=")
m1 <- solveLP(cvec, bvec, A, maximum=TRUE, const.dir=const.dir, lpSolve=TRUE)
# m1$solution # optimal number of acres for each crop
# carrot celery cucumber pepper
# 0.00000 27.45098 100.00000 72.54902
# Average income for this plan
## sum(cvec * m1$solution)
## [1] 77996.08
# Year-to-year income for this plan
## as.matrix(dat[,-1]) <!-- %*% m1$solution -->
## [,1]
## [1,] 80492.16
## [2,] 80431.37
## [3,] 81884.31
## [4,] 106868.63
## [5,] 37558.82
## [6,] 80513.73
# Brute-force search for optimum allocation that minimizes year-to-year
# income variability.
# For generality, assume we have unequal probabilities for each year.
probs <- c(.15, .20, .20, .15, .15, .15)
# Randomly allocate crops to 200 acres, 100,000 times
mat <- matrix(runif(4*100000), ncol=4)
mat <- 200*sweep(mat, 1, rowSums(mat), "/")
profit <- mat <!-- %*% t(dat[,-1]) # Each row is profit for each of the six years -->
ix <- apply(profit, 1, function(x) cov.wt(as.data.frame(x), wt=probs)$cov)
ix <- which.max(ix)
mat[ix,] # Optimal planting allocation that minimizes the weighted variance
## carrot celery cucumber pepper
## 71.67002 27.90306 84.69966 15.72726
# }
# NOT RUN {
# }
Run the code above in your browser using DataLab