I have a data frame with positions where a bus has had the speed zero (standing still). I want to determine if this is due to traffic conditions or because it has stopped at a bus stop. I have a function that calculates the distance from the center of a bus stop to any other position (the function is called in_circle
). If the bus has stopped within 20 meters from the center of the bus stop, I set stop_type
to 1 and move on to the next point at which a bus has stopped.
The code below is working, but I have a big amount of data and the two for-loops take quite a while to run. Therefore, I wonder if there is a more effective way to write the code below.
Edit: I added a picture of some rows of the data. https://i.stack.imgur.com/Ekvqv.png
k=1
for(i in 1:NROW(df_bus_h_z)){
# Save current longitude and latitude of the bus
cur_lat <- df_bus_h_z[i, "latitude"]
cur_lon <- df_bus_h_z[i, "longitude"]
# Controll boolean
stop_found = FALSE
#Search trough all bus stops
for(j in 1:NROW(df_stop_all)){
if(df_stop_all[j,"trip_id"] == cur_trip){
# If the bus stopped at a bus stop
if(in_circle(df_stop_all[j,"stop_lat"],df_stop_all[j,"stop_lon"], cur_lat, cur_lon) <= 20){
df_bus_h_z[i, "stop_type"] <- 1
df_bus_h_z[i, "stop_id"] <- df_stop_all[j,"stop_id"]
stop_found = TRUE
break
}
}
}
if(stop_found == FALSE){
df_bus_h_z$stop_type[i] <- 0
}
}