0

I am trying to make loops to calculate Speed for all "Longitude, Latitude and Timestamp" points. But loops are not working. Based on Min and Max values of a Speed i am filtering the points and saving them in other vectors. I just want to save latitude and longitude in one vector which satisfy condition of a Speed and save remaining latitude and longitude in other vector. Thanks

i = 1
j = i + 1
distt <<- 0
time_TT <- 0
#Speed 
MIN <- 0.001
MAX <- 0.002
LON_S <-0
LAT_S <-0
z<-2
LON_SS <- 0
LAT_SS <- 0 



while (i < length(longitude))
{
  library(geosphere)
  dist <- distm (c(longitude [j],Latitude[j]), c(longitude [i],Latitude[i]), 
  fun = distVincentyEllipsoid)
  distt <- append(distt, dist)
  time_vector <- time[j] - time[i]
  time_TT <- append(time_TT, time_vector*60)  # converting mints into 
  seconds 
  speed <- distt/time_TT
  speed <- round(speed, 3)

  if ((speed[z] >= MIN) & (speed[z] <= MAX))
  {
    #speed is inside the range

    LON_S  <- append(LON_S, longitude [j])
    LAT_S  <- append(LAT_S, Latitude[j]) 
    z <- z + 1
  }
    #speed is outside the range

  LON_SS  <- append(LON_SS, longitude [j])
  LAT_SS  <- append(LAT_SS, Latitude[j]) 
  z <- z + 1

  i <- j
  j <- j + 1  }


  Error Message:

  Error in if ((speed[z] >= MIN) & (speed[z] <= MAX)) { : 
  missing value where TRUE/FALSE needed



 Data 

longitude <- round(c(48.7188021250007,
                 48.7188133749999,
                 48.7188291249998,
                 48.7188336250004, 
                 48.7188291250005), 8);

 Latitude <- round(c (2.39514523661229,
                 2.39512477447308, 
                 2.39472235230961,
                 2.39467460730213,
                 2.39467460730313), 8);

 time <- strptime(c('2017-04-06 09:15:00',
               '2017-04-06 09:30:00',
               '2017-04-06 09:40:00',
               '2017-04-06 09:45:00'),"%Y-%m-%d %H:%M:%S");
Asad
  • 31
  • 1
  • 7
  • You don't seem to be initialising `j` anywhere – Andrew Gustar May 03 '17 at 09:35
  • Could you please elaborate more on what exactly doesn't work? For a start, the code above doesn't have an ending brace of the while-statement. – MJZ May 03 '17 at 09:35
  • I didn't put initialization steps before, but now i did. – Asad May 03 '17 at 09:38
  • 1
    ...and what is the exact error message you get. Also note that 1) while loops are rarely a good solution in R and 2) you iteratively grow objects (`append(LON_S, ...)` which will become really slow for larger datasets. – Paul Hiemstra May 03 '17 at 09:39
  • Thank you for your reply. I have added the error message in the above post. – Asad May 03 '17 at 09:48
  • 1
    when `i` is 4 and `j` is 5, `z` is 5 but the fifth value of `time_TT` is `NA` hence a `NA` for the 5th value of `speed` hence the error – Cath May 03 '17 at 10:08

0 Answers0