Announcement

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

  • Ending of Label

    How can I write a code with meaning: keep if ending of variables' labels is 4 ?

    The idead behind this is that I want to keep the observations that are at Quarter 4 every year of the quarterly dataset.
    Last edited by Giang Dao; 07 Jun 2018, 03:19.

  • #2
    It's unclear if you want to keep a variable (col) if the label ends with 4 or keep an observation (row) if it's value label ends with 4, regardless here's something to get you started for both situations:


    Code:
    **make fake data - run this in a do-file**
    clear
    set obs 25
    g x = int(1+runiform()*4)
    g y = int(1+runiform()*4)
    tostring y, g(stringversion) 
    
    *varlabel
    lab var x "quarter 1"
    lab var y "quarter 4"
    
    *value label
    lab def q 1 "Q1" 2 "Q2" 3 "Q3" 4 "Q4"
    lab val x y q
    describe
    label list
    
    tab2 *
    
    
    **first drop observations of string variables ending 4:
    drop if substr(stringversion, -1, 1) == "4" //compares last character at position -1
    
    **now drop observations of labeled numeric vars with label ending in 4:
    ds ,  has(vallabel) //get labeled numeric vars
    foreach v in `r(varlist)' {
        decode `v', g(temp`v')
        drop if substr(temp`v', -1, 1)=="4"
        drop temp`v'
        }
        
    **finally drop variable (col) if label ends in 4:
    foreach v of varlist * {
    di `"`:var lab `v''"'
        if substr(`"`:var lab `v''"', -1, 1)=="4"  drop `v'
        }
        
        
        list



    Eric A. Booth | Senior Director of Research | Far Harbor | Austin TX

    Comment


    • #3
      Thank you very much for your help. It is dropping variables whose labels end with "Q1" "Q2" "Q3" that I want to do.

      It works now with the following code:

      Code:
      foreach x of varlist q* v* {
          if substr(`"`:var lab `x''"', -1, 1)!="4"  drop `x'
          }
      Last edited by Giang Dao; 09 Jun 2018, 01:47. Reason: no more problem

      Comment


      • #4
        As a small twist on Eric's helpful answer note that findname (Stata Journal), functionally a superset of ds, so with extra handles, can get the names of such variables in one step:

        Code:
        *make fake data - run this in a do-file**
        clear
        set obs 25
        g x = ceil(runiform()*4)
        g y = ceil(runiform()*4)
        
        *varlabel
        lab var x "quarter 1"
        lab var y "quarter 4"
        
        *value label
        lab def q 1 "Q1" 2 "Q2" 3 "Q3" 4 "Q4"
        lab val x y q
        
        findname, varlabeltext(*4) 
        y
        
        findname, vallabeltext(*4) 
        x  y

        Comment

        Working...
        X