Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

RE: st: Replace one variable when other variable contains certain characters


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   RE: st: Replace one variable when other variable contains certain characters
Date   Mon, 19 Dec 2005 10:52:51 -0000

If the names are as in `c(Mons)', you 
could go 

tokenize "`c(Mons)'" 

forval i = 1/12 { 
	replace x = m`i' if index(Y, "``i''")
} 

Nick 
[email protected] 

Joseph Coveney

> FUKUGAWA Nobuya wrote:
> 
> Suppose we have string variable Y, and we would like to replace
> variable X when variable Y contains certain characters such as
> "Dec".
> In other words, we want to write;
> replace X="m12" if Y (contains "Dec")
> replace X="m11" if Y (contains "Nov")
> replace X="m10" if Y (contains "Oct") .
> How can I write the latter part of command?
> Please note Y can be Dec123abc, 456Novpqr, and zzz789Oct.
> 
\> --------------------------------------------------------------
> ------------------
> 
> Rafal Raciborski responded with an answer that uses Stata's 
> new regular
> expression functions.  If you have an earlier release, then:
> 
> replace X = "m12" if index(Y, "Dec")
> replace X = "m11" if index(Y, "Nov")
> replace X = "m10" if index(Y, "Oct")
> 
> Note that in Stata 9, you can use -strpos()- instead of -index()-:
> 
> replace X = "m12" if strpos(Y, "Dec")
> replace X = "m11" if strpos(Y, "Nov")
> replace X = "m10" if strpos(Y, "Oct")
> 
> You can get cute, too, if you want to:
> 
> foreach month in `c(Mons)' {
>     replace X = "m" + ///
>       string(month(date("2000-`month'-01", "ymd")), "%02.0f") ///
>       if strpos(Y, "`month")
> }
> 
> This last snippet helps avoid tedium if you need to replace X 
> for all twelve 
> months, but would be overkill for just three.
 

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



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index