Announcement

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

  • Using foreach to perform an action on a range of observations

    I'm pretty new to Stata and have been struggling with something that I know shouldn't be this difficult. I am trying to reverse geocode a dataset of 14,000 observations, but can only evaluate 2,500 observations per day for free. I already did the first 2,500 and am now trying to do the next 2,500. I can't figure out how to write a loop so that the command executes over observations 2,500-5000. Right now, I'm just testing the logic by trying to display the values of variable 'latitude' for observations 2501-2506.

    This is what I have been trying:
    Code:
    foreach i of list latitude 2501/2506 {
    2. di `i'
    3. }

    And I'm getting an invalid syntax error.

    I also tried
    Code:
    foreach i in latitude 2501/2506 {
    2. di latitude
    3. }

    For this one, it returns the latitude value of observation 1 twice.

    Any suggestions would be greatly appreciated! Thanks!

  • #2
    Code:
    forval i= 2501/2506{
        list latitude in `i'
    }
    or with display

    Code:
    forval i= 2501/2506{
        di latitude[`i']
    }
    Last edited by Andrew Musau; 10 Dec 2021, 14:28.

    Comment


    • #3
      in your first try, you used invalid syntax as Stata told you; please review
      Code:
      help foreach
      to see what is valid

      in your second, you never used the "i"

      it is not clear to me what you are trying to do but you may find using forval easier; see
      Code:
      help foval
      more, here is a guess:
      Code:
      foreach i of numlist 2501/2506 {
      di latitude if _n==`i'
      }
      
      or
      
      forval i=2501/2506 {
      di latitude in `i'
      }
      note that either "in" or "if" can be used in either command - I just wanted to show each

      Comment


      • #4
        Unfortunately, in and if qualifiers can't be combined with display as Rich Goldstein suggests in #3. You could use subscripts as in #2 but to see values in the example given

        Code:
        list latitude in 2501/2506
        seems much simpler to me .

        Comment

        Working...
        X