组织有最大值和最小值的数据r中
问题描述:
我有这样的一个表:组织有最大值和最小值的数据r中
这是由下面的代码生成:
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。所以,最终的结果会是这样的:
目前我使用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
,结果将不会在日期和时间的格式,但像1507864200
,1507807800
一系列数字。如何在为列指定不同名称的同时保持时间格式?
答
使用包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"]))
你的意思了'小时“成为您的数据中的一列?也许你忘了'数据$小时 Gregor