我想在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的「無論」。其餘的行可以被丟棄。 –