R/xsect.R

Defines functions xsect

Documented in xsect

#' Make a cross-section of multi-state data at a given time point
#' 
#' Given a dataset in long format, for instance generated by
#' \code{\link{msprep}}, this function takes a cross-section at a given time
#' point, to list the subjects under observation (at risk) at that time point
#' and the states currently occupied.
#' 
#' It is possible that subjects have moved to one of the absorbing states prior
#' to \code{xtime}; this is NOT taken into account. The function \code{xsect}
#' only concerns subjects currently (at \code{time}) at risk.
#' 
#' @param msdata An object of class \code{"msdata"}, such as output by
#' \code{\link{msprep}}
#' @param xtime The time point at which the intersection is to be made
#' @return A list containing \code{idstate}, a data frame containing
#' \code{id}'s and \code{state}, the number of the state currently occupied;
#' \code{atrisk}, the number at risk, and \code{prop}, a table counting how
#' many of those at risk occupy which state.
#' @author Hein Putter \email{H.Putter@@lumc.nl}
#' @keywords univar
#' @examples
#' 
#' tmat <- trans.illdeath(names=c("Tx","PR","RelDeath"))
#' data(ebmt3) # data from Section 4 of Putter, Fiocco & Geskus (2007)
#' msebmt <- msprep(time=c(NA,"prtime","rfstime"),status=c(NA,"prstat","rfsstat"),
#' 		data=ebmt3,trans=tmat)
#' # At the start everyone is in state 1 (default xtime=0 is used)
#' xsect(msebmt)
#' # At 5 years
#' xsect(msebmt, xtime=1826)
#' 
#' @export xsect
xsect <- function(msdata, xtime=0)
{
  msd <- msdata[msdata$Tstart<=xtime & msdata$Tstop>xtime,]
  msd <- msd[order(msd$id, msd$trans, msd$Tstart),]
  msd <- msd[!duplicated(msd$id),]
  idstate <- data.frame(id=msd$id, state=msd$from)
  tmat <- attr(msdata, "trans")
  K <- nrow(tmat)
  msd$from <- factor(msd$from, levels=1:K, labels=1:K)
  tbl <- table(msd$from)
  atrisk <- sum(tbl)
  prop <- tbl/atrisk
  res <- idstate
  attr(res, "atrisk") <- tbl
  attr(res, "prop") <- prop
  return(res)
}

Try the mstate package in your browser

Any scripts or data that you put into this service are public.

mstate documentation built on Sept. 11, 2024, 7:32 p.m.