我有一张这样的桌子:

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

通过以下代码生成:

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选择最早的打开时间和最新的关闭时间。因此,最终结果将如下所示:

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

目前,我使用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。在为列分配不同的名称时如何保持时间格式?

最佳答案

使用包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"]))

关于r - 在r中组织具有最大值和最小值的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46717998/

10-12 17:35