R programming how to convert a for loop within for loop structure into apply function?

时间:2016-11-09 06:55:22

标签: r

So I need to merge two data frames. The first one contains columns of the max and min values, and the second one contains a column of value that I want to use to match the min to max range of the first one. The result should be a data frame that contains information from both the first df and the second. How do I do this efficiently? Below is the codes that I currently am using. But it's super slow.

theatre_Friday_night_trips <- data.frame()

index <- 1

for (i in 1:nrow(theater_coord)){
  lon_min <- theater_coord[i, "lon_min.y"] 
  lon_max <- theater_coord[i, "lon_max.y"] 
  lat_min <- theater_coord[i, "lat_min.y"]
  lat_max <- theater_coord[i, "lat_max.y"]
  for (j in 1:nrow(Friday_night_trips)){
    if (Friday_night_trips[j, "pickup_longitude"] >= lon_min & 
        Friday_night_trips[j, "pickup_longitude"] <= lon_max &  
        Friday_night_trips[j, "pickup_latitude"] >= lat_min &  
        Friday_night_trips[j, "pickup_latitude"]<= lat_max) {
    print ("found matched trip")
    theatre_Friday_night_trips[index, "theatre_lat"] <- theater_coord[i, "lat.x"]
    theatre_Friday_night_trips[index, "theatre_lon"] <- theater_coord[i, "lon.x"]
    theatre_Friday_night_trips[index, "theatre_name"] <- theater_coord[i, "value.y"]
    theatre_Friday_night_trips[index, "pickup_datetime"] <- Friday_night_trips[j, "tpep_pickup_datetime"]
    theatre_Friday_night_trips[index, "pickup_longitude"] <- Friday_night_trips[j, "pickup_longitude"]
    theatre_Friday_night_trips[index, "pickup_latitude"] <- Friday_night_trips[j, "pickup_latitude"]
    theatre_Friday_night_trips[index, "dropoff_longitude"] <- Friday_night_trips[j, "dropoff_longitude"]
    theatre_Friday_night_trips[index, "dropoff_latitude"] <- Friday_night_trips[j, "dropoff_latitude"]
    index <- index +1 
  }
   }
}

0 个答案:

没有答案