Nonlinear discrete optimization in R

前端 未结 4 1633
执念已碎
执念已碎 2021-01-20 19:17

I have a simple (indeed standard in economics) nonlinear constrained discrete maximisation problem to solve in R and am having trouble. I found solutions for pa

4条回答
  •  迷失自我
    2021-01-20 19:35

    If you do not mind using a "by hand" solution:

    uf=function(x)prod(x)^.5
    bf=function(x,pr){
      if(!is.null(dim(x)))apply(x,1,bf,pr) else x%*%pr
    }
    budget=20
    df <- data.frame(product=c("ananas","banana","cookie"),
                     price=c(2.17,0.75,1.34),stringsAsFactors = F)
    an=0:(budget/df$price[1]) #include 0 for all possibilities
    bn=0:(budget/df$price[2])
    co=0:(budget/df$price[3])
    X=expand.grid(an,bn,co)
    colnames(X)=df$product
    EX=apply(X,1,bf,pr=df$price)
    psX=X[which(EX<=budget),] #1st restrict
    psX=psX[apply(psX,1,function(z)sum(z==0))==0,] #2nd restrict
    Ux=apply(psX,1,uf)
    cbind(psX,Ux)
    (sol=psX[which.max(Ux),])
    uf(sol) # utility
    bf(sol,df$price)  #budget
    
    > (sol=psX[which.max(Ux),])
         ananas banana cookie
    1444      3      9      5
    > uf(sol) # utility
    [1] 11.61895
    > bf(sol,df$price)  #budget
     1444 
    19.96
    

提交回复
热议问题