gpt4 book ai didi

r - 用r中的最大值和最小值组织数据

转载 作者:行者123 更新时间:2023-12-05 01:35:45 24 4
gpt4 key购买 nike

我有一个这样的表:

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

最佳答案

使用包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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com