Andy
Andy

Reputation: 65

How to ignore NA in a for loop

I have a vector of time intervals in lubridate that has an NA value mixed in as shown below. I have a second data frame with minute by minute data. I am trying to write a for loop to run through the intervals and only include timestamps that are within each interval.

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

The code I have works except for the one NA value.

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

My ref list is correct except for the second to last value which kept all rows from df which throws everything off when I eventually bind the list together.

Thanks for the help!

EDIT:

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")

Upvotes: 0

Views: 5089

Answers (1)

Cettt
Cettt

Reputation: 11981

Does this work:

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
 }

Upvotes: 1

Related Questions