I have towns (from A to D), which have different populations, and are at different distances. The objective is to add up the total population living within the circle of radius (distance XY) where X is a town in the centre of the circle and Y any other town.
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 A C 5 1000 500
2 A B 10 1000 800
3 B C 17 800 500
4 A D 18 1000 200
5 B D 20 800 200
6 C D 21 500 200
towns have been organised by (Town_From) and arranged by (distance).
Within the circle of 5km radius (from A to C) live 1000 (in A) + 500 (in C)= 1500 people; within the next circle live 1500 + 800 (in B) =2300. Within the third circle still live 2300 people because towns A, B, C are within the circle radius B to C = 17 km. Within the Circle radius A to D = 18km, live 2300 + 200 (in D)=2500people.
Here is a visualization of the circles in question. In theory, the circles could expand to any arbitrary radius. In practice, I only need to check them at the distances between pairs of towns (places where the counts change).