Statalist The Stata Listserver


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

Re: st: RE: creating different varibles in a loop depending on thevalues of x


From   n j cox <[email protected]>
To   [email protected]
Subject   Re: st: RE: creating different varibles in a loop depending on thevalues of x
Date   Tue, 24 Apr 2007 22:13:00 +0100

An alternative:

gen absx = abs(x)
sort group, stable
by group : gen id = cond(x < 0,_n, 0)
separate absx if id, by(id)
drop absx

Nick
[email protected]

Scott Merryman

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

sara borelli

> 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