Something like this?
clear
input group x
1 -5
1 -10
1 32
1 45
1 76
2 -9
2 24
2 32
end
egen neg = total(x<0), by(gro)
sum neg, meanonly
sort group
forv i = 1/`=r(max)' {
by group: gen ab`i' = abs(x) if x < 0 & _n == `i'
}
drop neg
l
Scott
> -----Original Message-----
> From: [email protected] [mailto:owner-
> [email protected]] On Behalf Of sara borelli
> Sent: Thursday, April 12, 2007 3:46 PM
> To: [email protected]
> Subject: st: creating different varibles in a loop depending on the values
> of x
>
> Dear Statalist members,
>
> I have the following question:
>
> group x
> 1 -5
> 1 -10
> 1 32
> 1 45
> 1 76
> 2 -9
> 2 24
> 2 32
>
> Whithin each group, I would like to create two
> variables that take the absolute value of x when x is
> negative, that is I would like to obtain:
>
> group x absx1 absx2
> 1 -5 5 .
> 1 -10 . 10
> 1 32 . .
> 1 45 . .
> 1 76 . .
> 2 -9 9 .
> 2 24 . .
> 2 32 . .
>
> I have manually typed:
> bysort group: gen absx=abs(x) if x <0 & _n==1;
> bysort group: gen absx=abs(x) if x <0 & _n==2;
>
> since the number of negatives varies depending on the
> situation, does anyone know how to write that in a
> loop, so that it cretaes automatically different absx
> depending on the numer of negatives present in the
> data?
*
* 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/