【发布时间】:2011-08-26 23:55:52
【问题描述】:
我有 55 个POSIXct 类型向量。 ptime 向量是参考向量。我想在 ptime 和其余向量之间找到匹配的日期。匹配日期后,我想进行时间比较。随后进行时间比较,结果将填充到 data.frame(test) 中,并带有适当的分类号。
# create the reference and the other vectors
ptime <- sample(seq(as.POSIXct('2005-08-01'),as.POSIXct('2006-05-31'), by='hour'),1051)
dawn <- sample(seq(as.POSIXct('2005-01-01'),as.POSIXct('2007-12-31'),by='hour'),1095)
sunrise <- sample(seq(as.POSIXct('2005-01-01'),as.POSIXct('2007-12-31'),by='hour'),1095)
sunset <- sample(seq(as.POSIXct('2005-01-01'),as.POSIXct('2007-12-31'),by='hour'),1095)
dusk <- sample(seq(as.POSIXct('2005-01-01'),as.POSIXct('2007-12-31'),by='hour'),1095)
# extract the date to compare using only the `dawn` vector
# all other vectors (except ptime) have the same date and length
pt <- as.Date(ptime)
dw <- as.Date(dawn)
# create data.frame
time <- c(1:1051)
test<-data.frame(time)
# I use a data.frame because I want to re-populate an existing data.frame
> str(test)
'data.frame': 1051 obs. of 1 variable:
$ time: int 1 2 3 4 5 6 7 8 9 10 ...
# this is the loop that matches and assigns
for( b in 1:length(ptime) ){
for( a in 1:length(dawn) ) {
if( dw[a] == pt[b] ){
if( ptime[b] < dawn[a] ) {
test$time[b] <- 1
}else if( ptime[b] < sunrise[a] ) {
test$time[b] <- 2
}else if( ptime[b] < sunset[a] ) {
test$time[b] <- 3
}else if( ptime[b] < dusk[a] ) {
test$time[b] <- 4
}else
test$time[b] <- 1
}
}
}
# output result shows the categorization sequence of 1, 2, 3, and 4
> head(test)
time
1 1
2 1
3 3
4 1
5 1
6 3
上面的代码完成了我想做的事情......但它需要98.58 秒。我有更多长度不同的数据(最多 5000 个)。
由于我是这方面的新手,我的猜测是......需要这么多时间的是日期的比较。每次必须进行新的比较时dw[a] == pt[b],该过程必须搜索dw[a]。另外,if-else 语句是完成任务所必需的吗?
谁能提供一种更快/更有效的方法来loop 通过、查找匹配项并存储结果?
非常感谢。谢谢
【问题讨论】:
-
您的代码不可重现,换句话说,当我在我的机器上运行它时会出错。请让您的示例可重现。
-
编辑了我的帖子。示例代码应该可以工作。谢谢
-
请再试一次。为确保您的示例可重现,请从干净的 R 会话开始并尝试运行您的代码。
-
我们去吧。对此感到抱歉