Tommaso Saccà
Tommaso Saccà

Reputation: 15

Why doesn't my time difference based if function work inside a for loop?

I have a series of animal observations linked with the time of the day. I need to group them in the following way for successive analyses; all the observations that are less than 10 minutes apart from the previous are in the same group. When an observation is more than ten minutes apart from the previous it starts a new group.

For this I've done a for loop with an if statement

wilde16 <- structure(list(Species = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "wildebeest", class = "factor"), 
    Total_Ind = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L), DateTime = structure(c(1464449354, 1464449370, 
    1464449393, 1464449402, 1464449876, 1464449954, 1464450303, 
    1464450624, 1464450640, 1464450656, 1464450953, 1464450969, 
    1464450985, 1464451132, 1464451148, 1464451165), class = c("POSIXct", 
    "POSIXt"), tzone = "Africa/Dar_es_Salaam")), row.names = c(99L, 
100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 110L, 128L, 129L, 
132L, 142L, 144L, 146L), class = "data.frame")    

class(wilde16$DateTime)
[1] "POSIXct" "POSIXt" 

wilde16$DateTime[223]
[1] "2016-05-30 09:54:54 EAT"

z <- 0

for(i in 1:length(wilde16$DateTime)){
if(wilde16$DateTime[i+1]-wilde16$DateTime[i]<600){
    wilde16$Group[i] <- z
  } 
  else{ 
    z <- z + 1
    wilde16$Group[i] <- z
    }
 }

Yet when I run it returns the error message

"Error in if (wilde16$DateTime[i + 1] - wilde16$DateTime[i] < 600) { : missing value where TRUE/FALSE needed"

Even though if I try the lines

i <- 1
(wilde16$DateTime[i + 1] - wilde16$DateTime[i] < 600)

it returns

[1] FALSE

What's wrong?

Upvotes: 0

Views: 51

Answers (1)

i94pxoe
i94pxoe

Reputation: 607

As @Henry observed, you have a index issue.

If you are trying to find intervals on your vector, you can probably avoid the for loop by using the function findInterval().

interval <- seq.POSIXt(from = min(wilde16$DateTime), to = max(wilde16$DateTime), by = "10 min")
z <- findInterval(x = wilde16$DateTime, vec = interval)

Upvotes: 1

Related Questions