Announcement

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

  • Command that returns value if a variable contains a string anywhere inside of it

    Suppose I have data that looks like the following:

    Code:
    clear
    set obs 5
    gen x = ""
    replace x = "COST YTD" in 3
    I would like to save a local macro that is equal to 1 if the variable x contains the string "COST" in any row, and 0 if it does not contain it anywhere. To do this, I could do the following:

    Code:
    gen x_cost = strpos(x, "COST")
    egen x_cost_max = max(x_cost)
    if x_cost_max != 0 {
         local cost_str_exists = 1 
    }
    else {
         local cost_str_exists = 0
    }
    Does anyone know of a command that does this more efficiently? Thanks!

  • #2
    One possibility:
    Code:
    assert (strpos(x, "COST") == 0)
    local cost_str_exists = (_rc == 9)

    Comment


    • #3
      Another way to do it:

      Code:
      count if strpos(x, "COST") 
      local cost_str_exists = r(N) > 0

      Comment


      • #4
        Nick's approach is much preferable. -assert- is an obscure (though workable) choice that popped into my head for no good reason.

        Comment

        Working...
        X