Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: use of subinstr


From   Eric Booth <[email protected]>
To   [email protected]
Subject   Re: st: use of subinstr
Date   Fri, 23 Mar 2012 08:31:56 -0500

<>

On Mar 23, 2012, at 4:44 AM, Nick Cox wrote:
> 1. As I should have remembered, -subinstr- can bite you. It never
> promises to act on "words", meaning here variable names. Consider
> 
> . local stuff "aaa aa a"
> 
> . tokenize "`stuff'"
> 
> . forval i = 1/3 {
>  2. local show : subinstr local stuff "``i''" ""
>  3. di "`show'"
>  4. }
> aa a
> a aa a
> aa aa a
> 
> Here, when asked to zap "aaa", it finds it and deletes it. When asked
> to zap "aa" it zaps it as part of "aaa", and similarly with "a" as
> part of "aaa". With real variable names, this might bite as an error,
> or you might get garbage.


Here's another way I've done it in the past (but this is sloppier than the method(s) Nick suggests):
Since variable names don't have spaces, you could change the extended_fcn -subinstr- from 

>  local show : subinstr local stuff "`i'" ""

to 

>  local show : subinstr local stuff "`i' " ""


where a space is added after the thing you are substituting 'from' so that you are getting full words substituted.  
To do so, you'd need to add an extra space to the end of the macro or the command above would miss the last var in your macro (which could cause other issues if you use this macro elsewhere).  An illustration:


**********
clear
set obs 1
foreach x in a aa aaa aaaa {
	g `x' = 1
	}
	

**the last run is wrong
 ds
 loc stuff `r(varlist)'
 foreach i in `stuff' {
  local show : subinstr local stuff "`i' " ""  //note the space trailing `i'
  di "`show'"
  }
  
 **corrected:
 ds
 loc stuff `r(varlist)'
   loc stuff `"`stuff' "' //added
 foreach i in `stuff' {
  local show : subinstr local stuff "`i' " "" //note the space trailing `i'
  di "`show'"
  }
****************


- Eric


__
Eric A. Booth
Public Policy Research Institute 
Texas A&M University
[email protected]
+979.845.6754


*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index