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

# Re: st: Generating new variables with values of difference in 2 variables

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: Generating new variables with values of difference in 2 variables Date Thu, 19 Apr 2012 08:57:23 +0100

```Sounds like

gen breakdate = .

qui forval k = 1/14 {
replace breakdate = `k' if B`k' > A`k' & missing(breakdate)
}

Nick

On Thu, Apr 19, 2012 at 3:12 AM, Hitesh Chandwani
<hchandwani.stata@gmail.com> wrote:

> This works great! Thanks Nick.
> This is not panel data; I'm using claims data to calculate compliance
> with medications for which I need each patient to have a single row of
> data (I converted the original long form to wide form data).
>
> I have another question though:
>
> I am interested in the first day that there was a break in medication
> possession. From the date variables (disp_date1-disp_date14 OR
> disp_date`k'), I need to pick out the first date of the break. In
> other words, I need to pick out the first date for each patient where
> variable A`k' > variable B`k'.
>
> I've been trying for hours but I can't get Stata to do exactly what I
> want. I tried -egen-, and some loops but to no avail.
>
> Does someone have any inputs?
>
> Hitesh
>
>
> On Wed, Apr 18, 2012 at 11:06 AM, Nick Cox <njcoxstata@gmail.com> wrote:
>> forval j = 1/7 {
>>     local J = `j' + 1
>>     gen var`j' = day`J' - day`j'
>> }
>>
>> or
>>
>> forval j = 1/7 {
>>    gen var`j' = day`=`j' + 1' - day`j'
>> }
>>
>> All that said, this sounds a very bad idea strategically. Presumably
>> -day1- is what happens on day 1, and so forth, so this is time series
>> or panel data. You start out with 8 day variables, then add 7
>> difference variables. When this is going to stop as you add further
>> analyses?
>>
>> Better to -reshape long-. Then you can work with one response
>> variable, one set of differences, etc.
>>
>> Nick
>>
>> On Wed, Apr 18, 2012 at 4:59 PM, Hitesh Chandwani
>> <hchandwani.stata@gmail.com> wrote:
>>
>>> This is another query about loops. I have 8 variables day1-day8. I am
>>> trying to run a loop that does:
>>>
>>> gen var1=day2-day1
>>> gen var2=day3-day2
>>> gen var3=day4-day3...and so on.
>>>
>>> From previous statlist emails, I found how to run loops subtracting
>>> one series of variables from another
>>> (http://www.stata.com/statalist/archive/2012-01/msg00303.html), but
>>> I'm having a hard time trying to generate a loop where variables
>>> within the same series are subtracted from each other.

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