![](/img/trans.png)
[英]R find max value in a column for which there are no values in corresponding columns
[英]Find the highest combination of values in column 1 based on max value in column 2 - R
我有一個3列的數據框(實際上是2000行)。 我想返回A列的值,該列在B列中的最高總得分最高,但限制了C列中的最大值。例如:
colName col1 col2
John 7 50
Jim 3 25
James 2 25
Peter 9 110
Robert 1 75
Hank 1 75
假設col2的最大總和值為100。col1中組合值的最高組合為7 + 3 + 2 = 12。 我想返回將要返回的姓名列表:John,Jim,James
Q1:我該怎么做?
問題2:或者,返回數據幀的整個行以及數據幀中最大可能組合的值會很有趣:
colName col1 col2
John 7 50
Jim 3 25
James 2 25
您指的是一個0/1背包問題 。 adagio
軟件包在R中實現了背包求解器。
> tbl
# A tibble: 6 x 3
colName col1 col2
<chr> <int> <int>
1 John 7 50
2 Jim 3 25
3 James 2 25
4 Peter 9 110
5 Robert 1 75
6 Hank 1 75
> tbl <- tbl[tbl$col2 <= 100, ] # `adagio` will complain otherwise
> soln <- knapsack(tbl$col2, tbl$col1, 100)
> tbl[soln$indices, ]
# A tibble: 3 x 3
colName col1 col2
<chr> <int> <int>
1 John 7 50
2 Jim 3 25
3 James 2 25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.