Search code examples
foreachstata

Stata: using foreach to rename numeric variables


I have a large dataset where subsets of variables have been entered with the same prefix, followed by an underscore and some details. They are all binary YN and the variables are all doubles. For example, I have the variables onsite_healthclinic and onsite_CBO where values can only be 1 or 0.

I want to rename them all according to the question they are on the survey I'm working off of (so the above variables would become q0052_healthclinic and q0052_CBO), but if I use the code below using substr I (obviously) get type mismatch:

foreach var in onsite_healthclinic onsite_CBO {
        local new = substr(`var', 8, .)
        rename `new' q0052_`new'
    } 

My question is, is there another command other than substr that I can use so that I don't have to either a) convert all of the variables to strings first; or b) rename them all manually (there are ~20 in each subset, so while doable, it's a waste of time).


Solution

  • There is no need for a loop here at all. Although the essential answer is one line long I give here a complete, self-contained answer.

    clear 
    set obs 1 
    foreach v in onsite_healthclinic onsite_CBO { 
        gen `v' = 1 
    }
    
    rename onsite_*  q0052_* 
    
    describe, fullnames 
    

    This answer implies that you've not studied the help under rename groups.