The -replace x=sum(x)- command you discuss is perhaps easiest to think
about in steps, with a column for each step, though this is not what
the C code that actually does -replace- is doing, I suspect:
obs x step1 step2
1 1 1 1
2 . 0 1
3 . 0 1
4 1 1 2
5 . 0 2
6 . 0 2
7 1 1 3
8 . 0 3
but if you think about -replace x=exp- being equivalent to -gen
step2=exp- followed by -replace x=step2- I think the logic is
inescapable. And the fact that the sum() function treats missing
values as adding zero to the running sum explains the presence of the
step1 column above, since you could also write 5 lines of code to
replace x=sum(x):
. gen step1=x
. replace step1=0 if mi(step1)
. gen step2=sum(step1)
. replace x=step2
. drop step1 step2
where of course the first two could be made one command via the cond()
function, but that would defeat the purpose ot being as verbose as
possible.
On 3/23/06, Jitian Sheu <jtsheu@mail.cgu.edu.tw> wrote:
> I know that the math function, sum( ), provides the running sum of a given
> variable, and I know that Stata treat missing as value of "0"
> My question is following:
>
> Because Stata is doing thing observation by observation(according to manual
> ), when I am typing –replace something-
> è Stata "should" do it observation by observation,
>
> Therefore, when using –replace x=sum(x)
> è the first observation of x would be summation of all x's observation from
> 1st obs up to the current observation, in this caseè1
> The logic to obtain the second observation of x is the same,
> è new x[2]=old x[1]+old x[2]=1+0=1è we obtain the 2nd observation of x=1
>
> When calculating x[3], the above new x[2] become a old one
> Hence, by the same logic, new x[3]=old x[1]+old x[2]+old x[3]
> Here, old x[1]=1, old x[3]=. (è missing=0 here)
> However, old x[2] should be 1 instead of a missing value, right?
> Therefore, I should have a new value of x[3]=1+1+)=2 instead of 1, right?
> Can anyone tell me anything wrong here?
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/