我想在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 xn矩阵 - 所以我需要unsplit
的结果。另外 - 它似乎很慢。我怎样才能改进这个逻辑? 我见过解决方案指向data.table
包的方向。我应该使用该软件包重新写入吗?
更新
伟大的答案家伙 - 谢谢!但是 - 我的原始数据框包含更多的列(Feature2 ...),我需要它们在过滤之后全部返回。没有最低的价格(关键/特征1的组合)中的行可以丢弃,所以我不感兴趣,他们的特征2 /特点3
使用什么逻辑值的其他列将被采取?例如,如果'Feature2'对于同一个key-feature1具有不同的值,哪个值必须包含在输出中? – nicola
属于最低价格的价值。所以这件事需要作为一个行过滤器。所以AAA-1,AAA-2,BBB-1的“无论”。其余的行可以被丢弃。 –