我想按组计算tab $ date [i + 1]和tab $ date [i]之间的时差(以小时为单位)。这是我的代码:
.transcript {
position: relative;
width: 400px;
height: 150px;
background: #ffcc00;
overflow-y: scroll;
&:before {
content: '';
position: fixed;
width: 400px; height: 20px;
margin-top: 0; margin-left: 0;
background: -webkit-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
background: -moz-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
background: -o-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
background: linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
}
&:after {
content: '';
position: fixed;
top: 140px; left: 0;
width: 400px; height: 20px;
background: -webkit-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
background: -moz-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
background: -o-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
background: linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
}
}
问题在于我获得了小时,分钟和秒:
setDT(tab)
system.time(tab <- tab[ , diffTime := c(0,diff(date, units="hours")), by="ID"])
tab$diffTime <- round(tab$diffTime)
日期是POSIXct数据。 我怎么才能获得几个小时?
答案 0 :(得分:4)
我们可以使用difftime
并将units
指定为'小时'。
library(data.table)
setDT(tab)[, DiffTime := c(0, round(difftime(date[-1L], date[-.N],
units='hours'))), by= ID]
tab
# ID date DiffTime
#1: 1 2012-03-05 01:00:36 0
#2: 1 2012-03-05 03:00:35 2
#3: 1 2012-03-05 05:01:05 2
#4: 2 2010-01-29 21:01:00 0
#5: 2 2010-01-29 22:01:01 1
#6: 2 2010-01-29 23:01:12 1
tab <- data.frame(ID= rep(1:2, each=3),
date= as.POSIXct(c('2012-03-05 01:00:36', '2012-03-05 03:00:35',
'2012-03-05 05:01:05', '2010-01-29 21:01:00', '2010-01-29 22:01:01',
'2010-01-29 23:01:12'), format='%Y-%m-%d %H:%M:%S'))