Announcement

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

  • creating macros/loops to count string variables

    Hi

    I have a variable 'operative procedure' which lists operation codes which are strings. These codes can be grouped for example 'right hemicolectomy' might take on code h079 or h071. I want to count the number of right hemicolectomies per patient. I need to create a loop that will allow me to define other procedures should as 'total colectomy' which will also have multiple codes and hence need to create a loop for this.

    local righthemi `" "h071" "h079" "'
    foreach v of varlist opcs {
    count if `v' == `righthemi'
    }

    when i use this syntax i get an error code saying invalid '"h079'
    any advice on how to approach the problem?

  • #2
    What went wrong: You defined local macro righthemi to have the content "h071" "h079". So when you get to -count if `v' == `righthemi'- this expands to -count if `v' == "h071" "h079"-. Well, that's not legal syntax: the "h079" is just hanging at the end with no relationship to the rest of the command. What I think you meant to do is something count the number of observations in which `v' is either h071 or h079. The simplest way to do this, provided that no procedure has more than 9 different codes is:
    Code:
    local righthemi `" "h071", "h079" "' // COMMA SEPARATION IS ESSENTIAL
    foreach v of varlist opcs {
        count if inlist(`v', `righthemi')
    }
    If, however, you will be applying this to procedures for which there are more than 9 codes, this code will fail because -inlist()- only allows 9 string comparators maximum. In that case
    Code:
    local righthemi `" "h071" "h079" "' // N.B. NO COMMA HERE
    foreach v of varlist opcs {
        local total_count = 0
        foreach code of local righthemi {
           quietly  count if `v' == `"`code'"'
            local total_count = `total_count' + `r(N)'
        }
        display `total_count'
    }
    As an aside, though it is harmless, there is nothing to be gained by looping over a varlist that contains only one variable. The loop could be replaced with:
    Code:
    local righthemi `" "h071", "h079" "'
    count ifinlist(`v', `righthemi')
    And an analogous simplification could be made in the second approach.
    Last edited by Clyde Schechter; 29 Sep 2023, 10:11.

    Comment


    • #3
      thanks Clyde for such a comprehensive answer!

      Comment

      Working...
      X