Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Nick Cox <njcoxstata@gmail.com> |
To | statalist@hsphsun2.harvard.edu |
Subject | Re: st: RE: strpos: cleaning string variables |
Date | Tue, 22 Feb 2011 08:56:48 +0000 |
You are quite correct about -drop-ping those variables, so that's not a bug. I suggest something like foreach x of local xlist { replace `x' = trim(`x') replace `x' = subinstr(`x', ".", " ", .) replace `x' = subinstr(`x'. ",", " ", .) replace `x' = subinstr(`x', "&", "and", .) } -subinstr()- is a function, not a command. Nick On Mon, Feb 21, 2011 at 11:10 PM, Emily Farchy <emily.farchy@sant.ox.ac.uk> wrote: > Thanks a lot Nick, > > This looks like a really useful command. > > NB the loop dropped the generated vars at the end so it did run fine, but didn't accomplish what I needed, I'll try again with subinstr() command > > Emily > > On Feb 21, 2011, at 8:36 PM, Nick Cox wrote: > >> -strpos()- is a function, not a command. >> >> You can eliminate substrings of length 1 if you wish using -subinstr()-. As -subinstr()- can delete more than one occurrence at a time it is likely to be an answer to your question about the n th occurrence. >> >> Your loop is going to fail second time around if only because you are then trying to -generate- variables that already exist. Again, you don't need to loop over , . & as you can work on them using separate commands within the loop. >> >> Nick >> n.j.cox@durham.ac.uk >> >> Emily Farchy >> >> I would like to run a loop to transform some messy names into cleaner versions eg >> "Drs. H. Muslim Kasim, Ak"--> "Muslim Kasim" >> "Drs. Makmur Syahputra, Sh" -->"Makmur Syah Putra" >> "H Amru Helmy Daulay Sh" --> "Amru Helmy Daulay" >> >> I was thinking of using the strpos command which seems like it might be useful but is there a way to get it to find the nth occurrence (eg of a space) and a way to eliminate substrings of for example 3 letters or less? >> >> I was working on the following but get stuck when I pass the first occurence >> >> foreach x of local xlist { >> >> **** get rid of . , or & in name (A, B --> A B; st. A --> st A, A & B --> A and B) >> foreach z in , . & { >> qui gen `x'_bh= trim(substr(`x', 1, strpos(`x', "`z'")-1)) >> qui gen `x'_ah= trim(substr(`x', strpos (`x', "`z'")+1, 50)) >> qui gen `x'_mid= substr(`x', strpos (`x', "`z'"), 1) >> >> replace `x'=trim(`x'_bh+" "+`x'_ah) >> replace `x'=trim(`x'_bh+" and "+`x'_ah) if `x'_mid=="&" >> >> drop `x'_bh `x'_ah `x'_mid >> } >> } * * 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/