Dear Statalist.
I have panel data of individuals in projects. I am trying to generate a variable that for each individual_id and project_id counts the number of other individual_id that are of the same type as the focal individual_id and in addition has a characteristic x. For instance, for a focal individual_id with type_a = 1, how many other individual_id are there in the same project_id that are also type_a = 1 but also has x = 1? It is not required that the focal individual_id has x = 1. This count value is then recorded for focal individual_id and project_id in question in the variable similar_coll. The same logic applies to individual_id and type_b.
Here is a small toy dataset that shows the structure of the data and the wanted count variable similar_coll.
The code suggested to me so far generates only 0 values. Here is the suggested (wrong) code:
Any help with this code would be greatly appreciated.
Thanks!
I have panel data of individuals in projects. I am trying to generate a variable that for each individual_id and project_id counts the number of other individual_id that are of the same type as the focal individual_id and in addition has a characteristic x. For instance, for a focal individual_id with type_a = 1, how many other individual_id are there in the same project_id that are also type_a = 1 but also has x = 1? It is not required that the focal individual_id has x = 1. This count value is then recorded for focal individual_id and project_id in question in the variable similar_coll. The same logic applies to individual_id and type_b.
Here is a small toy dataset that shows the structure of the data and the wanted count variable similar_coll.
Code:
* Example generated by -dataex-. For more info, type help dataex clear input byte(individual_id project_id type_a type_b x similar_coll) 1 1 1 0 1 0 2 1 0 1 0 1 3 1 0 1 1 0 4 2 1 0 0 0 5 2 1 0 0 0 3 2 0 1 0 0 1 3 0 1 1 0 2 3 1 0 0 1 9 3 1 0 1 0 10 3 1 0 0 1 11 4 0 1 0 0 12 4 0 1 0 0 2 4 1 0 1 1 9 4 1 0 1 1 10 4 1 0 0 2 end
The code suggested to me so far generates only 0 values. Here is the suggested (wrong) code:
Code:
sort project_id individual_id
gen similar_coll = 0
* Count for type_a
bysort project_id (individual_id): replace similar_coll = ///
sum((type_a == type_a[_n] & x == 1) * (individual_id != individual_id[_n])) ///
if type_a == 1
* Count for type_b
bysort project_id (individual_id): replace similar_coll = ///
sum((type_b == type_b[_n] & x == 1) * (individual_id != individual_id[_n])) ///
if type_b == 1
* Clean similar_coll to ensure it only contains relevant counts
bysort project_id individual_id: replace similar_coll = similar_coll - 1 if similar_coll > 0
Any help with this code would be greatly appreciated.
Thanks!

Comment