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

时间:2015-06-22 12:36:40

标签: r posix posixct

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

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

非常感谢

1 个答案:

答案 0 :(得分:3)

您可以尝试使用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