Announcement

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

  • Counting observations that satisfy a criteria, then using the resulting number in an 'if' statement

    Hi,

    I'm fairly new to Stata and am having difficulty with a bit of code that would be straightforward in other languages I'm familiar with.

    As the topic title says, I want to count observations that satisfy a criteria, then using the resulting number in an 'if' statement. The pseudocode would look something like this (assuming 'treated' is a binary 1/0 variable):

    gen treated_count = count(treated) if treated = 1

    if treated_count < 1 do something
    if treated_count == 1 do something else
    if treated_count > 1 do something else

    Thanks in advance for any help!

    Jack

  • #2
    Jack,

    Try this:

    Code:
    count if treated==1
    if `r(N)'<1 {
      something
    }
    else if `r(N)'==1 {
       something else
    }
    else if `r(N)'>1 {
      something else
    }
    This is a literal interpretation of your pseudo-code. However, depending on the "something" or "something else" you want to do, there may be better solutions. Keep in mind that, unlike most other programming language, Stata executes each statement on the entire data set before going to the next statement. This often changes the programming paradigm compared to what you are used to.

    Regards,
    Joe

    Comment


    • #3
      Thanks, that seems to work. Although it is rather slow.

      I'm basically automating a series of Nearest Neighbour matches on different datasets using nnmatch. Ideally I would run nnmatch using the 'average treatment effect in the treated' (ATT) option, but some of my datasets only have 1 treated observation and you get an "insufficient observations" error. However, you can use nnmatch on a dataset with a single treated observation if instead you use the 'average treatment effect' (ATE) option. This is slower as it matches all of the observations, rather than just the treated ones. So I was aiming to switch between the ATE and ATT options depending on how many treated observations there are.

      Please let me know if you can think of a simpler / quicker way of doing this.

      Thanks!

      Jack

      Comment


      • #4
        This is just a comment (pedantic if you wish) that "criteria" is a plural of which the singular is "criterion". I think either word has a long way to go before reaching the condition of "data" which is singular or plural in different hands.

        Comment

        Working...
        X