Q:

Count match ratio between two dataset

I have two dataset wanted to count match Ratio
> events_data       
  LONGITUDE LATITUDE  matchvalue
1     122.5    9.5    0.006269592
2     122.5   10.5    0.050156740
3     125.5   10.5    0.043887147
4     146.5   40.5    0.048213166
5     142.5   40.5    0.035078370
6     146.5   40.5    0.028213166

> events            
  LATITUDE LONGITUDE
1    9.880  124.1167
2   37.156  144.6611

using events(within 5 both in latitude and longitude) to select data in events_data
when  events_data.matchvalue > 0.04, set this row data in events_data is ture, or is flase
count match Ratio = (totalRows in events_data is ture)/(totalRows in events_data is ture + totalRows in events_data is false)

take event 1 for example
1.  select data in events_data within latitude(9.880 +/- 5) and longitude(124.1167 +/-5),you can get data in events_data:
   LONGITUDE LATITUDE  matchvalue 
 1     122.5    9.5    0.006269592
 2     122.5   10.5    0.050156740
 3     125.5   10.5    0.043887147
2.  count(events_data.matchvalue > 0.04) = 2
3.  count match Ratio = 2/3 = 0.67

my expect is add a new column match_Ratio
  LATITUDE LONGITUDE  match_Ratio
1    9.880  124.1167  0.67
2   37.156  144.6611  0.33

my data used are:
events_data <- structure(list(LONGITUDE = c(122.5, 122.5, 122.5, 146.5, 142.5, 
146.5), LATITUDE = c(9.5, 10.5, 10.5, 40.5, 40.5, 40.5
), matchvalue = c(0.00626959247648903, 0.0501567398119122, 0.0438871473354232, 
0.0482131661442006, 0.0350783699059561, 0.0282131661442006)), .Names = c("LONGITUDE", 
"LATITUDE", "matchvalue"), row.names = c(NA, 6L), class = "data.frame")

events <- structure(list(LATITUDE = c(9.88, 37.156), LONGITUDE = c(124.1167, 
144.6611)), .Names = c("LATITUDE", "LONGITUDE"), class = "data.frame", row.names = 1:2)

How to implement it, thanks

A:

Here is a straightforward base R solution. 
long <- events_data$LONGITUDE
lat <- events_data$LATITUDE
myVals <- events_data$matchvalue

events$match_Ratio <- apply(events, 1, function(x) {
    z <- which(lat > (x[1] - 5) & lat < (x[1] + 5))
    v <- which(long > (x[2] - 5) & long < (x[2] + 5))
    ind <- intersect(z, v)
    sum(myVals[ind] > 0.04)/length(ind)
})

events
  LATITUDE LONGITUDE match_Ratio
1    9.880  124.1167   0.6666667
2   37.156  144.6611   0.3333333

