在r中组织具有最大值和最小值的数据

时间:2017-10-12 20:04:58

标签: r datetime group-by sqldf

我有一张这样的表:

enter image description here

由以下代码生成:

id <- c("1","2","1","2","1","1")
status <- c("open","open","closed","closed","open","closed")
date <- c("11-10-2017 15:10","10-10-2017 12:10","12-10-2017 22:10","13-10-2017 06:30","13-10-2017 09:30","13-10-2017 10:30")
data <- data.frame(id,status,date)
hour <- data.frame(do.call('rbind', strsplit(as.character(data$date),' ',fixed=TRUE)))
hour <- hour[,2]
hour <- as.POSIXlt(hour, format = "%H:%M") 

我想要实现的是为每个id选择最早的开放时间最新的关闭时间。所以最终结果将如下所示:

enter image description here

目前我使用sqldf来解决问题:

sqldf("select * from (select id, status, date as closeDate, max(hour) as hour from data 
  where status='closed'
   group by id,status) as a
   join 
   (select id, status, date  as openDate, min(hour) as hour from data 
   where status='open'
   group by id,status) as b
  using(id);")

问题1:有更简单的方法吗?

问题2:如果我选择max(hour)作为任何其他名称而不是hour,结果将不会采用日期和时间的格式,而是一系列数字例如15078642001507807800。如何在为列分配不同的名称时保留时间格式?

1 个答案:

答案 0 :(得分:0)

使用包plyr

(出于某种原因,如here所示,您必须将小时转换为类as.POSIXct,否则会收到错误消息):

#add hour to data.frame:
data$hour <- as.POSIXct(hour)
library(plyr)
ddply(data, .(id), summarize, open=min(hour[status=="open"]),
     closed=max(hour[status=="closed"]))