[R] Aggregate by minimum

Hadley Wickham
Tue, 10 Jan 2012 22:55:10 -0000

On Mon, Jan 9, 2012 at 8:00 PM, jim holtman <jholtman at gmail.com>
wrote:
> try this:
>
>> x <- structure(list(speed = c(3,9,14,8,7,6), result = c(0.697,
0.011, 0.015, 0.012, 0.018, 0.019), house = c(1,
> + 1, 1, 1, 1, 1), date = c(719, 1027, 1027, 1027, 1030, 1030),
> + ? ?id = c("1000", "10000",
> + ? ?"10001", "10002", "10003",
"10004")), .Names = c("speed",
> + "result", "house", "date", "id"),
class = "data.frame", row.names = c("1000",
> + "10000", "10001", "10002",
"10003", "10004"))
>>
>> require(plyr)
>> ddply(x, .(date), .fun = function(a){
> + ? ? a[which.min(a$speed), ]
> + })

Or even more succinctly:

ddply(x, .(date), subset, speed == min(speed))

Hadley


--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University