在 R 中使用约束条件解决线性规划问题。

时间:2021-08-12 04:16:08

标签: r optimization linear-programming lpsolve

我想使用 R 和 lpSolve 解决一个优化问题,类似于 Excel 中的求解器插件。下面是一个简单的案例,其中我想要最大化 npv 值,具体地使用 lpSolve。

df <- structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8), Revenue = c(109, 111, 122, 139, 156, 140, 137, 167)), row.names = c(NA, 8L), class = "data.frame")

dcf <- function(x, r, t0=FALSE){
  # calculates discounted cash flows (DCF) given cash flow and discount rate
  #
  # x - cash flows vector
  # r - vector or discount rates, in decimals. Single values will be recycled
  # t0 - cash flow starts in year 0, default is FALSE, i.e. discount rate in first period is zero.
  if(length(r)==1){
    r <- rep(r, length(x))
    if(t0==TRUE){r[1]<-0}
  }
  x/cumprod(1+r)
}

npv <- function(x, r, t0=FALSE){
  # calculates net present value (NPV) given cash flow and discount rate
  #
  # x - cash flows vector
  # r - discount rate, in decimals
  # t0 - cash flow starts in year 0, default is FALSE
  sum(dcf(x, r, t0))
}
npv(df$Revenue,.2)
#Non optimized npv yields a value of 492.
#How can i use lpSolve to optimize my table? Said another way how can I rearrange the table to maximize npv using lpSolve?

更复杂的问题涉及到一列惩罚,其规则如下: Id 表示项目。

  1. 如果 Id 不是第一个期(行 1)。检查以前的 Id 是否在 2 个单位之内(绝对值为将其他先前行的 Id 从当前行的 Id 中减去)。如果是,则通过 20%惩罚 Revenue。我认为这个问题仍然涉及解决正确的顺序。如何优化此函数?
#Randomize order to give base npv. Now i need to optimize the order to find max value
df<- df%>%mutate(random_sort= sample(nrow(df)))

x=function(i){
  df_fcn<- i
  df_fcn<- df_fcn%>%mutate(Penalty= if_else(abs(random_sort-lag(random_sort))>2,1,.8))%>%mutate(Penalty=ifelse(is.na(Penalty),1,Penalty))
  df_fcn<- df_fcn%>%mutate(Revenue_Penalized= Revenue*Penalty)

  npv(df_fcn$Revenue_Penalized,.2)
  }

0 个答案:

没有答案