looping with if (the importance of vector indices) to solve something that has plagued me for a while (shifting fill dates)

This week I toyed around with some code to shift fill dates for persistence analysis, and I think I’ve stumbled on a workable solution that involves an if loop and the use of vector indices.  It’s a synthesis of a few concepts that have been bouncing around in my head for quite some time.  The detritus setting into a more well-behaved gel thanks to some help from what I’ve managed to pick up from my ongoing exploration into the Matloff text I’m nibbling on.  The problem involves the shifting of the fill date for medication fills that overlap with the fill date + days supply of a previous fill (or fills).  This intermediate step is addressed in SAS code by Scott Leslie in this SUGI paper (http://www.wuss.org/proceedings11/Papers_Chu_L_74886.pdf).  The solution I’ve come up with is probably not as eloquent as it could be (as I’m sure there are some vectorization efficiencies to be had), but nonetheless, I offer it up here:

FD is the vector of fill dates

DS is the vector of days supplies

Also, you will note that for the funciton to work for an entire data.frame of subjects you have to use something like Hadley Wickhams’ plyr to execute the fuction by member in a transform ddply fashion.

shiftday <- function(FD,DS){
x <- rep(0, length(FD))
VA <- FD
VB <- DS
for (i in 1:length(VA))
 if (i == 1)    x[i] <- VA[i]
else {    if ((((x[i-1] + VB[i-1])) - VA[i]) <= 0)
 x[i] <- VA[i]
 if ((((x[i-1] + VB[i-1])) - VA[i]) > 0)
x[i] <- ((x[i-1] + VB[i-1])) - VA[i] +VA[i]   }

Unfortnately, the text formatting of WordPress are not friendly to displaying code (the missing indentations make the reading less-than-ideal), but you get the picture.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s