I realized I missed putting the 1 and 0 in quotes and resent an email
correcting my code. When I realized I also missed the use of "in"
rather than "of" I again resent my code with the necessary corrections.
Sorry for all the emails.
Justin White
-----Original Message-----
From: owner-statalist@hsphsun2.harvard.edu
[mailto:owner-statalist@hsphsun2.harvard.edu] On Behalf Of Nick Cox
Sent: Friday, October 27, 2006 10:29 AM
To: statalist@hsphsun2.harvard.edu
Subject: st: RE: RE: foreach
The first problem here with Marilyn's code
is that the keyword "in" is not what she needs.
"in" is legal here but what follows will not
be interpreted as she wants. The first time around
the loop, the word "varlist" is taken literally
and Stata looks for a variable called -varlist-,
which she evidently does not have.
If Marilyn (and Justin) look again at the help for
-foreach-, they will see that "of" is needed here.
The second problem, again with Marilyn's original
and Justin's suggestion, is that there is a boundary
between numeric and string variables that cannot
be crossed as casually as you wish. This issue
also arose in my reply to someone else about a day ago.
qui foreach x of varlist p03a01 p03a01a-p03a01m {
replace `x' = "1" if `x' == "si"
replace `x' = "0" if `x' == "no"
capture destring `x', replace
}
would seem one possibility. The use of -encode- is
another, probably better.
Nick
n.j.cox@durham.ac.uk
White, Justin
> This sounds to me that Stata is having a hard time recognizing your
> varlist.
>
> Try listing each variable rather than using < p03a01a-p03a01m >.
>
> Also, why generate y?
>
> Why would you not use this:
>
> foreach x in varlist ......... {
> replace `x' = 1 if `x'=="si"
> replace `x' = 0 if `x'=="no"
> }
Ms. Marilyn Ibarra
> I have data that is coded as "si" or "no". I need to change this to
> numeric variables. I tried the following but keep getting an error
> message that says, "varlist not found". Can anyone tell me what I am
> doing wrong?
>
> Here is the code:
>
> foreach x in varlist p03a01 p03a01a-p03a01m {
> gen y = (`x' == "si")
> replace y = 0 if (`x' =="no")
> drop `x'
> rename y `x'
> }
>
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/