【发布时间】:2013-12-19 13:59:37
【问题描述】:
我有带有日期时间戳的位置数据。这些位置应该定期收集,但并不总是这样。我需要提取时间窗口内的那些位置。因此,例如,相隔 12 小时的位置。如果我从位置 1 的日期时间开始,则找到 12 小时后的下一个位置。如果没有一个正好是 12 小时,那么下一个最接近新的指定时间。然后从那个新位置开始,并在 12 小时内找到下一个位置。我必须为每个唯一 ID 执行此操作。
COLLAR_ID dt
2159 2006-01-27 13:02:55
2159 2006-01-27 14:01:12
2159 2006-01-27 15:01:04
2159 2006-01-27 16:01:09
是数据的样子,这是您可以剪切和粘贴的一小部分数据。请注意,这都是同一个 ID,我有 5 个不同的 ID,开始日期/时间不同
structure(list(COLLAR_ID = c(2159L, 2159L, 2159L, 2159L, 2159L,
2159L, 2159L, 2159L, 2159L, 2159L, 2159L, 2159L, 2159L, 2159L,
2159L, 2159L, 2159L, 2159L, 2159L, 2159L), dt = structure(c(1138366975,
1138370472, 1138374064, 1138377669, 1138381264, 1138384873, 1138388503,
1138399312, 1138402842, 1138406507, 1138413700, 1138417261, 1138420848,
1138424444, 1138428071, 1138431695, 1138435287, 1138438938, 1138442428,
1138446098), class = c("POSIXct", "POSIXt"), tzone = "GMT")), .Names = c("COLLAR_ID",
"dt"), class = "data.frame", row.names = c(NA, 20L))
所以我认为从示例数据来看,如果我的开始日期是 2006 年 1 月 27 日 00:00:00 时间,那么它应该记录的下一个位置是 12:00:00 - 但是这个位置没有存在所以它应该记录 13:02:55。但即使这是“外部”严格的 1 小时缓冲窗口 2 分钟。
我曾想过将日期时间转换为儒略十进制数以使其更易于使用,但我不知道该怎么做。将日期/时间四舍五入到几小时就可以了,除非有时在 1 小时的时间间隔内有 2 或 3 个位置,所以我需要在那些“最接近时间”的位置中选择原始开始.
因此,添加新的细节可能会使事情变得更加混乱 - 一些数据最初是每隔 1 小时收集一次,然后在 3 周后改为 12 小时。但是,我不知道每个人应该切换的编程时间。其他人从 12 小时开始,从 00:00:00 开始,但切换到 1 小时间隔,然后在几天后切换到 12 小时 - 但又一次不知道它在一天中的哪个时间进行了切换。所以,它本可以从下午 2 点开始切换到 12 小时。
我试图查看this stack overflow conversation,但看不到它是如何工作的。所以,这是我下面的尝试,我现在已经从最初的问题发布中更新了。这没用。我还在研究它......它的代码看起来仍然相当笨重。
test2 = test2[order(test2$COLLAR_ID,test2$dt),]
test2$dt <- as.POSIXct(strptime((test2$dt), "%Y-%m-%d %H:%M:%S"), tz="GMT")
MinInterval = 12 #minimum time interval (in hours) between consecutive locations
row = 0 # Keeps track of row within alldata
Endtest2 = 2 #keeps track of row within individual within all data
SubData1 = test2[1,]
IDNames = levels(as.factor(test2$COLLAR_ID))
test22 = data.frame()
for (n in 1:length(IDNames)){
IndivData = test2[test2$COLLAR_ID==IDNames[n],]
row = row+1 #Continues to track next row between individuals
Endtest2 = 2 #restarts counting the rows for NEXT individual
SubData1[row,]=IndivData[1,]
while (Endtest2<nrow(IndivData) ){
timediff = difftime(IndivData$dt[Endtest2],SubData1$dt[row],units = "hours")
if (timediff>MinInterval){ #If time difference is greater than 47 hours then do
row = row+1
SubData1=rbind(SubData1,IndivData[Endtest2,])
Endtest2 = Endtest2+1
} else{
Endtest2 = Endtest2+1
}
} #end while loop
} #end loop through individuals
test22 =SubData1
} #end conditional to subset data
我很抱歉并且很尴尬地说,我早就完全忘记了我 posted a question(使用类似的代码),但从来没有得到任何解决方案。我已经放弃了整个努力,但现在正在用新的数据(更混乱的数据)和新的需求重新审视它。该脚本没有过滤掉正确的数据。
【问题讨论】:
-
答案对您有用吗?它似乎做到了。如果是,请将其标记为已回答。