Question

Suppose I have a right-continuous step (or staircase) function s which jumps at the time points contained in a variable t: e.g. s could be the Kaplan-Meier estimator of time-to-event data obtained by sts gen.

Now, suppose I am given another variable r also containing time points that are possibly different from those contained in t and that I want to create another variable p which is my step function evaluated at the time points in r.

 t  |  s   |  r
0.5 | 0.9  | 0.7  
1.2 | 0.85 | 0.8
1.5 | 0.8  | 1.25
1.5 | 0.8  | 1.3  

My data could look something like what is shown above, and in this situation we would have

 p 
0.9
0.9
0.85
0.85

or in other words for each value of r we find the largest t value that is smaller than or equal to r and put p equal to s.

My question is: how do I do this in an efficient way? Obviously, I can, for every r-value, do the following:

gen diff=(r-t) if(r>=t)
sort diff
sum s if(_n==1)

but this is not what I'm looking for since this is very time-consuming when the number of observations are large.

Was it helpful?

Solution

I suggest that you think of your problem slightly differently, namely that you have new values of t for which s is not known; your interpolation rule is to replace by the previous known value of s. The procedure in Stata terms is written up in this Stata FAQ.

. list, sep(0)

     +------------+
     |    t     s |
     |------------|
  1. |   .5    .9 |
  2. |  1.2   .85 |
  3. |  1.5    .8 |
  4. |  1.5    .8 |
  5. |   .7     . |
  6. |   .8     . |
  7. | 1.25     . |
  8. |  1.3     . |
     +------------+

 . sort t s

 . replace s = s[_n-1] if missing(s)
 (4 real changes made)

 . list, sep(0)

     +------------+
     |    t     s |
     |------------|
  1. |   .5    .9 |
  2. |   .7    .9 |
  3. |   .8    .9 |
  4. |  1.2   .85 |
  5. | 1.25   .85 |
  6. |  1.3   .85 |
  7. |  1.5    .8 |
  8. |  1.5    .8 |
     +------------+

Note: sorting on t then s allows known s values to be copied for the same t.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top