首页 > 解决方案 > 按多个参数对 R 中的数据进行排序

问题描述

我有以下问题:我有一个包含 3 个不同列的数据集(还有更多,但对于分析它们不相关)。这是一个示例数据集(原始数据集有更多观察结果):

Date               Company             Return
March              A                   0.03
March              A                   0.02
March              B                   0.01
April              B                   0.02       
April              A                   0.01
May                C                   0.02
June               B                   0.03

现在我想找到每个月的最大回报,但是每个公司应该在最终输出中显示 3 次最大值。我尝试了一些 for 循环来为每个月创建子集,但是我不知道如何才能在每个月获得最大回报的同时仍然有每个公司出现少于 3 次的限制。重要的是,当一家公司在产出中被退回 3 次时,必须在特定月份选择具有次高回报的公司。每个月必须退回一次。

标签: r

解决方案


如果你想最大化整体回报,那么你需要转向优化方法,公式如下:

  • 最大化目标函数:收益总和
  • 每月限制:每个月必须在解决方案中出现一次
  • 公司限制:每家公司在解决方案中最多出现3次

这可以通过库来完成lpSolveAPI

library(lpSolveAPI)

# Create data.table
dt <- data.frame(Date = c("March", "March", "March", "April", "April", "May", "June"),
                 Company = c("A", "A", "B", "B", "A", "C", "B"),
                 Return = c(0.03, 0.02, 0.01, 0.02, 0.01, 0.02, 0.03))

# Objective
obj <- -dt$Return

# Constraints
constraints <- list()

# Each month must appear once in the solution
for (month in unique(dt$Date)){
  constraints[[paste0('month', month)]] <- list(xt = as.numeric(dt$Date == month),
                                                type = "=",
                                                rhs = 1)
}

# Each company can appear maximum 3 times in the solution
for (com in unique(dt$Company)){
  constraints[[paste0('company', com)]] <- list(xt = as.numeric(dt$Company == com),
                                                type = "<=",
                                                rhs = 3)
}

# Build model
lprec <- make.lp(0, ncol = nrow(dt))
set.type(lprec, columns = seq(1,nrow(dt)), type = "binary")

set.objfn(lprec, obj = obj)

for (constraint in constraints){
  add.constraint(lprec, xt = constraint$xt, type = constraint$type, rhs = constraint$rhs)
}

# Compute Solution
solve(lprec)

# Visualize solution
solution <- dt[get.variables(lprec)==1,]

solution

#    Date Company Return
# 1 March       A   0.03
# 4 April       B   0.02
# 6   May       C   0.02
# 7  June       B   0.03

推荐阅读