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]

st: RE: destringing and replacing values for several variables

From   "Martin Weiss" <>
To   <>
Subject   st: RE: destringing and replacing values for several variables
Date   Wed, 21 Apr 2010 21:40:58 +0200

The first loop should start - foreach var of varlist `varlistfoo'-, the
second one passes "varname" to -replace-, but Stata needs to see `varname',
so it can substitute the members of the -local- for it.

You are, btw, replacing with strings, since you put the values in quotation
marks, and I am not sure this is your intention. -encode- may me be much
more useful here.


-----Original Message-----
[] On Behalf Of Ann Miller
Sent: Mittwoch, 21. April 2010 21:35
Subject: st: destringing and replacing values for several variables

Dear Statalist, 

I am new to macros and the foreach looping and am trying to simplify my
life. I have a list of 40 or so variables (ex: hf_stage1 through hf_stage40)
that all have the same string coded values; "Stage 1" "Stage 2" "Stage 3"
"Stage 4". I want to change these values to 1, 2, 3 and 4, with value labels
of "Stage 1" "Stage 2" "Stage 3" and "Stage 4". What I have done in the past

 replace hf_stage1="1" if hf_stage1=="Stage 1"
 replace hf_stage1="2" if hf_stage1=="Stage 2", etc., 
destring hf_stage1,replace
 and for each value generate a label.

 I then have to repeat this for every variable (hf_stage2 through
hf_stage40). It works, but is time consuming and I sometimes make mistakes.
I feel sure there's a way to do this with macros and foreach but there's
something I'm missing so far. 

Here's what I've tried:

local varlistfoo "hf_stage1 hf_stage2 hf_stage3"

. foreach var of `varlistfoo' {
  2. replace  var= "1" if  var=="Stage 1"
  3. replace  var= "2" if  var=="Stage 2"
  4. replace  var= "3" if  var=="Stage 3"
  5. }
invalid syntax

. foreach varname of varlist  hf_stage1 hf_stage2 hf_stage3{
  2. replace  varname= "1" if  varname=="Stage 1"
  3. replace  varname= "2" if  varname=="Stage 2"
  4. }
variable varname not found

I can't even get the first step, let alone destringing and replacing! Any
advice you all can offer would be greatly appreciated.Thank you!

*   For searches and help try:

*   For searches and help try:

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