R chron%in%比较仅识别每隔一个日期

问题描述 投票:2回答:1

我在R中使用zoo和chron包来读取和转换数据。有一次,我需要选择与另一个chron对象相对应的chron-indexed zoo对象的一部分。不幸的是,使用%in%运算符我只获得相应日期的一部分。这是一个重现错误的MWE:

library(chron)
library(zoo)
chron1 <- seq(chron("2013-01-01","00:00:00", format=c(dates="y-m-d",times="h:m:s")),
              chron("2013-01-01","03:10:00", format=c(dates="y-m-d",times="h:m:s")),by=1./1440.)
x1 <- runif(200)
z1 <- zoo(x1,chron1)
chron10 <- trunc(chron1, "00:10:00")
x10 <- aggregate(z1,chron10,FUN=sum)
which(index(x10) %in% chron1)

(意外)输出是:

[1]  1  3  5  7  9 10 12 14 16 18 19
r date zoo chron
1个回答
3
投票

chron对象是浮点数,因此根据计算方式,可能会出现相同日期时间的细微差别。 format他们并比较那些:

which(format(index(x10)) %in% format(chron1))
## [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

这也有效,因为trunc使用eps值来确保稍微不到一分钟的输入不会再被截断。见?trunc.times

which(trunc(index(x10), "minutes") %in% trunc(chron1, "minutes"))
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

另见R FAQ 7.31

© www.soinside.com 2019 - 2024. All rights reserved.