Announcement

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

  • How Can I Quickly Find an Observation with Specific ID in Stata?

    Hi, I have a small dataset for the purpose of demonstration below,
    clear
    input str80 id byte male
    000001 0
    000001 0
    000001 0
    000001 0
    000002 0
    000002 0
    000002 0
    000002 0
    000003 0
    000003 0
    000003 0
    000003 0
    000004 1
    000004 1
    000004 1
    end
    I just try to make sure that I can use Stata code to quickly identify an observation with specific ID. For example, I want to find where the observations with the ID of "000004" are.
    Can someone show me how to do this in Stata code?
    Thank you!
    Last edited by smith Jason; 17 Jul 2022, 13:17.

  • #2
    If by "identify," you mean "find out the observation numbers(s)," you could do:
    Code:
    list id if (id == 4) // obs numbers listed on the left
    If you want those observation numbers to go into an object you can use for some other purpose, you could do:
    Code:
    gen obs = _n
    tab obs if (id == 4), matrow(A)
    mat list A  
    //  Another possibility for making the list of observation numbers manipulable:
    levelsof obs if (id == 4), local(pos)
    di "`pos'"

    Comment


    • #3
      Thank you!

      Comment


      • #4
        You can be more succinct if you can ensure that any observations matching the filter criterion exists as a contiguous block of observations in your dataset (or perhaps don't exist at all). For example, in pseudo code:

        Code:
        // May wish to sort data first by some sensible way to group like observations, but only needed for ranges of observations
        gen `c(obs_t)' obs = _n
        summ myvar if mycond , meanonly
        Following this, summarize returns to local macros to r(min) and r(max) the first and last observation number matching the condition, respectively.

        Comment


        • #5
          Thank you!

          Comment

          Working...
          X