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

# Re: st: Insert sum of column values by id as new observation

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: Insert sum of column values by id as new observation Date Thu, 23 Dec 2010 07:42:43 +0000

```Eric gave Mike what he asked, but for most purposes this data
structure is very awkward for Stata use, so for that you would need to
_exclude_ the additional observations from later calculations.

Getting an extra variable or a -reshape- to long might serve most
purposes better.

Nick Cox

Eric Booth
========

> Here's one approach:
>
> ***************!
>
> clear
> 1       10              10
> 1       20              10
> 2       10              20
> 2       10              20
> 2       20              10
> 3       10              20
> 4   99      100
> 4   80      80
> 4   50      50
> 4   1       2
> end
>
> bys id: g i = _n
> preserve
> sa "tot.dta", replace
> restore
>
> append using "tot.dta"
> sort id i
>
> recode i (.=.a)
> lab def total .a "TOTALS", modify
> lab val i total
> order i
>
> /*
> if you don't want the "totals"
> line when there is one obs
> */
>  drop if i==1 & i[_n+1]==.a
> ***************!

Mike Kim
=======

>> My data looks like the following and I would like to create sum of wk1ad
>> wk2ad... by id and insert as new observations.
>>
>> 1     10              10
>> 1     20              10
>> 2     10              20
>> 2     10              20
>> 2     20              10
>> 3     10              20
>> .....
>>
>> The resulting data I want to have is the following. How can I do this work
>> in Stata?
>>
>> 1     10              10
>> 1     20              10
>> 1     30              20   <- newly created obs
>> 2     10              20
>> 2     10              20
>> 2     20              10
>> 2     40              50   <- newly created obs
>> 3     10              20
>

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