Announcement

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

  • Using value labels in an if condition

    Hi fellow Statalisters,

    I'm writing a code which is supposed to store variables from survey data in a local. Those variables have to fulfill two conditions: 1) some observation has to take on value "-8" and 2) the corresponding value label for this observation has to say - for example - "Stata".

    I can handle the -8 restriction but I'm not sure how to code the label restriction properly. I assume it would be best to use a command and a corresponding return code. Has anyone had a similar problem or an idea how to extend my code?

    Code:
    local filtered_nondc
    
    foreach var of varlist _all {
            cap count if `var' == -8                       // cap needed to avoid break for string variables
                if `r(N)' > 0 local filtered_nondc "`filtered_nondc' `var'"  
        }
    One way to do it might be using decode var, gen(var_dc) and then checking the return code of var_dc == "Stata". But that looks like it's not the easiest way of reaching my goal.

    Best,
    Christian

  • #2
    Use findname (Cox, SSC) to selct variables that have a value label with the word "Stata" and in which value -8 occurs. Then select from these variables, the ones for which value -8 is associated with label "Stata".

    Code:
    // find variables with
    // (i) value labels with the label "Stata"
    // (ii) and values -8
    findname ,vallabelt("Stata") any(@ == -8)
    loc varlist `r(varlist)'
    
    // now select from these variables
    // the ones where -8 has the label "Stata"
    loc myvars
    foreach var of loc varlist {
        if (`"`: lab (`var') -8'"' == "Stata") {
            loc myvars `myvars' `var'
        }
    }
    di "`myvars'"
    Best
    Daniel

    Comment


    • #3
      Presumably you want to store variable names in a local, not variables themselves. The first part, finding any variables with values of -8, yields to findname (SJ). The same command could also find any variables with value labels "Stata", but that is not quite what you want, so we can write a loop for the rest of the problem.

      Code:
       
      findname, any(@ == -8) local(myvars) 
      
      foreach v of local myvars { 
              local label :  label (`v') -8 
              if "`label'" == "Stata" local found `found' `v' 
      } 
      
      di "`found'"
      The write-up of findname at http://www.stata-journal.com/sjpdf.h...iclenum=dm0048 is a slow but steady exposition of some technique in this territory.

      Comment

      Working...
      X