Statalist The Stata Listserver


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

st: RE: creating different varibles in a loop depending on the values of x


From   "Scott Merryman" <[email protected]>
To   <[email protected]>
Subject   st: RE: creating different varibles in a loop depending on the values of x
Date   Thu, 12 Apr 2007 20:26:22 -0500

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/



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