How to swap an apply within a for by a double apply?

5

I have a origem vector and a destino vector with several locations in latitude and longitude.

For each location in origem , I want to count how many places in destino are located within a radius of up to 2km, so I did a function that calculates the distanciaEmKm(lat1, long1, lat2, long2) distances.

I then solved the problem as follows:

for (i in 1:nrow(destino)) {

  dists <- mapply(distanceLatLongKm, origem$LAT[i], origem$LONG[i], destino$LAT, destino$LONG)
  origem$ATE_2KM[i] <- sum(dists <= 2)

}

Then I would like to know if there is another way and avoid this for and make it already run to all lines of both vectors.

    
asked by anonymous 18.01.2017 / 01:16

1 answer

2

One possible way is to generate all possible combinations and then apply normal apply. Combinations can be generated using something like expand.grid or so using the purrr package.

Consider origem and destino lists or data.frames like this:

origem <- list(
  id = 1:10,
  lat = 1:10,
  long = 1:10
)

destino <- list(
  id = 1:11,
  lat = 10:20,
  long = 10:20
) 

So you get all combinations:

library(purrr)
todas_combinacoes <- list(origem = origem, destino = destino) %>%
  map(transpose) %>% 
  cross_n()

Now you can apply the function you want by using mutate of dplyr . For distance, for example:

library(dplyr)
todas_combinacoes %>%
  mutate(
    id_origem = map_int(origem, ~.x$id),
    id_destino = map_int(destino, ~.x$id),
    distancia = map2_dbl(origem, destino, ~distanciaEmKm(.x$lat, .x$long, .y$lat, .y$long))
  ) %>%
  group_by(id_origem) %>%
  summarise(sum(distancia <= 2))

This is unlikely to be the simplest solution / with fewer lines of code. But, thinking that way helps you do a lot of other analysis, as you can find here >

    
18.01.2017 / 02:15