我有一个数据集,不定期地以30分钟的频率采样,如下所示。我需要提取每天的上一个时间戳的索引。数据集如下:
datetime <-c("8/19/2011 16:00",
"8/19/2011 17:30",
"8/19/2011 18:30",
"8/19/2011 19:30",
"8/22/2011 4:00",
"8/22/2011 6:00",
"8/22/2011 7:00",
"8/22/2011 19:00",
"8/22/2011 19:30",
"8/23/2011 4:00",
"8/24/2011 5:30",
"8/24/2011 7:00",
"10/25/2011 7:30")
我已将其转换为POSIXlt对象,如下所示。
datetime <- strptime(datetime, format="%m/%d/%Y %H:%M")
datetime <- as.POSIXlt(datetime)
但是,我无法提取每天的最后一个索引。我想要一个输出作为每天上一次时间戳的索引,即我的输出将是
list of (4, 9, 10,12,13) corresponding to datetime values of
"8/19/2011 19:30"
"8/22/2011 19:30"
"8/23/2011 4:00"
"8/24/2011 7:00"
"10/25/2011 7:30"
任何帮助将不胜感激。谢谢!
尝试:
datetime <- c("8/19/2011 16:00", "8/19/2011 17:30", "8/19/2011 18:30", "8/19/2011 19:30", "8/22/2011 4:00", "8/22/2011 6:00", "8/22/2011 7:00", "8/22/2011 19:00", "8/22/2011 19:30", "8/23/2011 4:00", "8/24/2011 5:30", "8/24/2011 7:00", "8/23/2011 7:30", "12/23/2012 19:23", "11/24/2015 7:13")
splitter <- strftime(strptime(datetime,"%m/%d/%Y %H:%M"), "%m/%d/%Y")
lapply(split(datetime, splitter), function(x) {
match(x[length(x)], datetime)
})
如果您还想返回索引处的值,则可以像下面这样调整代码:
lapply(split(datetime, splitter), function(x) {
val_index <- match(x[length(x)], datetime)
c(val_index,datetime[val_index])
})
输出1:
$`08/19/2011`
[1] 4
$`08/22/2011`
[1] 9
$`08/23/2011`
[1] 13
$`08/24/2011`
[1] 12
$`11/24/2015`
[1] 15
$`12/23/2012`
[1] 14
输出2:
$`08/19/2011`
[1] "4" "8/19/2011 19:30"
$`08/22/2011`
[1] "9" "8/22/2011 19:30"
$`08/23/2011`
[1] "13" "8/23/2011 7:30"
$`08/24/2011`
[1] "12" "8/24/2011 7:00"
$`11/24/2015`
[1] "15" "11/24/2015 7:13"
$`12/23/2012`
[1] "14" "12/23/2012 19:23"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句