How do I exchange a apply inside a for for for a double apply?

Asked

Viewed 70 times

5

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

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

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)

}

So I’d like to know if there’s another way and avoid that for and make it already rotate to all lines of both vectors.

1 answer

2


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

Consider origem and destino lists or data.frames thus:

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 the combinations:

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

Now you can apply the function you want 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))

It is unlikely that this is the simplest/least line of code solution. But, thinking this way helps to do several other analyses, as you can find here

  • Oops, thanks again Falbel! In addition to the answer to the original problem, I found very interesting the idea of list-column. I’ve had problems where I had to run the code several times to get different information, but I never had the idea to store in list. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.