Calculating cumulative time in R

纵饮孤独 提交于 2019-12-06 09:59:34

To get the total time in each group's periods, you first need to create a group index. I'm using rleid from data.table You can then, calculate the total time spent in each of these groups, and then summarise by the initial POI using sum.

df <- read.table(text="     POI   LOCAL.DATETIME
1     '2017-07-11 15:02:13'
1     '2017-07-11 15:20:28'
2     '2017-07-11 15:20:31'
2     '2017-07-11 15:21:13'
3     '2017-07-11 15:21:18'
3     '2017-07-11 15:21:21'
2     '2017-07-11 15:21:25'
2     '2017-07-11 15:21:59'
1     '2017-07-11 15:22:02'
1     '2017-07-11 15:22:05'",
                 header=TRUE,stringsAsFactors=FALSE)
df$LOCAL.DATETIME <- as.POSIXct(df$LOCAL.DATETIME)

library(dplyr)
df%>%
  mutate(grp=data.table::rleid(POI))%>%
  group_by(grp)%>%
  summarise(POI=max(POI),TOTAL.TIME=difftime(max(LOCAL.DATETIME),
                                     min(LOCAL.DATETIME),units="secs"))%>%
  group_by(POI)%>%
  summarise(TOTAL.TIME=sum(TOTAL.TIME))

# A tibble: 3 × 2
    POI TOTAL.TIME
  <int>     <time>
1     1  1098 secs
2     2    76 secs
3     3     3 secs

To get minute and seconds, you can use as.period from lubridate:

library(lubridate)
df%>%
  mutate(grp=data.table::rleid(POI))%>%
  group_by(grp)%>%
  summarise(POI=max(POI),TOTAL.TIME=difftime(max(LOCAL.DATETIME),
                                    min(LOCAL.DATETIME),units="secs"))%>%
  group_by(POI)%>%
  summarise(TOTAL.TIME=sum(TOTAL.TIME))%>%
  mutate(TOTAL.TIME =as.period((TOTAL.TIME), unit = "sec"))

    POI   TOTAL.TIME
  <int> <S4: Period>
1     1      18M 18S
2     2       1M 16S
3     3           3S

Another data.table option is to create groupings of 2 rows for each POI, take the time difference between them, and finally sum it up by POI:

library(data.table)

dt <- as.data.table(df)
dt[, grp2 := (seq_len(.N)+1) %/% 2, by = POI]
dt[, time_diff := difftime(LOCAL.DATETIME, shift(LOCAL.DATETIME), unit = "min"), by = .(POI, grp2)]
dt[ , .(TOTAL.TIME = sum(time_diff, na.rm = T)), by = POI]

#   POI     TOTAL.TIME
#1:   1 18.300000 mins
#2:   2  1.266667 mins
#3:   3  0.050000 mins
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!