【问题标题】:Comparing date ranges between different length vectors in R比较 R 中不同长度向量之间的日期范围
【发布时间】:2017-05-10 18:43:57
【问题描述】:

我在下面的示例中遇到了一些问题,我们将不胜感激。

我有两个向量 x 和 y。 x 是一个长度为 78,725 的向量,其中包含从 "2017-04-23 06:55:00 UTC" to "2017-04-27 17:00:52 UTC" 开始的日期范围,但每个元素之间的时间间隔从 1 秒到几个小时不等。 y 是一个长度为 8640 的向量,其中包含从 "2017-04-23 00:00:00 UTC" to "2017-04-23 23:59:50 UTC" 开始的日期范围,增量为 10 秒。我想确定哪个x >= y and x < y

样本数据:

x <- as.POSIXct(c("2017-04-24 18:32:35", "2017-04-24 14:01:03", "2017-04-24 17:51:35",
                  "2017-04-24 15:42:22", "2017-04-24 13:00:51", "2017-04-24 16:56:28",
                  "2017-04-24 17:17:32", "2017-04-24 15:03:34", "2017-04-24 22:40:47",
                  "2017-04-23 17:37:15"), tz = "UTC")
base.date <- as.POSIXct("2017-04-23 0:00:00", tz = "UTC")
every = 10
seconds.in.day = 60*60*24
y <- seq(base.date, length = seconds.in.day / every, by = every)

我想要的结果:

x 的第 10 个位置,即"2017-04-23 17:37:15 UTC" 在 y 元素 6344 和 6345 之间。

尝试了以下方法:

mapply(function(x, y) x >= y & x < y, as.data.frame(x), as.data.frame(y))

和

Position(function(x) x >= y & x < y, x)

和

vapply(x, function(x) x >= y & x < y, logical(NROW(x)))

这些都没有返回我想要的东西

【问题讨论】:

  • 欢迎使用 stackoverflow,请提供可重现的数据示例和所需的输出。
  • 已转发

标签: r date datetime


【解决方案1】:

因为x 中只有一个观察值落在y 的范围内,所以您的采样数据很困难。所以我写了以下内容来解释这一点。试试这个...

# Filter down only to observations within the date range of y
 x_range <- x[max(y) >= x & min(y) <= x]

 for (i in length(x_range)) {
   upper.y.index <- vector('numeric')
   upper.y.index[i] <- which.max(y < x_range[i])

   lower.y.index <- vector('numeric')
   lower.y.index[i] <- which.max(y >= x_range[i])
 }


 upper.y.index
 [1] 1
 lower.y.index
 [1] 6345

【讨论】:

  • 感谢@Mark,但我对您的建议做了一些修改,以避免出现for循环lower.y.index &lt;- sapply(x_range, function(x) which.min(y &lt;= x) - 1)upper.y.index &lt;- sapply(x_range, function(x) which.max(y &gt; x))y[lower.y.index]y[upper.y.index]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
相关资源
最近更新 更多