Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: SV: SV: st: value labels, rename and merge


From   Maarten buis <[email protected]>
To   [email protected]
Subject   Re: SV: SV: st: value labels, rename and merge
Date   Tue, 13 Apr 2010 15:24:26 +0000 (GMT)

--- On Tue, 13/4/10, Tomas Lind wrote:
> The variable names are not just: 
> Q1, Q2, Q3 ... . 
> 
> They are:
> id, est, dat, Q1, Q2, Q3 ... . 
> 
> I do not simply want to change to:
>  w_Q1, w_Q2, w_Q3 ... . 
> 
> I want to get rid of "Q" in the names and change the names
> to:
> id, est, dat, q12p1, q12p2, q12p3 ... .
> 
> To change your code to add q12 instead of w_ is straight
> forward, but to get rid of Q and get the loop running is
> more than I can achieve. 

So we want to creat a loop that will run over the variable
names Q1, Q2, etc., but does not include the variables id,
est, dat. One way to do that is as follows:

forvalues var in varlist Q* {

}

This loop will run over all variables whose name starts with
Q.

Inside the loop these variable names will be stored in the
local `var'. You want to replace the character Q with the 
character p. You can do that with the -subinstr- extended
macro function (-help extended_fcn-):

local Qtop : subinstr local var "Q" "p"

This creates the local macro `Qtop' which is a copy of `var'
except that the first occurance of the chacter Q is replaced
with the character p.

So putting this together:

*-------------- begin example -------------
// create some silly example data
clear
input id est  dat  Q1  Q2  Q3
      1  1    1    1    1  1
      2  2    2    2    2  2
end
label define Q1 1 "foo" 2 "bar"
label values Q1 Q1

// the loop of interest
foreach var of varlist Q* {
	local Qtop : subinstr local var "Q" "p"
	rename `var' w_`Qtop'
	local lab : value label w_`Qtop'
	if "`lab'" != "" {
		label copy `lab' w_`Qtop'
		label drop `lab'
		label values w_`Qtop' w_`Qtop' 
	}
}
desc
*---------------- end example ------------------
(For more on examples I sent to the Statalist see: 
http://www.maartenbuis.nl/example_faq )

Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany

http://www.maartenbuis.nl
--------------------------


      

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index