Store values from a variable and reuse them

跟風遠走 提交于 2019-12-25 04:36:18

问题


This is a question that could help me to solve another, still unsolved question I posted. Basically I need to condition a dataset in Stata and I thought a procedure which would need to first store certain values of a variable in a sort of matrix and then use compare the values of another variable with those stored in the matrix. A simple example could be the following:

obs id act1 act2  year act1year
  1   1   0    1   2000    0
  2   1   1    0   2001   2001
  3   1   0    1   2004    0  
  4   2   1    0   2001   2001
  5   2   1    0   2002   2002
  6   2   0    1   2004    0

The code should be able to save in the matrix by(id) the value of act1year different from 0 (in this case 2001) for group 1 and then check if this value, for observations for which act2 is 1, is included in the range for obs i=1,3 [year(i) : year(i)-2] in this case the range does not contain the value stored in the matrix; therefore the observation will be dropped. For group id 2 the code should store [2001, 2002] and then check if the range [year(6):year(6)-2] contains any of the values stored in the matrix.

I hope my question is clear enough! Apologies for not posting any attempt but this is something I really have no idea about how to do.


回答1:


Both this question and the previous discussion are difficult for me to understand, so let me suggest the following as a starting point to a solution that identifies observations for which either (a) act1 occurs or (b) act2 occurs no more than 2 years after the most recent act1 occurrence.

clear
input id act1 act2  year
  1   0    1   2000
  1   1    0   2001
  1   0    1   2004
  2   1    0   2001
  2   1    0   2002
  2   0    1   2004
end
generate a1yr = 0
replace  a1yr = year if act1==1
generate act1r = -act1
bysort id (year act1r): replace a1yr=a1yr[_n-1] if a1yr==0 & _n>1
generate tokeep = 0
replace  tokeep = 1 if act1==1
replace  tokeep = 1 if act2==1 & year-a1yr<=2
list, clean noobs

Looking at the previous discussion, as it now stands, suggests substituting the following data into the code above and seeing if the code then meets the needs of that discussion.

input obsno id act1 act2  year
  1  1  1 0 2000
  2  1  0 1 2001
  3  1  0 1 2002
  4  1  0 1 2002
  5  1  0 1 2003
  6  2  1 0 2000
  7  2  1 0 2001
  8  2  0 1 2002
  9  2  0 1 2002
 10  2  0 1 2003
end


来源:https://stackoverflow.com/questions/31449536/store-values-from-a-variable-and-reuse-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!