Announcement

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

  • Keeping variables from a list

    Hello everyone,

    I'd like to know if there's a way to keep in my dataset, the observations that are returned from a list. To give you some context, I have a panel data set, where I want to keep just some IDs that satisfy certain condition on the initial year. So I get the list of the IDs that I need, but it's too large to write a keep if, so I would like to keep the observations that only have those IDs.

    Below it's the code that returns the IDs (which are called mrun in this database) that I need to keep.

    Code:
    list mrun if cod_ense2==2 & agno==2016 & (cod_grado==1 | cod_grado==2 | cod_grado==3 | cod_grado==4)
    Thanks for the help!

  • #2
    Code:
    by mrun, sort: egen keeper = max(cod_ense2==2 & agno==2016 & (cod_grado==1 | cod_grado==2 | cod_grado==3 | cod_grado==4))
    keep if keeper
    By the way: -(cod_grado==1 | cod_grado==2 | cod_grado==3 | cod_grado==4)- can be shortened to -inlist(cod_grado, 1, 2, 3, 4)-, and if cod_grado is always an integer, it can be further shortened to -inrange(cod_grado, 1, 4)-.

    Added: Just noticed that #1 in this thread is a duplicate post of https://www.statalist.org/forums/for...es-from-a-list, where Nick Cox responded with the same solution and comments.
    Last edited by Clyde Schechter; 08 Nov 2022, 16:24.

    Comment


    • #3
      Spot on. Also see https://www.stata.com/support/faqs/d...ble-recording/ for the technique used. I guess Boole got there earlier, and perhaps Leibniz.

      Comment

      Working...
      X