I have a dataset of patient stays in hospital rooms. The data contains each patient's id, room location, and start and end datetimes for their stay in those rooms. I am trying to build a for loop to identify periods of time where two patients were in the same room at the same time. I have built a for loop that I was hoping would dynamically generate 3 new columns for a patient with roommates:
For now I am just using x = 1/3 to test out the loop on smaller groups of rows. Running this for loop generates r_start_datetime_1 and r_end_datetime_1, but they are just the start_ and end_datetimes of the previous rows. No r_ids are generated and I get an error that reads: "_n- invalid name". I assume this error comes from the _`x' syntax of naming the variables, but I'm not sure.
And here is a sample of the dataset
id location start_datetime end_datetime
42989001 106^0615 14jan2009 21:15:03 16jan2009 09:53:00
42935002 106^0615 04feb2009 17:49:31 09feb2009 10:02:53
43463003 106^0615 23jun2009 18:23:22 25jun2009 07:26:12
43941004 106^0615 13nov2009 16:23:00 18nov2009 11:21:59
44203005 106^0615 27mar2010 09:05:39 28mar2010 14:59:31
44486006 106^0615 26apr2010 18:08:21 27apr2010 14:58:19
44443007 106^0615 04may2010 18:21:26 06may2010 09:12:10
44569008 106^0615 25may2010 18:01:47 27may2010 09:32:38
44540009 106^0615 18jun2010 17:20:35 24jun2010 17:09:59
44462010 106^0615 29jun2010 19:19:43 01jul2010 14:29:12
Code:
sort location start_datetime end_datetime forvalues x = 1/3 { by location: gen double r_start_datetime_`x' = start_datetime[_n-`x'] if id != id[_n-`x'] by location: gen double r_end_datetime_`x' = end_datetime[_n-`x'] by location: gen long r_id_`x' = id[_n-`_x'] if start_datetime <= r_end_datetime_`x' & r_start_datetime_`x' >= start_datetime }
And here is a sample of the dataset
id location start_datetime end_datetime
42989001 106^0615 14jan2009 21:15:03 16jan2009 09:53:00
42935002 106^0615 04feb2009 17:49:31 09feb2009 10:02:53
43463003 106^0615 23jun2009 18:23:22 25jun2009 07:26:12
43941004 106^0615 13nov2009 16:23:00 18nov2009 11:21:59
44203005 106^0615 27mar2010 09:05:39 28mar2010 14:59:31
44486006 106^0615 26apr2010 18:08:21 27apr2010 14:58:19
44443007 106^0615 04may2010 18:21:26 06may2010 09:12:10
44569008 106^0615 25may2010 18:01:47 27may2010 09:32:38
44540009 106^0615 18jun2010 17:20:35 24jun2010 17:09:59
44462010 106^0615 29jun2010 19:19:43 01jul2010 14:29:12
Comment