按组获取期间的最小值和最大值

时间:2018-03-18 12:53:41

标签: r dplyr lubridate

我每组有几次参加者喝水(1 =年轻人,2 =成年人)。不幸的是,我找不到一个很好的方法来获得最小(时间)和最大(时间)之间的差异。对于年轻人来说,这是21小时,成人则是6小时。这显然不起作用:

age <-c(1,1,2,1,2) 
time <-hm("22:00","01:00","12:00","16:00","18:00")
drink <- data.frame(age, time)
diff <- drink %>% group_by(age) %>% summarise(max()-min()) 

1 个答案:

答案 0 :(得分:1)

使用time_length中的lubridate函数可以实现一个解决方案。

library(lubridate)

#data
sex <-c(1,1,2,1,2) 
time <-hm(c("22:00","01:00","12:00","16:00","18:00"))
food <- data.frame(sex, time)


food %>% mutate(tl_sec = time_length(time)) %>% 
  group_by(sex) %>% summarise(diff_secs = max(tl_sec) - min(tl_sec)) %>%
  as.data.frame()

#    sex diff_secs
# 1   1     75600
# 2   2     21600


#Diff in HRS
food %>% mutate(tl_sec = time_length(time)) %>% 
  group_by(sex) %>% summarise(diff_hrs = (max(tl_sec) - min(tl_sec))/3600) %>%
  as.data.frame()

#     sex diff_hrs
# 1   1       21
# 2   2        6