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.
Joseph Coveney
*
* 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/