Announcement

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

  • How can I apply value labels (stored in different dataset) into my primary data?

    I am using Stata for Windows Version 13.1. I have a dataset with 300 variables and approximately 10,000 observations. The value labels were initially entered into a Microsoft excel workbook. I have imported this to Stata and named it “Value_ Labels.dta”. I’d like to have a code that will extract the value labels from “Value_ Labels” and apply it to my primary dataset. I have tried to find solutions (via internet) but didn’t succeed. I welcome solutions to this since. I have attached a sample of the primary data (dummy) and a section of the “Value_Labels” herewith. I am mindful of folks who are not using Microsoft Office in the forum, however I have tried to load the Stata dta files but I was getting an error message "This is not a valid image file. Primary_data.dta".

    Thanks in advance!
    Attached Files

  • #2
    Code:
    // store the data on my computer
    // you can use the files as they are on your computer
    // instead of the temporary files
    
    clear
    tempfile prim lab dolabs
    import excel "C:\Temp\Primary_data.xlsx", sheet("Sheet1") firstrow
    save `prim'
    
    clear
    import excel "C:\temp\Value_labels.xlsx", sheet("Sheet1") firstrow
    save `lab'
    
    // start collecting the labels
    use `lab'
    forvalues i = 1/`=_N' {
        if `"`=Variable_name[`i']'"' == `"`=Variable_name[`i'-1]'"'    {
            label define `=Variable_name[`i']' `=Value[`i']' `"`=Label[`i']'"', add
        }
        else {
            label define `=Variable_name[`i']' `=Value[`i']' `"`=Label[`i']'"'
            local labeledvars `"`labeledvars' `=Variable_name[`i']'"'
        }
    }
    
    // store them in a temporary do-file
    label save using `dolabs'
    
    // open the primary data
    use `prim'
    
    // get the value labels
    run `dolabs'
    
    // assign them to the variables
    foreach var of local labeledvars {
        label value `var' `var'
    }
    
    // admire the result
    desc
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Indeed I admired the results. It worked amazingly well. Many thanks Maarten.

      Comment

      Working...
      X