Hi everyone,
I have a variable with many negative observations that I need to make positive.
Here's an example:
When a negative value is found, I need to get a positive average of the negative observation and the smallest number of previous observations.
For instance, -32 is negative; (-32+20) is still negative; (-32+20+10) is still negative; (-32+20+10+10) is positive. So, I would like to replace these observations (-32; 20; 10; 10) by their average (2; 2; 2; 2).
Moreover, I cannot get decimal values: when the average is not an integer, the last observation of the series needs to be adjusted accordingly.
For instance, (-12+6+10) is positive and the sum is 4, to be divided by 3; therefore, I would like to get a series of 1, 1 and 2 (whose sum is still 4) in such a case.
The code I thought about looks like this:
It works, but only when the sum of the negative observation and the previous one is positive; otherwise, I get two negative values replacing the original ones, making the situation worse.
I may need to create a loop but I did not succeed yet.
I am getting crazy over this issue.
Many thanks for your precious help!
Demetrio
I have a variable with many negative observations that I need to make positive.
Here's an example:
Var | NeededVar |
40 | 40 |
10 | 2 |
10 | 2 |
20 | 2 |
-32 | 2 |
20 | 20 |
15 | 15 |
10 | 1 |
6 | 1 |
-12 | 2 |
10 | 10 |
When a negative value is found, I need to get a positive average of the negative observation and the smallest number of previous observations.
For instance, -32 is negative; (-32+20) is still negative; (-32+20+10) is still negative; (-32+20+10+10) is positive. So, I would like to replace these observations (-32; 20; 10; 10) by their average (2; 2; 2; 2).
Moreover, I cannot get decimal values: when the average is not an integer, the last observation of the series needs to be adjusted accordingly.
For instance, (-12+6+10) is positive and the sum is 4, to be divided by 3; therefore, I would like to get a series of 1, 1 and 2 (whose sum is still 4) in such a case.
The code I thought about looks like this:
Code:
gen Var2 = Var replace Var2=Var if Var2[_n+1]<0 replace Var=int((Var[_n]+Var[_n+1])/2) if Var2[_n+1]<0 replace Var=(Var2[_n]+Var2[_n-1])-Var[_n-1] if Var2[_n]<0
I may need to create a loop but I did not succeed yet.
I am getting crazy over this issue.
Many thanks for your precious help!
Demetrio
Comment