[英]Time difference between two values
data.frame(gid = c(1,1,1,2), gtime = c("2015-10-22 13:23:02", "2015-10-22 13:23:02", "2015-10-22 13:23:02", "2016-11-23 13:23:02"), wid = c (3,4,5,2) wtime = c("2015-10-22 13:33:02", "2015-10-22 13:53:02", "2015-10-22 14:23:02", "2016-11-23 13:28:02"), type = c("google", "google", "amazon", "yahoo")
如何區分時間戳 pf gtime 和 wtime 之間的差異? 預期 output 的示例:
data.frame(difference = c("10 minutes", "30 minutes", "60 minutes", "24 hours and 5 minutes"), gid = c(1,1,1,2), gtime = c("2015-10-22 13:23:02", "2015-10-22 13:23:02", "2015-10-22 13:23:02", "2016-11-23 13:23:02"), wid = c (3,4,5,2) wtime = c("2015-10-22 13:33:02", "2015-10-22 13:53:02", "2015-10-22 14:23:02", "2016-11-24 13:28:02"), type = c("google", "google", "amazon", "yahoo")
我們可以轉換為日期時間difftime
並使用unit
指定為min
的 difftime
df1$difference <- with(df1, difftime(as.POSIXct(wtime),
as.POSIXct(gtime), unit = 'min'))
如果我們需要刪除屬性,請用as.numeric
包裝
轉換成as.POSIXct
后可以直接減去時間
with(df, as.POSIXct(wtime) - as.POSIXct(gtime))
#Time differences in mins
#[1] 10 30 60 5
也可以使用 lubridate 的ymd_hms
代替as.POSIXct
。
library(lubridate)
with(df, ymd_hms(wtime) - ymd_hms(gtime))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.