Dear all,

I have a data structure as below and based on the structure I want to calculate five variables:

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str6 date byte id float(longitude latitude)
"201910"  1 114.188 22.3719
"201910"  2 114.043 22.3621
"201910"  3 114.169 22.3193
"201910"  4 114.134 22.2868
"201911"  5 114.209 22.3335
"201911"  6 114.202 22.4004
"201911"  2 114.043 22.3621
"201911"  3 114.169 22.3193
"201911"  7 114.057 22.3662
"201912"  1 114.188 22.3719
"201912"  8  114.14  22.372
"201912"  9 114.261 22.3117
"201912" 10 114.221 22.3319
"201912"  3 114.169 22.3193
"201912"  5 114.209 22.3335
end
From the second period (201911),
for id 5, I want to calculate the pairwise distance between id=5 and all the IDs in the last period (201910) if id!=6.
then keep the ids if the pairwise distance between this id and id5 is smaller than 5km.
calculate the number of ids falling in the radius of 5km (for id=5 and date=201911) and give this value to variable nonc.
calculate the sum of weighted density for ids falling in the radius of 5km (for id=5 and date=201911) sum (1/pairwise distance between id i and id j) and give this value to variable wnonc.
calculate the same two variables for all the ids.

calculate the pairwise distance with all the ids in the previous periods (for instance, for id=5 date=201912, previous period are 201911 and 201910).
then keep the ids if the pairwise distance between this id and id5 is smaller than 5km.
calculate the number of unique ids falling in the radius of 5km (for id=5 and date=201912) and give this value to variable c. (for instance, 3 appeared twice in the previous period, only calculate the first one.
calculate the sum of weighted density for ids falling in the radius of 5km (for id=5 and date=201911) sum (1/pairwise distance between id i and id j) and give this value to variable wec.
calculate the same two variables for all the ids.

Please let me know if you have any idea how to implement this.

Thanks a lot.