R/generate_pe.R

Defines functions generate_pe

Documented in generate_pe

#' Generate event times from a piecewise exponential distribution.
#'
#' Generates random event times under a piecewise exponential distribution, where different constant hazard rates apply before and after a specified separation timepoint. This is commonly used for simulating survival data with delayed treatment effects.
#' @importFrom stats pbeta rexp runif
#' @param n Integer. Number of event times  to generate (i.e., sample size).
#' @param t Numeric. Separation timepoint at which the hazard rate changes.
#' @param lambda1 Numeric. Constant hazard rate before the separation timepoint.
#' @param lambda2 Numeric. Constant hazard rate after the separation timepoint.
#' @return A numeric vector of length \code{n}, representing simulated survival times
#'   drawn from a piecewise exponential distribution with hazard rate \code{lambda1}
#'   before time \code{t}, and \code{lambda2} after time \code{t}.
#'   Times are expressed in the same time unit as specified in the hazard rate (typically months)
#' @examples
#' set.seed(42)
#' generate_pe(1000, 1, 1, 0.5)
#' @export
generate_pe <- function(n, t, lambda1, lambda2) {
  random_numbers <- numeric(n)

  for (i in 1:n) {
    u <- runif(1) # Generate a uniform random number

    # Probability of the event happening before time t
    p_before_t <- 1 - exp(-lambda1 * t)
    if (u < p_before_t) {
      # Event occurs before t
      random_numbers[i] <- -log(1 - u) / lambda1
    } else {
      # Event occurs after t
      # Generate time after t based on remaining probability
      random_numbers[i] <- t - (log(1 - u)+lambda1 * t)/lambda2
    }
  }

  return(random_numbers)
}

Try the DTEBOP2 package in your browser

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

DTEBOP2 documentation built on June 8, 2025, 1:24 p.m.