R/data_generator.R

Defines functions data_generator

Documented in data_generator

#' Data Generator
#'
#'
#'@description Created by Vincent Runge. Generating data with a given model = changepoint relative positions + parameters + type of cost
#'
#' @param n number of data points to generate
#' @param chpts vector of position of the changepoints in (0,n] (last element is always n).
#' @param means vector of means of the data
#' @param sd a positive number = the standard deviation of the data
#' @param type a string defining the cost model to use: "mean", "variance", "gauss", "poisson"
#'
#' @return a vector of size n generated by the chosen model
#' @export
#'
#' @examples
#' data_generator(100)
#' data_generator(20, chpts = c(10), means = c(0,10), type = "gauss")
#' data_generator(25, chpts = c(10,20), means = c(2,0,1), type = "gauss")
data_generator <- function(n, chpts = NULL, means = 0, sd = 1, type = "gauss")
{
  #---stop---#
  if(!is.null(chpts))
  {
    if (max(chpts) >= n){stop('change-point(s) greater than or equal to n')}
    if(!is.numeric(chpts)){stop('change-points are not all numeric')}
  }

  if(is.unsorted(chpts)){stop('change-points should be an increasing vector')}
  if(!is.numeric(means)){stop('means are not all numeric')}
  if((length(chpts) + 1) != length(means)){stop('change-points and means vectors are not compatible')}
  if(!is.double(sd)){stop('sd is not a double')}
  if(sd < 0){stop('sd must be non-negative')}

  allowed.types <- c("gauss", "poisson")
  if(!type %in% allowed.types){stop('type must be one of: ', paste(allowed.types, collapse=", "))}

  segmentLength <- diff(c(0,chpts,n))
  if(type == "gauss"){data <- rep(means, segmentLength) + rnorm(n, sd = sd)}
  if(type == "poisson"){data <- rpois(lambda = rep(means, segmentLength), n = n)}

  return(data)
}
Qrtsaad/CHANGEPOINT documentation built on Dec. 18, 2021, 8:42 a.m.