Hi everyone,

I have a question about how to calculate the population density of the neighborhood in a location.

My data looks like this:
Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str36 location float(longitude latitude population)
"1"  114.1539 22.2488 100
"2"   113.975 22.4032 200
"3"  114.2438 22.4287  50
"4"  114.2286 22.2811  60
"5"  114.1036 22.3783  20
"6"  114.2171 22.3251 300
"7"  114.1514 22.2445  50
"8"  114.1472  22.334 200
"9"  114.2623 22.3064 100
"10" 114.0614 22.3674  40
end
What I want to do is: first: calculate the geographical distance dij between every two locations.
second, change the geographical distance dij to (1/dij)*population(j) if the distance is smaller than 5(km)
third, change other geographical distance dij to 0 if the distance is larger than 5(km)

The code that I use is as below:
Code:
forval i = 1/`=_N' {
  local olat = latitude[`i']
  local olong = longitude[`i']  
  local pop=population[`i']
  geodist latitude longitude `olat' `olong', gen(dist`i')
replace dist`i'=. if dist`i'>5
replace dist`i'=0.1 if dist`i'<0.1
replace dist`i'=1/dist`i'*pop if dist`i'<5
}
I replace dist`i'=0.1 if dist`i'<0.1 because the distance with oneself is very close to 0 and stata cannot process 1/d if d is very small.
However, the problem with this code is that for //replace dist`i'=1/dist`i'*pop if dist`i'<5//, I want to time 1/dist with the population of j. For instance, for location 2, the distance between location 2 and location 6 is 4, then I want t o calculate 1/4*(population of location 6), but current code gives me 1/4*(population of location 2).

I wonder if anyone can help me with this.

Thank you very much and look forward to your reply.