Bookmark and Share

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

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

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

From   "Tomas Lind" <>
To   <>
Subject   SV: SV: SV: st: value labels, rename and merge
Date   Wed, 14 Apr 2010 14:32:08 +0200

Thanks Maarten, and thanks Nick for your kind help with my renaming problem.

I've learnt a lot from the looping syntax. 



-----Ursprungligt meddelande-----
[] För Maarten buis
Skickat: den 13 april 2010 17:24
Ämne: Re: SV: SV: st: value labels, rename and merge

--- 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

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
input id est  dat  Q1  Q2  Q3
      1  1    1    1    1  1
      2  2    2    2    2  2
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' 
*---------------- end example ------------------
(For more on examples I sent to the Statalist see: )

Hope this helps,

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


*   For searches and help try:

*   For searches and help try:

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