Announcement

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

  • Extracting geographical coordinates from string

    My data set includes a string variable called -geo-, which looks like this:

    Code:
    {u'type': u'Point', u'coordinates': [36.2743876, -80.8518072]}
    What code can be used to extract the two "enclosed" coordinates (i.e., latitude and longitude) from -geo- variable as two separate variables?

    Thank you in advance for help!

  • #2
    Anton Ivanov are you trying to read Python dicts from a console file? If not, it looks like it would be fairly standard JSON (minus the u prefix for the strings). If that is the case you could use jsonio to read and write JSON data. You can install it with:

    Code:
    net install jsonio, from("https://wbuchanan.github.io/StataJSON") replace

    Comment


    • #3
      Here's another solution. (I'm not one to use regular expressions, but I found them easier here than a solution with strpos, substr, and subinstr. I also broke up the solution into steps, as these kinds of string manipulations, in my experience, make for error-prone code, off-by-one errors, etc.) Someone else might well do this more elegantly than I did:
      Code:
      clear
      // Example data
      set obs 1
      gen s = "{u'type': u'Point', u'coordinates': [36.2743876, -80.8518072]}"
      gen snew = regexr(s, "^.*\[", "")            // strip leading stuff
      //
      // latitude
      gen slat = regexr(snew , ",.*$", "")        // strip trailing stuff
      gen double latitude = real(slat)
      // longitude
      gen slong = regexr(snew, "^.*,", "")        // strip leading stuff
      replace slong = regexr(slong, "\].*$", "")  // strip trailing stuff
      gen double longitude = real(slong)
      drop snew slat slong
      //
      format latitude longitude %12.7f
      list s latitude longitude

      Comment


      • #4
        Mr. Lacy, thank you for response. Your suggestion worked perfectly.

        wbuchanan, I also appreciate your feedback and will explore jsonio for my future tasks.

        Comment

        Working...
        X