Statalist The Stata Listserver

[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Re: Seeking explanation of the internal procedures of -replace- [thanks]

From   Jesper Kjr Hansen <>
To   <>
Subject   st: Re: Seeking explanation of the internal procedures of -replace- [thanks]
Date   Fri, 25 May 2007 00:53:02 +0200


On 2007/05/24 Michael Blasnik wrote:
> Stata works sequentially through the variable in a replace, 
> which allows functions such as sum() to accumulate a 
> running sum and allows [_n-1] constructs 
> program define scramble
> version 9.2
> syntax [varlist]
> tempvar hold order rand
> gen long `order'=_n
> foreach var of local varlist {
>  gen `rand'=uniform()
>  gen `hold'=`var'
>  sort `rand'
>  replace `var'=`hold'[`order']
>  drop `rand' `hold'
>  }
> end

thank you for refreshing my memory with 
regard to -replace-

You are also right in saying that I don't 
need the -clonevar- construct - instead I
just use replace and a temp var (although, 
I still use _`var' in place of an actual 
temp var, because each run permutes one 
_or more_ variables).

To round things off I include a copy of 
my current ado file below, in compact form.

program define bfsimu, rclass
version 9.2
syntax ...

tempfile ORG bfPERM 
tempvar tag dtrank sortorder
marksample touse, strok    


qui drop if !`touse'
gen long `sortorder' = _n
keep `sortorder' `Varlist'
sort `sortorder'
qui save `ORG'

forval r = `nextrun'/`reps' {
    qui use `ORG'
    local oldseed "`seed'"
    foreach gr of local nVarlist {
        sort `gr'
        local concat_gr : subinstr local gr " " "+" , all
        mark `tag' if indexnot(`concat_gr',"?") != 0
        set seed `seed'
        qui egen long `dtrank' = rank(uniform()) if `tag' , unique
        qui foreach var of local gr {
            gen _`var' = `var'
            replace `var' = _`var'[`dtrank'] if  `tag'
            local droplist "`droplist' _`var'"

        drop `tag' `dtrank' `droplist'
        local droplist ""
        local seed = c(seed)
    sort `sortorder'
    qui save `bfPERM', replace
    bfsearch `Varlist' , maxvar(`maxvar') `Options'


-- Jesper Kjr Hansen

*   For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index