Announcement

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

  • SAS-like Arrays in Stata using Geodist?

    I'm trying to find the distance between two lat/long points in Stata. I have 15 lat/long pairs of coordinates in a wide format, and I want to find the distance between (lat1, long1), (lat2, long2) and (lat2, long2), (lat3, long3), etc. Below is an example of two points.

    lat1 lon1 lat2 lon2
    39.9522613 -75.1949641 39.9482853 -75.1962355

    I found the "geodist" function to be useful, so I'd like to use it to loop through everything. I tried the following, but it did not work. Any suggestions?

    Code:
    forval i = 1/15 {
         geodist lat`i' lon`i' lat(`i'+1) lon(`i'+1), gen(km_`i')
    }
    Was expecting a number or a numeric scalar instead of -lat(1+1)-
    r(198);
    I also previously had my data in LONG format, with each lat/long coordinate on a separate row, and I tried the following with no luck.

    Code:
    geodist latitude longitude latitude[_n-1] longitude[_n-1], gen(km)
    Last edited by Robert Charles; 17 Aug 2023, 11:32.

  • #2
    Stata doesn't have the same construct as SAS -array-, but it does have local macros which are both more flexible and more (broadly) useful. However, it may take a little more setup to get it working in a similar manner, depending on what you are trying to do. For example, local macros cannot be indexed like a tuple, but there are macro functions that can pull out specific words by position, thus offering a similar mechanism.

    To your question, the loop is the way that I would go. The long format approach won't work in this case because -geodist- evidently requires variable names, and that implies a wide-layout.

    You were nearly there with your first attempt, but you'll need one more level of nested macros to evaluate the intended arithmetic (i + 1).

    Code:
    forval i = 1/15 {
         geodist lat`i' lon`i' lat`=`i'+1' lon`=`i'+1', gen(km_`i')
    }
    The macro is resolved from the innermost level, outwards. For example, on the first iteration when i=1:
    `=`i'+1' becomes/resolves to ==> `=1+1'
    `=1+1' becomes 2

    Comment


    • #3
      Thank you, Leonardo! That worked!

      Comment


      • #4
        You’re welcome. For a more detailed elaboration, see this Stata FAQ.

        Comment

        Working...
        X