【发布时间】:2016-12-20 15:55:59
【问题描述】:
我有一些跟踪数据,我想计算每个点之间的时间差,我可以这样做:
# prep the data
ID = c(rep("A",5), rep("B",5))
DateTime = c("2014-09-25 08:39:45", "2014-09-25 08:39:48", "2014-09-25 08:40:44", "2014-09-25 09:04:00","2014-09-25 09:04:10", "2014-09-25 08:33:32", "2014-09-25 08:34:41", "2014-09-25 08:35:24", "2014-09-25 09:04:00", "2014-09-25 09:04:09")
speed = c(1:10)
df = data.frame(ID,DateTime,speed, stringsAsFactors = FALSE)
df$DateTime<-as.POSIXct(df$DateTime, tz = "UTC")
# function to calculate time differences
timeCheck<-function(df) {
sapply(1:(nrow(df) - 1), function(i){
timeDiff<- difftime(df$DateTime[i+1], df$DateTime[i], units = "sec" )
return(timeDiff)
})
}
# preserve order of factor levels
df$ID <- factor(df$ID, levels=unique(df$ID))
# apply the function by ID
timeDiffData<-sapply(split(df, df$ID), timeCheck)
我希望能够将时间差的新列添加到原始数据帧,但当然这个列表的长度不同,因为该函数不会计算与自身的时间差。
然后,如果差异大于某个值(例如 100 秒),我想在新函数中使用这些时间差异来拆分轨道,并让 ID 反映这一点。
所以最后我的 ID 列有 4 个级别,并且当时间差大于 100 秒时会发生拆分。
生成的数据框应如下所示:
# what it should look like
ID = c(rep("A",3),rep("A1",2) , rep("B",3), rep("B1",2))
DateTime = c("2014-09-25 08:39:45", "2014-09-25 08:39:48", "2014-09-25 08:40:44", "2014-09-25 09:04:00","2014-09-25 09:04:10", "2014-09-25 08:33:32", "2014-09-25 08:34:41", "2014-09-25 08:35:24", "2014-09-25 09:04:00", "2014-09-25 09:04:09")
speed = c(1:10)
timeDiff<-c(NA,3,56,1396,10,NA,69,43,1716,9)
newdf = data.frame(ID,DateTime,speed,timeDiff, stringsAsFactors = FALSE)
newdf$DateTime<-as.POSIXct(df$DateTime, tz = "UTC")
newdf
【问题讨论】:
标签: r function datetime time lapply