在base
:
dt1$timediff <- cumsum(c(0, difftime(tail(dt1$timestamp,-1), head(dt1$timestamp,-1))))
或使用data.table
:
library(data.table)
dt1[ , timediff := cumsum(c(0, diff(as.numeric(timestamp))))][]
#> timestamp event timediff
#> 1: 2019-09-26 07:29:22.778 X 0.00
#> 2: 2019-09-26 07:29:23.917 Y 1.14
#> 3: 2019-09-26 07:29:25.118 Z 2.34
另一个dplyr
基于akrun答案的解决方案:
library(dplyr)
dt1 %>%
mutate(difftime = difftime(timestamp, timestamp[1], unit = 'sec'))
数据:
注意:我data.table
用来读取数据。
fread(text="date time event
2019-09-26 07:29:22.778 X
2019-09-26 07:29:23.918 Y
2019-09-26 07:29:25.118 Z") -> dt1
dt1$timestamp <- as.POSIXct(paste(dt1$date, dt1$time), format="%Y-%m-%d %H:%M:%OS")
dt1 <- dt1[,4:3]