按组查找第一个日期时间

时间:2013-04-02 14:11:17

标签: r plyr

您好我正在寻找与plyr(或任何其他包,但bug #2531的data.table原因)的“按日期分组的最短时间”的等效内容

set.seed(1)
datetimes=c(rep(as.POSIXct("2011-01-01 08:00:00"),3) , rep(as.POSIXct("2011-01-03 08:00:00"),3)) + rnorm(6)
groups=c(rep('a',3),rep('b',3))
X = data.frame(datetime=datetimes,group=groups)
X
#                  datetime group
#2011-01-01 07:59:59.373546     a
#2011-01-01 08:00:00.183643     a
#2011-01-01 07:59:59.164371     a
#2011-01-03 08:00:01.595280     b
#2011-01-03 08:00:00.329507     b
#2011-01-03 07:59:59.179531     b

预期答案

                    datetime group
2011-01-01 07:59:59.164371     a
2011-01-03 07:59:59.179531     b

2 个答案:

答案 0 :(得分:3)

试试这个:

aggregate(datetime ~ group, X, min)

答案 1 :(得分:1)

使用ddply

ddply(X, .(group), summarise, first_datetime = min(datetime))

这种变体更简洁,但不太清楚:

ddply(X, .(group), colwise(min))