Statalist


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

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


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: data management - changing every 1st encountered of a str data content of a var
Date   Tue, 6 Jan 2009 22:18:38 -0000

Roy is here cross-referencing to other work of his on related problems.
Naturally I can't see his full program or its context but what I see
does not convince that either looping over observations or repeated
application of any program is required, as his code exemplifies and his
advice would imply. 

Roy too appears to be dealing with spell problems which in my experience
typically yield to -by:- alone. 

Nick 
[email protected] 

Roy Wada

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'
  }
 }
}
 
 

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