I have this data which has around 10,000 observations
id var1 var2 var3
1 P P 0
2 1 1 2
3 P 0 0
4 A P P
5 P 2 0
....
....
and so on
var1 var2 and var3 are string variables
I want to identify those individuals for whom there is a "0" after a "P" i.e. "P" and "0" are observed consecutively
lets say the name of new variable is p0
then the new variable will look like this:
id var1 var2 var3 p0
1 P P 0 1
2 1 1 2 0
3 P 0 0 1
4 A P P 0
5 P 2 0 0
you can see individuals 1 has a a p0 value 1 because "P" and "0" are observed consecutively in var2 and var3 similarly individual 3 has a p0 value 1 because var1 value is "P" and var2 value is "0" so "P" and "0" has come consecutively. However, individuals 5 has a p0 value 0 because "P" and "0" has not come consecutively, var1 is P var2 is "2" and var3 is "0"
to do this I have written this code:
but this code is not able to identify the individuals
I have tried this also:
this also not working
can anyone solve this problem
id var1 var2 var3
1 P P 0
2 1 1 2
3 P 0 0
4 A P P
5 P 2 0
....
....
and so on
var1 var2 and var3 are string variables
Code:
* Example generated by -dataex-. For more info, type help dataex clear input float id str1(var1 var2 var3) 1 "P" "P" "0" 2 "1" "1" "2" 3 "P" "0" "0" 4 "A" "P" "P" 5 "P" "2" "0" end
I want to identify those individuals for whom there is a "0" after a "P" i.e. "P" and "0" are observed consecutively
lets say the name of new variable is p0
then the new variable will look like this:
id var1 var2 var3 p0
1 P P 0 1
2 1 1 2 0
3 P 0 0 1
4 A P P 0
5 P 2 0 0
you can see individuals 1 has a a p0 value 1 because "P" and "0" are observed consecutively in var2 and var3 similarly individual 3 has a p0 value 1 because var1 value is "P" and var2 value is "0" so "P" and "0" has come consecutively. However, individuals 5 has a p0 value 0 because "P" and "0" has not come consecutively, var1 is P var2 is "2" and var3 is "0"
to do this I have written this code:
Code:
gen p0 = 0 forval i = 1/2 { if p0 == 0 { if var`i' == "P" & var`i+1' == "0" { replace p0 = 1 } } }
but this code is not able to identify the individuals
I have tried this also:
Code:
gen p0 = 0 forval i = 1/2 { replace p0 = 1 if var`i' == "P" & var`i+1' == "0" & p0 == 0 }
can anyone solve this problem
Comment