【发布时间】:2015-09-29 10:08:12
【问题描述】:
我要在 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 值不感兴趣
【问题讨论】:
-
用什么逻辑取其他列的值?例如,如果
Feature2对同一个 key-feature1 有不同的值,那么输出中必须包含哪个值? -
属于最低价的值。所以这个东西需要作为一个行过滤器。所以AAA-1,AAA-2,BBB-1的“随便”。其余行可以丢弃。
标签: r