在 r 中减去时间,将结果单位强制为分钟

Subtract time in r, forcing unit of results to minutes

我成功减去 df1 的两个 POSIXct 列(下图)。但是,由于所有行的时间差 >= 1 小时,因此 R 以小时为单位给出结果。我知道这是有道理的,但是有没有直接的方法让它变成 return 分钟?

df1 <- data.frame(time.stamp1 = c("2015-01-05 15:00:00", "2015-01-05 16:00:00", "2015-01-05 18:00:00", "2015-01-05 19:00:00", "2015-01-05 20:00:00"),
                  time.stamp2 = c("2015-01-05 16:00:00", "2015-01-05 17:00:00", "2015-01-05 20:00:00", "2015-01-05 20:00:00", "2015-01-05 22:00:00"))

df1$time.stamp1 <- as.POSIXct(strptime(df1$time.stamp1, "%Y-%m-%d %H:%M:%S"))                 
df1$time.stamp2 <- as.POSIXct(strptime(df1$time.stamp2, "%Y-%m-%d %H:%M:%S"))                 

df1$time.diff <- df1$time.stamp2 - df1$time.stamp1

当前结果

> df1
          time.stamp1         time.stamp2 time.diff
1 2015-01-05 15:00:00 2015-01-05 16:00:00   1 hours
2 2015-01-05 16:00:00 2015-01-05 17:00:00   1 hours
3 2015-01-05 18:00:00 2015-01-05 20:00:00   2 hours
4 2015-01-05 19:00:00 2015-01-05 20:00:00   1 hours
5 2015-01-05 20:00:00 2015-01-05 22:00:00   2 hours

期望的结果

> df1
          time.stamp1         time.stamp2  time.diff
1 2015-01-05 15:00:00 2015-01-05 16:00:00    60 mins
2 2015-01-05 16:00:00 2015-01-05 17:00:00    60 mins
3 2015-01-05 18:00:00 2015-01-05 20:00:00   120 mins
4 2015-01-05 19:00:00 2015-01-05 20:00:00    60 mins
5 2015-01-05 20:00:00 2015-01-05 22:00:00   120 mins

非常感谢

你可以试试difftime

 df1$time.diff <- with(df1, difftime(time.stamp2, time.stamp1, unit='min'))
 df1
 #         time.stamp1         time.stamp2 time.diff
 #1 2015-01-05 15:00:00 2015-01-05 16:00:00   60 mins
 #2 2015-01-05 16:00:00 2015-01-05 17:00:00   60 mins
 #3 2015-01-05 18:00:00 2015-01-05 20:00:00  120 mins
 #4 2015-01-05 19:00:00 2015-01-05 20:00:00   60 mins
 #5 2015-01-05 20:00:00 2015-01-05 22:00:00  120 mins