Bill TP
Bill TP

Reputation: 1097

Stata: renaming variables

I have many variables like:

slsoke slsoke_g jfue jfue_g iii iii_g bsueo bsueo_g ...

And also there are other variables that don't have the pair, such as hid, pid,...

I have to drop the variables that do not end with _g, and rename the "_g" variables to those without _g. So, for example, the values for "slsoke" should be obsolete, and the "slsoke" should be the exact copy of the "slsoke_g". How can I write a code to do the alterations in Stata?

Upvotes: 2

Views: 2063

Answers (2)

Nick Cox
Nick Cox

Reputation: 37183

The most difficult thing here is getting prefixes for all the variable names ending in _g. That could be done like this:

unab which : *_g 
local which : subinstr local which "_g " " ", all 

The details are crucial. You are looking for _g at the end of a name, hence the extra space, but you need to replace the space too. Now you can cycle over that set of prefixes:

foreach w of local which { 
     drop `w'_g 
     rename `w' `w'_g 
} 

(LATER EDIT) Perhaps you want something more like this.

foreach w of local which { 
    replace `w' = `w'_g 
    drop `w'_g 
    rename `w' `w'_g 
} 

Whatever you want, as said earlier, getting the prefixes seems the most difficult bit, and the rest is a loop over the prefixes.

Upvotes: 2

Fr.
Fr.

Reputation: 2885

You can probably write something like this:

// example

clear
set obs 50
gen hid = _n
gen pid = floor(_n/5)
local y = "slsoke jfue iii bsueo"
foreach x of local y {
    gen `x' = runiform()
    gen `x'_g = int(10 * `x')
}

// the code

local k ""

qui d, varl
local l = r(varlist)
foreach x of local l {
    cap qui replace `x' = `x'_g
    if !_rc local k = "`k' `x'"
}

di as err "`k'"
keep `k'

// bye

There might be a shorter solution with an intelligent regex.

Upvotes: 2

Related Questions