Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • calculating distance in a loop using 'spdistance' in STATA 15

    Dear Statalisters

    I have shapefile containing information about the geographic coordinates of all the districts in Pakistan. I am required to have a variable of the distance between a border district and the rest of all the districts. I am using STATA 15's 'spdistance' command to calculate it. As the syntax for 'spdistance' returns the distance between two district IDs whereas I want to calculate the distance between 93 districts. Is there any way I can do it in a loop? I am writing the codes here as I am not sure how to use 'dataex' with shapefile.

    capture drop distance
    gen distance=.
    local id 20 54 94 95 99 101
    spdistance `id' 96 (* where 96 is the id for border district which will remain fixed)
    replace distance=r(distance) if distt_id==`id'

    however, this code returns an error i.e
    94 95 99 101 96 found where nothing expected
    r(198);


  • #2
    You didn't get a quick answer. You'll increase your chances of a useful answer by following the FAQ on asking questions - provide Stata code in code delimiters, readable Stata output, and sample data using dataex.

    I don't use spdistance, but the documentation is clear it works with two id's. So, set up a loop over id's and then save each of the distances where ever you want them saved. Often this is done by setting up a variable with all empty values and replacing the appropriate values after each invocation of the procedure (spdistance).

    Comment


    • #3
      Dear Phil

      Many thanks for your reply. Yes, you are right I should have provided Stata code and output using dataex.
      However, as you advised, I tried to loop over id's and save the distance in a new variable "distance". The following code I used and it worked.

      Code:
      capture drop distance
      gen distance=.
      local j 96 /*96 is the code for border district*/
      local id 54 94 95 99 101 104
      forvalues w=1/6{
      local i : word `w' of `id'
      spdistance `i' `j'
      local d=r(distance)
      replace distance=`d' if distt_id==`i'
      }
      Thanks.

      Comment

      Working...
      X