I have cities (from A to D) that have different populations and are at different distances. The goal is to reduce the total population living within a circle of radius (distance XY), where X is the city in the center of the circle and Y is any other city.
In this code:
Df <- structure(list(Town_From = c("A", "A", "A", "B", "B", "C"), Town_To = c("B", "C", "D", "C", "D", "D"), Distance = c(10, 5, 18, 17, 20, 21)), .Names = c("Town_From", "Town_To", "Distance"), row.names = c(NA, -6L), class = "data.frame") Df2 <- structure(list(Town = c("A", "B", "C", "D"), Population = c(1000, 800, 500, 200)), .Names = c("Town", "Population"), row.names = c(NA, -4L), class = "data.frame") Df <- Df %>% left_join(Df2,by=c("Town_From"="Town")) %>% left_join(Df2,by=c("Town_To"="Town"))%>% group_by(Town_From) %>% arrange(Distance) colnames(Df)[4]<-c("pop_TF") colnames(Df)[5]<-c("pop_TT") Source: local data frame [6 x 5] Groups: Town_From [3] Town_From Town_To Distance pop_TF pop_TT <chr> <chr> <dbl> <dbl> <dbl> 1 AC 5 1000 500 2 AB 10 1000 800 3 BC 17 800 500 4 AD 18 1000 200 5 BD 20 800 200 6 CD 21 500 200
Cities were organized (Town_From) and organized (distance).
In a circle of radius 5 km (from A to C) live 1000 (in A) + 500 (in C) = 1500 people; 1500 + 800 (in B) = 2300 live in the next circle. 2300 people still live in the third circle, because cities A, B, C are in a radius from B to C = 17 km. Within the radius of the circle from A to D = 18 km, live 2300 + 200 (in D) = 2500 people.
Here is a visualization of the circles in question. Theoretically, circles can expand to any arbitrary radius. In practice, I only need to check them at distances between pairs of cities (places where the counters change).
