如何在 for 循环中忽略 NA

How to ignore NA in a for loop

我在 lubridate 中有一个时间间隔向量,其中混合了一个 NA 值,如下所示。我有第二个数据框,其中包含每分钟的数据。我正在尝试通过间隔为 运行 编写一个 for 循环,并且只包含每个间隔内的时间戳。

timespan
2016-05-24 11:05:00 UTC--2016-05-24 11:07:59 UTC
2016-05-24 11:08:00 UTC--2016-05-24 11:10:59 UTC
2016-05-24 11:11:00 UTC--2016-05-24 11:13:59 UTC
2016-05-24 11:18:00 UTC--2016-05-24 11:22:59 UTC
2016-05-24 11:26:00 UTC--2016-05-24 11:30:59 UTC
2016-05-24 11:32:00 UTC--2016-05-24 11:36:59 UTC
2016-05-24 11:40:00 UTC--2016-05-24 11:44:59 UTC
2016-05-24 11:47:00 UTC--2016-05-24 11:51:59 UTC
2016-05-24 11:53:00 UTC--2016-05-24 11:57:59 UTC
2016-05-24 11:59:00 UTC--2016-05-24 12:03:59 UTC
2016-05-24 12:11:00 UTC--2016-05-24 12:12:59 UTC
NA
2016-05-24 12:18:00 UTC--2016-05-24 12:22:59 UTC

除了一个 NA 值,我的代码有效。

ref = list()
for (i in 1:nrow(df)) {
  ifelse (!is.na(timespan), ref[[i]] <- df[ACC$Timestamp %within% timespan[i], ], NA)
 }

我的引用列表是正确的,除了倒数第二个值,它保留了 df 中的所有行,当我最终将列表绑定在一起时,它会抛出所有内容。

感谢您的帮助!

编辑:

dput(timespan)
new("Interval", .Data = c(179, 179, 179, 299, 299, 299, 299, 
299, 299, 299, 119, NA, 299), start = structure(c(1464087900, 
1464088080, 1464088260, 1464088680, 1464089160, 1464089520, 1464090000, 
1464090420, 1464090780, 1464091140, 1464091860, NA, 1464092280
), tzone = "UTC", class = c("POSIXct", "POSIXt")), tzone = "UTC")

这个有用吗:

ref = list()
for (i in 1:nrow(df)) {
  if (!is.na(timespan[i])){
       ref[[i]] <- df[ACC$Timestamp %within% timespan[i], ]
      } else
        ref[[i]] <- NA
 }