我想在 R 中实现以下目标:给定一个表(在我的例子中是数据框)- 我想为 两个 列的每个唯一组合获得最低价格。
例如,给定下表:
+-----+-----------+-------+----------+----------+
| Key | Feature1 | Price | Feature2 | Feature3 |
+-----+-----------+-------+----------+----------+
| AAA | 1 | 100 | whatever | whatever |
| AAA | 1 | 150 | whatever | whatever |
| AAA | 1 | 200 | whatever | whatever |
| AAA | 2 | 110 | whatever | whatever |
| AAA | 2 | 120 | whatever | whatever |
| BBB | 1 | 100 | whatever | whatever |
+-----+-----------+-------+----------+----------+
我想要一个看起来像这样的结果:
+-----+-----------+-------+----------+----------+
| Key | Feature1 | Price | Feature2 | Feature3 |
+-----+-----------+-------+----------+----------+
| AAA | 1 | 100 | whatever | whatever |
| AAA | 2 | 110 | whatever | whatever |
| BBB | 1 | 100 | whatever | whatever |
+-----+-----------+-------+----------+----------+
所以我正在按照以下方式制定解决方案:
s <- lapply(split(data, list(data$Key, data$Feature1)), function(chunk) {
chunk[which.min(chunk$Price),]})
但结果是一个 1 x n 矩阵 - 所以我需要unsplit
结果。另外 - 它似乎很慢。我怎样才能改进这个逻辑?
我已经看到指向 data.table
包方向的解决方案。我应该使用那个包重写吗?
更新
很好的答案伙计们 - 谢谢!但是 - 我的原始数据框包含更多列( Feature2 ... ),过滤后我需要将它们全部返回。没有最低价格的行(对于 Key/Feature1 的组合)可以被丢弃,所以我对它们对 Feature2/Feature3 的值不感兴趣
最佳答案
您可以使用dplyr
包:
library(dplyr)
data %>% group_by(Key, Feature1) %>%
slice(which.min(Price))
关于r - 按两列的唯一组合获取最小分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31344487/