## Loading and grooming data from the exampl file in Crowther & Lambert

library( foreign )
bc <- read.dta( "http://fmwww.bc.edu/repec/bocode/m/multistate_example.dta" )
names( bc )
head( bc )

## We will only record dates of relapse and metastasis where they
## actually occur; we use the os as the exit date relying on the
## factor osi as the death indicator; so we define the times of
## relapse (without metastasis), metastasis, exit and death ---
## counting the follow-up in years: 

bc <- transform( bc, tor = ifelse( rfi==0      , NA, rf )/12,
                     tom = ifelse( mfi=="no"   , NA, mf )/12,
                     tox = os/12,
                     tod = ifelse( osi=="alive", NA, os )/12,
                     xst = factor( osi, labels=c("Alive","Dead") ),
                  hormon = factor(hormon),
                   grade = factor(grade) )
## correct typo in level name
levels( bc$size )[2] <- ">20-50 mm"

## If metastatis at relapse, then metastasis,
## if death and metastasis at same time, metastatis 1 week before death

bc <- transform( bc, tor = ifelse( !is.na(tor) & !is.na(tom) & tor==tom, NA      , tor ),
                     tom = ifelse( !is.na(tom) & !is.na(tod) & tom==tod, tom-1/52, tom ),
                   pr.tr = pr_1 )

## Select relevant variables for inclusion in the package

bc <- bc[,c("pid","year","age","meno","size","grade","nodes","pr","pr.tr","er","hormon","chemo",
            "tor","tom","tod","tox","xst","rf","rfi","mf","mfi","os","osi")]

## Check

subset( bc, !is.na(tor) & !is.na(tom) & !is.na(tod) )[1:5,]
subset( bc, !is.na(tor) &  is.na(tom)               )[1:5,]
subset( bc,  is.na(tor) & !is.na(tom)               )[1:5,]
BrCa <- bc[,1:17]
head( BrCa )
save( BrCa, file="../data/BrCa.rda" )
