R/ca_to_ps_matrix.R

Defines functions ca_to_ps_matrix

Documented in ca_to_ps_matrix

#' CADF to purchase string 

#' Extracts purchase strings from the CADF and formats as a R matrix.
#' @details 
#' Output is a matrix.  Rows are number of customers; columns = maxT

#' @export ca_to_ps_matrix
#' @param ca.data Data in the CADF format generated by the CADF _to_CADF functions and Customer class.
#' @param maxT Number of columns in the matrix
#' @return Matrix with dimensions C x maxT  (number of customers by maxT)


#' library(CADF)
#' data("transactions")
#' customer <- subset(transactions, transactions$ID == 40)
#' today.study.cutoff <- max(customer$PURCHASE_DATE)
#' customer.40.CADF <- list(Customer$new(customer, today.study.cutoff))
#' psmatrix <- customer.40.CADF$purchase_string_as_matrix
#' psmatrix2 <- ca_to_ps_matrix(customer.40.CADF, 15)


ca_to_ps_matrix <- function(ca.data, maxT) {
  
  x <- ca.data
  
  extract.ps <- lapply(x, function(x) x$purchase_string)
  extract.ps <- unlist(extract.ps)
  
  extract.ps <- extract.ps[!is.na(extract.ps)]
  extract.ps <- extract.ps[extract.ps != 1]
  
  rows <- length(extract.ps)
  columns <- maxT
  
  m <- matrix(nrow = rows, ncol = columns)
  
  for(i in 1:length(extract.ps)) {
    ps <- extract.ps[[i]]
    ps <- substr(ps, 1, maxT)
    ps <- as.numeric(strsplit(ps, split='')[[1]])
    m[i, 1:length(ps)] <- ps
  }
  
  m[is.na(m)] <- 0
  return (m)
  
  
}

Try the CADF package in your browser

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

CADF documentation built on Oct. 31, 2024, 5:08 p.m.