dimanche 9 juin 2019

R: Why my if function based on a time difference doesn't work inside my 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

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?

Aucun commentaire:

Enregistrer un commentaire