Statalist


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

st: data management - changing every 1st encountered of a str data content of a var


From   Roy Wada <[email protected]>
To   <[email protected]>
Subject   st: data management - changing every 1st encountered of a str data content of a var
Date   Tue, 6 Jan 2009 03:21:18 -0800

 
i have a var like this: 
 
monopolar
nodiathrm
diathermy[2]
diathermy[2]

what i want to achieve is for every first encountered diathermy[2] 
to be changed to diathermy[1], while leaving the second occurence 
as diathermy[2].
 
*********************
 
If this is your exact question, then it can be done this way:
 
replace myvar="diathermy[1]" if myvar==`"diathermy[2]"' & myvar[_n+1]==`"diathermy[2]"'
 
For a more generic question, any string content of the form "string[num]" can 
be made to change the num of the first instance to num-1. This is a recycled 
code from anther program.
 
If you have triplicates (or more), i.e. diathermy[2] three times, then run the 
whole thing that many times and the number shoud be consequtively less in the 
reverse order.

 
forval num=1/`=_N' {
 * clear locals
 local temp1=.
 local count1=""
 local temp2=.
 local count2=""
 
 local first=myvar[`num']
 local open=index("`first'","[")
 local close=index("`first'","]")
 if `open'~=0 & `close'~=0 {
  local count1=trim(substr("`first'",`open'+1,`close'-`open'-1))
  local temp1=trim(substr("`first'",1,`open'-1))
 }
 
 local second=myvar[`num'+1]
 local open=index("`second'","[")
 local close=index("`second'","]")
 if `open'~=0 & `close'~=0 {
  local count2=trim(substr("`second'",`open'+1,`close'-`open'-1))
  local temp2=trim(substr("`second'",1,`open'-1))
 }
 di "`num' : `first' `second' `count1' `count2'"
 capture confirm number `count1'
 if _rc==0 {
  capture confirm number `count2 '
  if _rc==0 {
   replace myvar=`"`temp1'[`=`count1'-1']"' if "`temp1'"=="`temp2'" & `count1'==`count2' in `num'
  }
 }
}
 
 
_________________________________________________________________
Life on your PC is safer, easier, and more enjoyable with Windows Vista®. 
http://clk.atdmt.com/MRT/go/127032870/direct/01/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   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