content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' @templateVar name_model_full GGompertz/NBD
#' @template template_class_clvmodelstaticcov
#'
#' @seealso Other clv model classes \linkS4class{clv.model}, \linkS4class{clv.model.ggomnbd.no.cov}
#' @seealso Classes using its instance: \linkS4class{clv.fitted.transactions.static.cov}
#'
#' @include all_generics.R class_clv_model_ggomnbd_nocov.R
setClass(Class = "clv.model.ggomnbd.static.cov", contains = "clv.model.ggomnbd.no.cov",
slots = list(start.param.cov = "numeric"),
prototype = list(
start.param.cov = numeric(0)
))
#' @importFrom methods new
clv.model.ggomnbd.static.cov <- function(){
return(new("clv.model.ggomnbd.static.cov",
clv.model.ggomnbd.no.cov(),
name.model = "GGompertz/NBD with Static Covariates",
start.param.cov = 0.1))
}
# Methods --------------------------------------------------------------------------------------------------------------------------------
# . clv.model.check.input.args ------------------------------------------------------------------------------------------------------------
# Use nocov
# . clv.model.put.estimation.input ------------------------------------------------------------------------------------------------------------
# Nothing specific required, use nocov
# . clv.model.transform.start.params.cov ------------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.transform.start.params.cov", signature = signature(clv.model="clv.model.ggomnbd.static.cov"), definition = function(clv.model, start.params.cov){
# no transformation needed
return(start.params.cov)
})
# . clv.model.backtransform.estimated.params.cov -----------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.backtransform.estimated.params.cov", signature = signature(clv.model="clv.model.ggomnbd.static.cov"), definition = function(clv.model, prefixed.params.cov){
# no transformation needed
return(prefixed.params.cov)
})
# . clv.model.process.newdata -----------------------------------------------------------------------------------------------------
# Use ggomnbd.no.cov methods, dont need to overwrite
# . clv.model.prepare.optimx.args -----------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.prepare.optimx.args", signature = signature(clv.model="clv.model.ggomnbd.static.cov"), definition = function(clv.model, clv.fitted, prepared.optimx.args){
# Do not call the no.cov function because the LL is different
# Everything to call the LL function
optimx.args <- modifyList(prepared.optimx.args,
list(LL.function.sum = ggomnbd_staticcov_LL_sum,
LL.function.ind = ggomnbd_staticcov_LL_ind, # if doing correlation
obj = clv.fitted,
vX = clv.fitted@cbs$x,
vT_x = clv.fitted@cbs$t.x,
vT_cal = clv.fitted@cbs$T.cal,
# Covariate data, as matrix!
mCov_life = clv.data.get.matrix.data.cov.life(clv.data = [email protected], correct.row.names=clv.fitted@cbs$Id,
correct.col.names=clv.data.get.names.cov.life([email protected])),
mCov_trans = clv.data.get.matrix.data.cov.trans(clv.data = [email protected], correct.row.names=clv.fitted@cbs$Id,
correct.col.names=clv.data.get.names.cov.trans([email protected])),
# parameter ordering for the callLL interlayer
LL.params.names.ordered = c(c(log.r = "log.r",log.alpha = "log.alpha", log.b = "log.b", log.s = "log.s", log.beta = "log.beta"),
[email protected],
[email protected])),
keep.null = TRUE)
return(optimx.args)
})
#' @include all_generics.R
#' @importFrom stats integrate
setMethod("clv.model.expectation", signature(clv.model="clv.model.ggomnbd.static.cov"), function(clv.model, clv.fitted, dt.expectation.seq, verbose){
r <- alpha_i <- beta_i <- b <- s <- t_i <- tau <- NULL
params_i <- clv.fitted@cbs[, c("Id", "T.cal", "date.first.actual.trans")]
m.cov.data.life <- clv.data.get.matrix.data.cov.life([email protected], correct.row.names=params_i$Id,
correct.col.names=names([email protected]))
m.cov.data.trans <- clv.data.get.matrix.data.cov.trans([email protected], correct.row.names=params_i$Id,
correct.col.names=names([email protected]))
params_i[, alpha_i := ggomnbd_staticcov_alpha_i(alpha_0 = [email protected][["alpha"]],
vCovParams_trans = [email protected],
mCov_trans = m.cov.data.trans)]
params_i[, beta_i := ggomnbd_staticcov_beta_i(beta_0 = [email protected][["beta"]],
vCovParams_life = [email protected],
mCov_life = m.cov.data.life)]
fct.expectation <- function(params_i.t){
return(drop(ggomnbd_staticcov_expectation(r = [email protected][["r"]],
b = [email protected][["b"]],
s = [email protected][["s"]],
vAlpha_i= params_i.t$alpha_i,
vBeta_i = params_i.t$beta_i,
vT_i = params_i.t$t_i)))
}
return(DoExpectation(dt.expectation.seq = dt.expectation.seq, params_i = params_i,
fct.expectation = fct.expectation, clv.time = [email protected]@clv.time))
})
# . clv.model.pmf --------------------------------------------------------------------------------------------------------
#' @include all_generics.R
setMethod("clv.model.pmf", signature=(clv.model="clv.model.ggomnbd.static.cov"), function(clv.model, clv.fitted, x){
stop("PMF is not available for ggomnbd!", call.=FALSE)
})
# . clv.model.predict --------------------------------------------------------------------------------------------------------
#' @include all_generics.R
setMethod("clv.model.predict", signature(clv.model="clv.model.ggomnbd.static.cov"), function(clv.model, clv.fitted, dt.predictions, verbose, continuous.discount.factor, ...){
r <- alpha <- beta <- b <- s <- x <- t.x <- T.cal <- CET <- PAlive <- i.CET <- i.PAlive <- period.length <- NULL
predict.number.of.periods <- dt.predictions[1, period.length]
# To ensure sorting, do everything in a single table
dt.result <- copy(clv.fitted@cbs[, c("Id", "x", "t.x", "T.cal")])
data.cov.mat.life <- clv.data.get.matrix.data.cov.life(clv.data = [email protected], correct.row.names=dt.result$Id,
correct.col.names=names([email protected]))
data.cov.mat.trans <- clv.data.get.matrix.data.cov.trans(clv.data = [email protected], correct.row.names=dt.result$Id,
correct.col.names=names([email protected]))
# Add CET
dt.result[, CET := ggomnbd_staticcov_CET(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
b = [email protected][["b"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
dPeriods = predict.number.of.periods,
vX = x,
vT_x = t.x,
vT_cal = T.cal,
vCovParams_trans = [email protected],
vCovParams_life = [email protected],
mCov_life = data.cov.mat.life,
mCov_trans = data.cov.mat.trans)]
# Add PAlive
dt.result[, PAlive := ggomnbd_staticcov_PAlive(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
b = [email protected][["b"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
vX = x,
vT_x = t.x,
vT_cal = T.cal,
vCovParams_trans = [email protected],
vCovParams_life = [email protected],
mCov_life = data.cov.mat.life,
mCov_trans = data.cov.mat.trans)]
# Add results to prediction table, by matching Id
dt.predictions[dt.result, CET := i.CET, on = "Id"]
dt.predictions[dt.result, PAlive := i.PAlive, on = "Id"]
return(dt.predictions)
})
# .clv.model.vcov.jacobi.diag --------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.vcov.jacobi.diag", signature = signature(clv.model="clv.model.ggomnbd.static.cov"), definition = function(clv.model, clv.fitted, prefixed.params){
# Get corrections from nocov model
m.diag.model <- callNextMethod()
# No transformations for static covs: Set diag to 1 for all static cov params
# Gather names of cov param
names.cov.prefixed.params <- c([email protected],
[email protected])
if([email protected])
names.cov.prefixed.params <- c(names.cov.prefixed.params, [email protected])
# Set to 1
m.diag.model[names.cov.prefixed.params,
names.cov.prefixed.params] <- diag(x = 1,
nrow = length(names.cov.prefixed.params),
ncol = length(names.cov.prefixed.params))
return(m.diag.model)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_ggomnbd_staticcov.R
|
#' CLV Model without support for life-trans correlation
#'
#' @description
#' This class serves as a parent class to other clv.model classes that cannot be fit with correlation between the
#' lifetime and transaction process.
#'
#' @seealso Parent class \linkS4class{clv.model}
#' @seealso CLV model subclasses \linkS4class{clv.model.bgnbd.no.cov}, \linkS4class{clv.model.ggomnbd.no.cov}
#'
#' @keywords internal
#' @importFrom methods setClass
#' @include all_generics.R
setClass(Class = "clv.model.no.correlation", contains = c("clv.model", "VIRTUAL"))
setMethod("clv.model.supports.correlation", signature = signature(clv.model="clv.model.no.correlation"), def = function(clv.model){
return(FALSE)
})
setMethod("clv.model.estimation.used.correlation", signature = signature(clv.model="clv.model.no.correlation"), def = function(clv.model){
return(FALSE)
})
# Nothing to store additionally
setMethod("clv.model.put.estimation.input", signature = signature(clv.model="clv.model.no.correlation"), def = function(clv.model, ...){
return(clv.model)
})
setMethod(f = "clv.model.generate.start.param.cor", signature = signature(clv.model="clv.model.no.correlation"), definition = function(clv.model, start.param.cor, transformed.start.params.model){
return(transformed.start.params.model)
})
setMethod(f = "clv.model.coef.add.correlation", signature = signature(clv.model="clv.model.no.correlation"), definition = function(clv.model, last.row.optimx.coef, original.scale.params){
return(original.scale.params)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_nocorrelation.R
|
#' @templateVar name_model_full Pareto/NBD
#' @template template_class_clvmodelnocov
#'
#' @keywords internal
#' @seealso Other clv model classes \linkS4class{clv.model}, \linkS4class{clv.model.pnbd.static.cov}, \linkS4class{clv.model.pnbd.dynamic.cov}
#' @seealso Classes using its instance: \linkS4class{clv.fitted}
#' @include all_generics.R class_clv_model_withcorrelation.R
#' @importFrom methods setClass
setClass(Class = "clv.model.pnbd.no.cov", contains = "clv.model.with.correlation")
#' @importFrom methods new
clv.model.pnbd.no.cov <- function(){
return(new("clv.model.pnbd.no.cov",
name.model = "Pareto/NBD Standard",
names.original.params.model = c(r="r", alpha="alpha", s="s", beta="beta"),
names.prefixed.params.model = c("log.r","log.alpha", "log.s", "log.beta"),
start.params.model = c(r=1, alpha=1, s=1, beta=1),
optimx.defaults = list(method = "L-BFGS-B",
# lower = c(log(1*10^(-5)),log(1*10^(-5)),log(1*10^(-5)),log(1*10^(-5))),
# upper = c(log(300),log(2000),log(300),log(2000)),
itnmax = 3000,
control = list(
kkt = TRUE,
save.failures = TRUE,
# Do not perform starttests because it checks the scales with max(logpar)-min(logpar)
# but all standard start parameters are <= 0, hence there are no logpars what
# produces a warning
starttests = FALSE))))
}
# Methods --------------------------------------------------------------------------------------------------------------------------------
# .clv.model.check.input.args -----------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.check.input.args", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, start.params.model, optimx.args, verbose, use.cor, start.param.cor, ...){
err.msg <- c()
# Have to be > 0 as will be logged
if(any(start.params.model <= 0))
err.msg <- c(err.msg, "Please provide only model start parameters greater than 0 as they will be log()-ed for the optimization!")
err.msg <- c(err.msg, .check_user_data_single_boolean(b=use.cor, var.name ="use.cor"))
err.msg <- c(err.msg, check_user_data_startparamcorm(start.param.cor=start.param.cor, use.cor=use.cor))
check_err_msg(err.msg)
})
# .clv.model.put.estimation.input --------------------------------------------------------------------------------------------------------
# Nothing required, use clv.model.with.correlation
# .clv.model.transform.start.params.model --------------------------------------------------------------------------------------------------------
#' @importFrom stats setNames
setMethod("clv.model.transform.start.params.model", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, original.start.params.model){
# Log all user given or default start params
return(setNames(log(original.start.params.model[[email protected]]),
[email protected]))
})
# .clv.model.backtransform.estimated.params.model --------------------------------------------------------------------------------------------------------
setMethod("clv.model.backtransform.estimated.params.model", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, prefixed.params.model){
# exp all prefixed params
return(exp(prefixed.params.model[[email protected]]))
})
# .clv.model.prepare.optimx.args --------------------------------------------------------------------------------------------------------
#' @importFrom utils modifyList
setMethod(f = "clv.model.prepare.optimx.args", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, prepared.optimx.args){
# Only add LL function args, everything else is prepared already, incl. start parameters
optimx.args <- modifyList(prepared.optimx.args,
list(LL.function.sum = pnbd_nocov_LL_sum,
LL.function.ind = pnbd_nocov_LL_ind, # if doing correlation
obj = clv.fitted,
vX = clv.fitted@cbs$x,
vT_x = clv.fitted@cbs$t.x,
vT_cal = clv.fitted@cbs$T.cal,
# parameter ordering for the callLL interlayer
LL.params.names.ordered = c(log.r="log.r", log.alpha="log.alpha",
log.s="log.s", log.beta="log.beta")),
keep.null = TRUE)
return(optimx.args)
})
# . clv.model.process.post.estimation -----------------------------------------------------------------------------------------
setMethod("clv.model.process.post.estimation", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, res.optimx){
# No additional step needed (ie store model specific stuff, extra process)
return(clv.fitted)
})
# .clv.model.cor.to.m --------------------------------------------------------------------------------------------------------
setMethod(f="clv.model.cor.to.m", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, prefixed.params.model, param.cor){
.cor.part <- function(params){
r <- exp(params[["log.r"]])
alpha <- exp(params[["log.alpha"]])
s <- exp(params[["log.s"]])
beta <- exp(params[["log.beta"]])
fct.part <- function(param.ab, param.rs){
return( (sqrt(param.rs) / (1+param.ab)) * ((param.ab / (1+param.ab))^param.rs))
}
return(fct.part(param.ab = alpha, param.rs = r) * fct.part(param.ab = beta, param.rs = s))
}
res.m <- param.cor / .cor.part(params=prefixed.params.model)
# return unnamed as otherwise still called "cor"
return(unname(res.m))
})
setMethod(f="clv.model.m.to.cor", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, prefixed.params.model, param.m){
.cor.part <- function(params){
r <- exp(params[["log.r"]])
alpha <- exp(params[["log.alpha"]])
s <- exp(params[["log.s"]])
beta <- exp(params[["log.beta"]])
fct.part <- function(param.ab, param.rs){
return( (sqrt(param.rs) / (1+param.ab)) * ((param.ab / (1+param.ab))^param.rs) )
}
return(fct.part(param.ab = alpha, param.rs = r) * fct.part(param.ab = beta, param.rs = s))
}
res.cor <- param.m * .cor.part(params=prefixed.params.model)
# return unnamed as otherwise still called "m"
return(unname(res.cor))
})
# .clv.model.vcov.jacobi.diag --------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.vcov.jacobi.diag", signature = signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, prefixed.params){
# Jeff:
# Delta method:
# h=(log(t),log(t),log(t),log(t),t,t,t)
# g=h^-1=(exp(t),exp(t),exp(t),exp(t),t,t,t)
# Deltaexp = g' = (exp(t),exp(t),exp(t),exp(t),1,1,1)
# Create matrix with the full required size
m.diag <- diag(x = 0, ncol = length(prefixed.params), nrow=length(prefixed.params))
rownames(m.diag) <- colnames(m.diag) <- names(prefixed.params)
# Add the transformations for the model to the matrix
# All model params need to be exp()
m.diag[[email protected],
[email protected]] <- diag(x = exp(prefixed.params[[email protected]]),
nrow = length([email protected]),
ncol = length([email protected]))
# If correlation, add the transformations for each parameter vs correlation param.m
if([email protected]){
# This is same as m.to.cor
cor.phi <- function(param.m, a, r, s, b){
return(param.m * (sqrt(r)/(1+a)) * (a/(1+a))^r * (sqrt(s)/(1+b)) * (b/(1+b))^s)
}
a <- exp(prefixed.params["log.alpha"])
r <- exp(prefixed.params["log.r"])
b <- exp(prefixed.params["log.beta"])
s <- exp(prefixed.params["log.s"])
param.m <- prefixed.params[[email protected]]
# eq 2
phi_dloga <- cor.phi(param.m=param.m, a=a, r=r, b=b, s=s) * (r - ((a*(1+r))/(1+a)))
# eq 3
phi_dlogb <- cor.phi(param.m=param.m, a=a, r=r, b=b, s=s) * (s - ((b*(1+s))/(1+b)))
# eq 4
phi_dlogr <- cor.phi(param.m=param.m, a=a, r=r, b=b, s=s) * (0.5 - r*log(1+a) + r*log(a))
# eq 5
phi_dlogs <- cor.phi(param.m=param.m, a=a, r=r, b=b, s=s) * (0.5 - s*log(1+b) + s*log(b))
# eq 6
phi_dlogm <- (sqrt(r)/(1+a)) * (a/(1+a))^r * (sqrt(s)/(1+b)) * (b/(1+b))^s
# Add to transformation matrix on last line only! (not aswell on the last column)
m.diag[[email protected], "log.alpha"] <- phi_dloga
m.diag[[email protected], "log.r"] <- phi_dlogr
m.diag[[email protected], "log.beta"] <- phi_dlogb
m.diag[[email protected], "log.s"] <- phi_dlogs
m.diag[[email protected],
[email protected]] <- phi_dlogm
}
return(m.diag)
})
# clv.model.process.newdata --------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.process.newdata", signature = signature(clv.model = "clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, verbose){
# clv.data in clv.fitted is already replaced with newdata here
# Only need to redo cbs if new data is given
clv.fitted@cbs <- pnbd_cbs(clv.data = [email protected])
return(clv.fitted)
})
# clv.model.predict --------------------------------------------------------------------------------------------------------
setMethod("clv.model.predict", signature(clv.model="clv.model.pnbd.no.cov"), definition = function(clv.model, clv.fitted, dt.predictions, verbose, continuous.discount.factor, ...){
period.length <- Id <- x <- t.x <- T.cal <- PAlive <- i.PAlive <- CET <- i.CET <- DERT <- i.DERT <- NULL # cran silence
predict.number.of.periods <- dt.predictions[1, period.length]
# To ensure sorting, do everything in a single table
dt.result <- copy(clv.fitted@cbs[, c("Id", "x", "t.x", "T.cal")])
# Add CET
dt.result[, CET := pnbd_nocov_CET(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
dPeriods = predict.number.of.periods,
vX = x,
vT_x = t.x,
vT_cal = T.cal)]
# Add PAlive
dt.result[, PAlive := pnbd_nocov_PAlive(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
vX = x,
vT_x = t.x,
vT_cal = T.cal)]
# Add DERT
dt.result[, DERT := pnbd_nocov_DERT(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
continuous_discount_factor = continuous.discount.factor,
vX = x,
vT_x = t.x,
vT_cal = T.cal)]
# Add results to prediction table, by matching Id
dt.predictions[dt.result, CET := i.CET, on = "Id"]
dt.predictions[dt.result, PAlive := i.PAlive, on = "Id"]
dt.predictions[dt.result, DERT := i.DERT, on = "Id"]
return(dt.predictions)
})
# . clv.model.expectation --------------------------------------------------------------------------------------------------------
setMethod("clv.model.expectation", signature(clv.model="clv.model.pnbd.no.cov"), function(clv.model, clv.fitted, dt.expectation.seq, verbose){
r <- s <- alpha_i <- beta_i <- date.first.actual.trans <- T.cal <- t_i <- NULL
params_i <- clv.fitted@cbs[, c("Id", "T.cal", "date.first.actual.trans")]
fct.expectation <- function(params_i.t) {return(pnbd_nocov_expectation(r = [email protected][["r"]],
s = [email protected][["s"]],
alpha_0 = [email protected][["alpha"]],
beta_0 = [email protected][["beta"]],
vT_i = params_i.t$t_i))}
return(DoExpectation(dt.expectation.seq = dt.expectation.seq, params_i = params_i,
fct.expectation = fct.expectation, clv.time = [email protected]@clv.time))
})
# . clv.model.pmf --------------------------------------------------------------------------------------------------------
setMethod("clv.model.pmf", signature=(clv.model="clv.model.pnbd.no.cov"), function(clv.model, clv.fitted, x){
Id <- T.cal <- pmf.x <- NULL
dt.res <- clv.fitted@cbs[, list(Id, T.cal)]
dt.res[, pmf.x := pnbd_nocov_PMF(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
vT_i = T.cal,
x = x)]
dt.res <- dt.res[, list(Id, pmf.x)]
setnames(dt.res, "pmf.x", paste0("pmf.x.", x))
return(dt.res)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_pnbd.R
|
#' CLV Model functionality for PNBD with dynamic covariates
#'
#' This class implements the functionalities and model-specific steps which are required
#' to fit the Pareto/NBD model with dynamic covariates.
#'
#' @keywords internal
#' @seealso Other clv model classes \linkS4class{clv.model}, \linkS4class{clv.model.pnbd.no.cov}, \linkS4class{clv.model.pnbd.static.cov}
#' @seealso Classes using its instance: \linkS4class{clv.fitted.transactions.dynamic.cov}
#'
#' @include all_generics.R class_clv_model_pnbd_staticcov.R
setClass(Class = "clv.model.pnbd.dynamic.cov", contains = "clv.model.pnbd.static.cov")
clv.model.pnbd.dynamic.cov <- function(){
return(new("clv.model.pnbd.dynamic.cov",
clv.model.pnbd.static.cov(),
name.model = "Pareto/NBD with Dynamic Covariates",
# Overwrite optimx default args
optimx.defaults = list(method = "Nelder-Mead",
itnmax = 3000,
control = list(
kkt = TRUE,
save.failures = TRUE,
# Do not perform starttests because it checks the scales with max(logpar)-min(logpar)
# but all standard start parameters are <= 0, hence there are no logpars what
# produces a warning
starttests = FALSE))))
}
# Methods --------------------------------------------------------------------------------------------------------------------------------
# Override static cov implementation
# . clv.model.prepare.optimx.args ------------------------------------------------------------------------------------------------
#' @importFrom utils modifyList
setMethod(f = "clv.model.prepare.optimx.args", signature = signature(clv.model="clv.model.pnbd.dynamic.cov"),
definition = function(clv.model, clv.fitted, prepared.optimx.args){
# Do not call the no.cov function because the LL is different
x <- t.x <- T.cal <- NULL
# Everything to call the LL function
optimx.args <- modifyList(prepared.optimx.args,
list(
LL.function.sum = pnbd_dyncov_LL_negsum,
LL.function.ind = pnbd_dyncov_LL_ind, # if doing correlation
LL.params.names.ordered = c([email protected],
[email protected],
[email protected])))
l.dyncov.args <- pnbd_dyncov_getLLcallargs(clv.fitted)
optimx.args <- modifyList(optimx.args, l.dyncov.args)
return(optimx.args)
})
# . clv.model.process.post.estimation ------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.process.post.estimation", signature = signature(clv.model="clv.model.pnbd.dynamic.cov"), definition = function(clv.model, clv.fitted, res.optimx){
# Estimate again at found values to get LL.data (of last method used)
# This is then used when plotting and predicting
optimal.coefs <- drop(tail(coef(res.optimx), n=1))
if(!anyNA(optimal.coefs)){
# Need to set prediction params to all params needed for LL
clv.fitted <- clv.controlflow.predict.set.prediction.params(clv.fitted)
# For the LL, the model params need to be logged again
# can do directly, as know this is the pnbd dyncov model
# Other option: read from optimx result
# final.params <- c(drop(tail(coef([email protected]), n=1))[[email protected]@names.prefixed.params.model])
final.params <- c(setNames(log([email protected][c("r", "alpha", "s", "beta")]),
c("log.r", "log.alpha", "log.s", "log.beta")),
# use the same names as after interlayers. Need these as could be constrained
setNames([email protected], [email protected]),
setNames([email protected], [email protected]))
# get LL with all values, not just ind LL or summed LL
[email protected] <- pnbd_dyncov_getLLdata(clv.fitted=clv.fitted, params=final.params)
}else{
warning("Could not derive dyncov LL data with these final parameters - cannot predict and plot!", call. = FALSE)
}
return(clv.fitted)
})
# . clv.model.process.newdata ------------------------------------------------------------------------------------------------
#' @importFrom methods callNextMethod
setMethod(f = "clv.model.process.newdata", signature = signature(clv.model = "clv.model.pnbd.dynamic.cov"), definition = function(clv.model, clv.fitted, verbose){
# do nocov preparations (new cbs only)
clv.fitted <- callNextMethod()
# data in clv.fitted is already newdata
# Remake cbs for dyncov becasuse in the nocov cbs, there is no d_omega.
clv.fitted@cbs <- pnbd_dyncov_cbs(clv.data = [email protected])
if(verbose)
message("Calculating LogLikelihood values for the provided newdata at the estimated parameters.")
# For dyncov also neeed to calculate the LL.data again - Exact same as in
# For the LL, the model params need to be logged again
# can do directly, as know this is the pnbd dyncov model
# Other option: read from optimx result
# final.params <- c(drop(tail(coef([email protected]), n=1))[[email protected]@names.prefixed.params.model])
final.params <- c(setNames(log([email protected][c("r", "alpha", "s", "beta")]),
c("log.r", "log.alpha", "log.s", "log.beta")),
# use the same names as after interlayers. Need these as could be constrained
setNames([email protected], [email protected]),
setNames([email protected], [email protected]))
# also need to re-do the walks if there is new data
l.walks <- pnbd_dyncov_createwalks(clv.data = [email protected])
[email protected] <- l.walks[["data.walks.life.aux"]]
[email protected] <- l.walks[["data.walks.life.real"]]
[email protected] <- l.walks[["data.walks.trans.aux"]]
[email protected] <- l.walks[["data.walks.trans.real"]]
[email protected] <- pnbd_dyncov_getLLdata(clv.fitted=clv.fitted, params=final.params)
return(clv.fitted)
})
# . clv.model.predict ------------------------------------------------------------------------------------------------
setMethod("clv.model.predict", signature(clv.model="clv.model.pnbd.dynamic.cov"), function(clv.model, clv.fitted, dt.predictions, verbose, continuous.discount.factor, ...){
period.length <- period.last <- CET <- i.CET <- PAlive <- i.palive <- DECT <- i.DECT <- NULL
predict.number.of.periods <- dt.predictions[1, period.length]
tp.period.last <- dt.predictions[1, period.last]
if(verbose)
message("Predicting for dyn cov model....")
# Palive
dt.palive <- pnbd_dyncov_palive(clv.fitted=clv.fitted)
dt.predictions[dt.palive, PAlive := i.palive, on="Id"]
# CET
dt.cet <- pnbd_dyncov_CET(clv.fitted = clv.fitted,
predict.number.of.periods = predict.number.of.periods,
prediction.end.date = tp.period.last)
dt.predictions[dt.cet, CET := i.CET, on="Id"]
# DECT
if(continuous.discount.factor != 0){
dt.dect <- pnbd_dyncov_DECT(clv.fitted = clv.fitted,
predict.number.of.periods = predict.number.of.periods,
prediction.end.date = tp.period.last,
continuous.discount.factor = continuous.discount.factor)
dt.predictions[dt.dect, DECT :=i.DECT, on="Id"]
}else{
# If the discount factor is zero, the results correspond to CET
# DECT crashes for discount.factor = 0
dt.predictions[, DECT := CET]
}
return(dt.predictions)
})
# . clv.model.expectation ------------------------------------------------------------------------------------------------
setMethod("clv.model.expectation", signature(clv.model="clv.model.pnbd.dynamic.cov"), function(clv.model, clv.fitted, dt.expectation.seq, verbose){
return(pnbd_dyncov_expectation(clv.fitted=clv.fitted, dt.expectation.seq=dt.expectation.seq, verbose=verbose))
})
# . clv.model.pmf --------------------------------------------------------------------------------------------------------
#' @include all_generics.R
setMethod("clv.model.pmf", signature=(clv.model="clv.model.pnbd.dynamic.cov"), function(clv.model, clv.fitted, x){
stop("PMF is not available for pnbd with dynamic covariates!", call.=FALSE)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_pnbd_dynamiccov.R
|
#' @templateVar name_model_full Pareto/NBD
#' @template template_class_clvmodelstaticcov
#'
#' @seealso Other clv model classes \linkS4class{clv.model}, \linkS4class{clv.model.pnbd.no.cov}, \linkS4class{clv.model.pnbd.dynamic.cov}
#' @seealso Classes using its instance: \linkS4class{clv.fitted.transactions.static.cov}
#'
#' @include all_generics.R class_clv_model_pnbd.R
setClass(Class = "clv.model.pnbd.static.cov", contains = "clv.model.pnbd.no.cov",
slots = list(
start.param.cov = "numeric"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
start.param.cov = numeric(0)))
#' @importFrom methods new
clv.model.pnbd.static.cov <- function(){
# optimx.args stay the same as for nocov
return(new("clv.model.pnbd.static.cov",
clv.model.pnbd.no.cov(),
# Overwrite nocov name
name.model = "Pareto/NBD with Static Covariates",
start.param.cov = 0.1))
}
clv.model.pnbd.static.cov.get.alpha_i <- function(clv.fitted){
alpha_i <- NULL
dt.alpha_i <- clv.fitted@cbs[, "Id"]
m.cov.data.trans <- clv.data.get.matrix.data.cov.trans([email protected], correct.row.names=dt.alpha_i$Id,
correct.col.names=names([email protected]))
dt.alpha_i[, alpha_i := pnbd_staticcov_alpha_i(alpha_0 = [email protected][["alpha"]],
vCovParams_trans = [email protected],
mCov_trans = m.cov.data.trans)]
return(dt.alpha_i)
}
clv.model.pnbd.static.cov.get.beta_i <- function(clv.fitted){
beta_i <- NULL
dt.beta_i <- clv.fitted@cbs[, "Id"]
m.cov.data.life <- clv.data.get.matrix.data.cov.life([email protected], correct.row.names=dt.beta_i$Id,
correct.col.names=names([email protected]))
dt.beta_i[, beta_i := pnbd_staticcov_beta_i(beta_0 = [email protected][["beta"]],
vCovParams_life = [email protected],
mCov_life = m.cov.data.life)]
return(dt.beta_i)
}
# Methods --------------------------------------------------------------------------------------------------------------------------------
# .clv.model.check.input.args ------------------------------------------------------------------------------------------------------------
# use nocov, no static cov checks
# . clv.model.put.estimation.input ------------------------------------------------------------------------------------------------------------
# Nothing specific required, use nocov
# . clv.model.transform.start.params.cov ------------------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.transform.start.params.cov", signature = signature(clv.model="clv.model.pnbd.static.cov"), definition = function(clv.model, start.params.cov){
# no transformation needed
return(start.params.cov)
})
# . clv.model.backtransform.estimated.params.cov -----------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.backtransform.estimated.params.cov", signature = signature(clv.model="clv.model.pnbd.static.cov"), definition = function(clv.model, prefixed.params.cov){
# no transformation needed
return(prefixed.params.cov)
})
# . clv.model.prepare.optimx.args -----------------------------------------------------------------------------------------------------
#' @importFrom utils modifyList
setMethod(f = "clv.model.prepare.optimx.args", signature = signature(clv.model="clv.model.pnbd.static.cov"),
definition = function(clv.model, clv.fitted, prepared.optimx.args){
# Do not call the no.cov function as the LL is different
# Everything to call the LL function
optimx.args <- modifyList(prepared.optimx.args,
list(
obj = clv.fitted,
LL.function.sum = pnbd_staticcov_LL_sum,
LL.function.ind = pnbd_staticcov_LL_ind, # if doing correlation
# For cpp static cov the param order is: model, life, trans
LL.params.names.ordered = c([email protected],
[email protected],
[email protected]),
vX = clv.fitted@cbs$x,
vT_x = clv.fitted@cbs$t.x,
vT_cal = clv.fitted@cbs$T.cal,
mCov_life = clv.data.get.matrix.data.cov.life(clv.data = [email protected], correct.row.names=clv.fitted@cbs$Id,
correct.col.names=clv.data.get.names.cov.life([email protected])),
mCov_trans = clv.data.get.matrix.data.cov.trans(clv.data = [email protected], correct.row.names=clv.fitted@cbs$Id,
correct.col.names=clv.data.get.names.cov.trans([email protected]))),
keep.null = TRUE)
return(optimx.args)
})
# . clv.model.vcov.jacobi.diag -----------------------------------------------------------------------------------------------------
setMethod(f = "clv.model.vcov.jacobi.diag", signature = signature(clv.model="clv.model.pnbd.static.cov"),
definition = function(clv.model, clv.fitted, prefixed.params){
# Get corrections from nocov model
m.diag.model <- callNextMethod()
# No transformations for static covs: Set diag to 1 for all static cov params
# Gather names of cov param
names.cov.prefixed.params <- c([email protected],
[email protected])
if([email protected])
names.cov.prefixed.params <- c(names.cov.prefixed.params, [email protected])
# Set to 1
m.diag.model[names.cov.prefixed.params,
names.cov.prefixed.params] <- diag(x = 1,
nrow = length(names.cov.prefixed.params),
ncol = length(names.cov.prefixed.params))
return(m.diag.model)
})
# . clv.model.predict -----------------------------------------------------------------------------------------------------
setMethod("clv.model.predict", signature(clv.model="clv.model.pnbd.static.cov"), definition = function(clv.model, clv.fitted, dt.predictions, verbose, continuous.discount.factor, ...){
# cran silence
period.length <- CET <- i.CET <- x <- t.x <- T.cal <- PAlive <- i.PAlive <- i.DERT <- DERT <- NULL
predict.number.of.periods <- dt.predictions[1, period.length]
# To ensure sorting, do everything in a single table
dt.result <- copy(clv.fitted@cbs[, c("Id", "x", "t.x", "T.cal")])
data.cov.mat.life <- clv.data.get.matrix.data.cov.life(clv.data = [email protected], correct.row.names=dt.result$Id,
correct.col.names=names([email protected]))
data.cov.mat.trans <- clv.data.get.matrix.data.cov.trans(clv.data = [email protected], correct.row.names=dt.result$Id,
correct.col.names=names([email protected]))
# Add CET
dt.result[, CET := pnbd_staticcov_CET(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
dPeriods = predict.number.of.periods,
vX = x,
vT_x = t.x,
vT_cal = T.cal,
vCovParams_trans = [email protected],
vCovParams_life = [email protected],
mCov_trans = data.cov.mat.trans,
mCov_life = data.cov.mat.life)]
# Add PAlive
dt.result[, PAlive := pnbd_staticcov_PAlive(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
vX = x,
vT_x = t.x,
vT_cal = T.cal,
vCovParams_trans = [email protected],
vCovParams_life = [email protected],
mCov_trans = data.cov.mat.trans,
mCov_life = data.cov.mat.life)]
# Add DERT
dt.result[, DERT := pnbd_staticcov_DERT(r = [email protected][["r"]],
alpha_0 = [email protected][["alpha"]],
s = [email protected][["s"]],
beta_0 = [email protected][["beta"]],
continuous_discount_factor = continuous.discount.factor,
vX = x,
vT_x = t.x,
vT_cal = T.cal,
mCov_life = data.cov.mat.life,
mCov_trans = data.cov.mat.trans,
vCovParams_life = [email protected],
vCovParams_trans = [email protected])]
# Add results to prediction table, by matching Id
dt.predictions[dt.result, CET := i.CET, on = "Id"]
dt.predictions[dt.result, PAlive := i.PAlive, on = "Id"]
dt.predictions[dt.result, DERT := i.DERT, on = "Id"]
return(dt.predictions)
})
# . clv.model.expectation -----------------------------------------------------------------------------------------------------
setMethod("clv.model.expectation", signature(clv.model="clv.model.pnbd.static.cov"), function(clv.model, clv.fitted, dt.expectation.seq, verbose){
r <- s <- alpha_i <- beta_i <- i.alpha_i <- i.beta_i <- T.cal <- t_i <- NULL
#calculate alpha_i, beta_i
params_i <- clv.fitted@cbs[, c("Id", "T.cal", "date.first.actual.trans")]
dt.alpha_i <- clv.model.pnbd.static.cov.get.alpha_i(clv.fitted)
dt.beta_i <- clv.model.pnbd.static.cov.get.beta_i(clv.fitted)
params_i[dt.alpha_i, alpha_i := i.alpha_i, on="Id"]
params_i[dt.beta_i, beta_i := i.beta_i, on="Id"]
# To caluclate expectation at point t for customers alive in t, given in params_i.t
fct.expectation <- function(params_i.t) {
return(drop(pnbd_staticcov_expectation(r = [email protected][["r"]],
s = [email protected][["s"]],
vAlpha_i = params_i.t$alpha_i,
vBeta_i = params_i.t$beta_i,
vT_i = params_i.t$t_i)))}
return(DoExpectation(dt.expectation.seq = dt.expectation.seq, params_i = params_i,
fct.expectation = fct.expectation, clv.time = [email protected]@clv.time))
})
# . clv.model.pmf -----------------------------------------------------------------------------------------------------
setMethod("clv.model.pmf", signature=(clv.model="clv.model.pnbd.static.cov"), function(clv.model, clv.fitted, x){
Id <- T.cal <- pmf.x <- alpha_i <- beta_i <- i.alpha_i <- i.beta_i <- NULL
dt.res <- clv.fitted@cbs[, list(Id, T.cal)]
dt.alpha_i <- clv.model.pnbd.static.cov.get.alpha_i(clv.fitted)
dt.beta_i <- clv.model.pnbd.static.cov.get.beta_i(clv.fitted)
dt.res[dt.alpha_i, alpha_i := i.alpha_i, on="Id"]
dt.res[dt.beta_i, beta_i := i.beta_i, on="Id"]
dt.res[, pmf.x := pnbd_staticcov_PMF(r = [email protected][["r"]],
s = [email protected][["s"]],
vAlpha_i = alpha_i,
vBeta_i = beta_i,
vT_i = T.cal,
x = x)]
dt.res <- dt.res[, list(Id, pmf.x)]
setnames(dt.res, "pmf.x", paste0("pmf.x.", x))
return(dt.res)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_pnbd_staticcov.R
|
#' CLV Model providing life-trans correlation related functionalities
#'
#' @description
#' This class serves as a parent class to other clv.model classes and provides the functionality needed
#' to fit a model with correlation between the lifetime and transaction process.
#'
#' @slot estimation.used.correlation Single boolean whether the correlation was estimated.
#' @slot name.prefixed.cor.param.m Single character vector of the internal name used for the correlation parameter during optimization.
#' @slot name.correlation.cor Single character vector of the external name used for the correlation parameter.
#'
#' @seealso Parent class \linkS4class{clv.model}
#' @seealso CLV model subclasses \linkS4class{clv.model.pnbd.no.cov}, \linkS4class{clv.model.pnbd.static.cov}, \linkS4class{clv.model.pnbd.dynamic.cov}
#'
#' @keywords internal
#' @importFrom methods setClass
#' @include all_generics.R
setClass(Class = "clv.model.with.correlation", contains = c("clv.model", "VIRTUAL"),
slots = list(
estimation.used.correlation = "logical",
name.prefixed.cor.param.m = "character",
name.correlation.cor = "character"),
# Have to use prototype because cannot instantiate (ie constructor function) a virtual class
prototype = list(
estimation.used.correlation = logical(0), # not known yet
name.prefixed.cor.param.m = "correlation.param.m",
name.correlation.cor = "Cor(life,trans)"))
setMethod("clv.model.supports.correlation", signature = signature(clv.model="clv.model.with.correlation"), def = function(clv.model){
return(TRUE)
})
setMethod("clv.model.estimation.used.correlation", signature = signature(clv.model="clv.model.with.correlation"), def = function(clv.model){
return([email protected])
})
setMethod("clv.model.put.estimation.input", signature = signature(clv.model="clv.model.with.correlation"), def = function(clv.model, use.cor, ...){
# Should correlation be calculated? -----------------------------------------------------------------
if(use.cor){
[email protected] <- TRUE
}else{
[email protected] <- FALSE
}
return(clv.model)
})
setMethod(f = "clv.model.coef.add.correlation", signature = signature(clv.model="clv.model.with.correlation"), definition = function(clv.model, last.row.optimx.coef, original.scale.params){
if([email protected]){
prefixed.params.model <- last.row.optimx.coef[1, [email protected], drop=TRUE]
param.m <- last.row.optimx.coef[1, [email protected], drop=TRUE]
param.cor <- clv.model.m.to.cor(clv.model = clv.model,
prefixed.params.model = prefixed.params.model,
param.m = param.m)
names(param.cor) <- [email protected]
original.scale.params <- c(original.scale.params, param.cor)
}
return(original.scale.params)
})
# function(clv.model, start.param.cor, transformed.start.params)
setMethod(f = "clv.model.generate.start.param.cor", signature = signature(clv.model="clv.model.with.correlation"), definition = function(clv.model, start.param.cor, transformed.start.params.model){
# Correlation param m
if([email protected]){
# Transform correlation to param m
# do model-specific transformation with the generated and transformed model parameters
if(is.null(start.param.cor)){
# Use cor=0 if none given
start.param.cor.param.m <- clv.model.cor.to.m(clv.model=clv.model,
prefixed.params.model=transformed.start.params.model,
param.cor = 0)
}else{
start.param.cor.param.m <- clv.model.cor.to.m(clv.model=clv.model,
prefixed.params.model=transformed.start.params.model,
param.cor = start.param.cor)
}
# Name and add to all start params
names(start.param.cor.param.m) <- [email protected]
transformed.start.params.model <- c(transformed.start.params.model, start.param.cor.param.m)
}
return(transformed.start.params.model)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_model_withcorrelation.R
|
#' @templateVar name_model_full Pareto/NBD
#' @templateVar name_class_clvmodel clv.model.pnbd.no.cov
#' @template template_class_clvfittedtransactionmodels
#'
#' @template template_slot_pnbdcbs
#'
#' @seealso \linkS4class{clv.fitted.transactions}, \linkS4class{clv.model.pnbd.no.cov}, \linkS4class{clv.pnbd.static.cov}, \linkS4class{clv.pnbd.dynamic.cov}
#'
#' @keywords internal
#' @importFrom methods setClass
#' @include class_clv_model_pnbd.R class_clv_data.R class_clv_fitted_transactions.R
setClass(Class = "clv.pnbd", contains = "clv.fitted.transactions",
slots = c(
cbs = "data.table"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
cbs = data.table()))
#' @importFrom methods new
clv.pnbd <- function(cl, clv.data){
dt.cbs.pnbd <- pnbd_cbs(clv.data = clv.data)
clv.model <- clv.model.pnbd.no.cov()
return(new("clv.pnbd",
clv.fitted.transactions(cl=cl, clv.model=clv.model, clv.data=clv.data),
cbs = dt.cbs.pnbd))
}
pnbd_cbs <- function(clv.data){
Date <- Price <- x <- date.first.actual.trans <- date.last.transaction <- NULL
# Customer-By-Sufficiency (CBS) Matrix
# Only for transactions in calibration period
# Only repeat transactions are relevant
#
# For every customer:
# x: Number of repeat transactions := Number of actual transactions - 1
# t.x: Time between first actual and last transaction
# T.cal: Time between first actual transaction and end of calibration period
#
# All time is expressed in time units
trans.dt <- clv.data.get.transactions.in.estimation.period(clv.data = clv.data)
#Initial cbs, for every Id a row
cbs <- trans.dt[ , list(x =.N,
date.first.actual.trans = min(Date),
date.last.transaction = max(Date)),
by="Id"]
# Only repeat transactions -> Number of transactions - 1
cbs[, x := x - 1]
# t.x, T.cal
cbs[, ':='(t.x = clv.time.interval.in.number.tu([email protected], interv=interval(start = date.first.actual.trans, end = date.last.transaction)),
T.cal = clv.time.interval.in.number.tu([email protected], interv=interval(start = date.first.actual.trans, end = [email protected]@timepoint.estimation.end)))]
cbs[, date.last.transaction := NULL]
setkeyv(cbs, c("Id", "date.first.actual.trans"))
setcolorder(cbs, c("Id","x","t.x","T.cal", "date.first.actual.trans"))
return(cbs)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_pnbd.R
|
#' Result of fitting the Pareto/NBD model with dynamic covariates
#'
#' @description
#' Output from fitting the Pareto/NBD model on data with dynamic covariates. It constitutes the
#' estimation result and is returned to the user to use it as input to other methods such as
#' to make predictions or plot the unconditional expectation.
#'
#' Inherits from \code{clv.fitted.transactions.dynamic.cov} in order to execute all steps required for fitting a model
#' with dynamic covariates and it contains an instance of class \code{clv.model.pnbd.dynamic.cov} which
#' provides the required Pareto/NBD (dynamic covariates) specific functionalities.
#'
#' @template template_slot_pnbdcbs
#'
#' @seealso \linkS4class{clv.fitted.transactions.dynamic.cov}, \linkS4class{clv.model.pnbd.dynamic.cov}, \linkS4class{clv.pnbd}, \linkS4class{clv.pnbd.static.cov}
#'
#' @keywords internal
#' @importFrom methods setClass
#' @include class_clv_model_pnbd_dynamiccov.R class_clv_data_dynamiccovariates.R
setClass(Class = "clv.pnbd.dynamic.cov", contains = "clv.fitted.transactions.dynamic.cov",
slots = c(
cbs = "data.table",
data.walks.life.aux = "data.table",
data.walks.life.real = "data.table",
data.walks.trans.aux = "data.table",
data.walks.trans.real = "data.table",
LL.data = "data.table"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
cbs = data.table(),
data.walks.life.aux = data.table(),
data.walks.life.real = data.table(),
data.walks.trans.aux = data.table(),
data.walks.trans.real = data.table(),
LL.data = data.table()))
#' @importFrom methods new
clv.pnbd.dynamic.cov <- function(cl, clv.data){
dt.cbs.pnbd <- pnbd_dyncov_cbs(clv.data = clv.data)
clv.model <- clv.model.pnbd.dynamic.cov()
# Create walks only after inputchecks
# (walks are done in clv.model.put.estimation.input)
return(new("clv.pnbd.dynamic.cov",
clv.fitted.transactions.dynamic.cov(cl=cl, clv.model=clv.model, clv.data=clv.data),
cbs = dt.cbs.pnbd))
}
# Dyncov cbs also has d_omega for every customer
pnbd_dyncov_cbs <- function(clv.data){
d_omega <- date.first.actual.trans <- NULL
dt.cbs <- pnbd_cbs(clv.data = clv.data)
# The CBS for pnbd dyncov additinoally contains d_omega for every customer
# d_omega: "= Time difference between the very first purchase (start of the observation period)
# and the end of the interval the first purchase is contained in."
dt.cbs[, d_omega := pnbd_dyncov_walk_d([email protected], tp.relevant.transaction = date.first.actual.trans)]
return(dt.cbs)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_pnbd_dynamiccov.R
|
#' @templateVar name_model_full Pareto/NBD
#' @templateVar name_class_clvmodel clv.model.pnbd.static.cov
#' @template template_class_clvfittedtransactionmodels_staticcov
#'
#' @template template_slot_pnbdcbs
#'
#' @seealso \linkS4class{clv.fitted.transactions.static.cov}, \linkS4class{clv.model.pnbd.static.cov}, \linkS4class{clv.pnbd}, \linkS4class{clv.pnbd.dynamic.cov}
#'
#' @keywords internal
#' @importFrom methods setClass
#' @include class_clv_model_pnbd_staticcov.R class_clv_data_staticcovariates.R class_clv_fitted_transactions_staticcov.R
setClass(Class = "clv.pnbd.static.cov", contains = "clv.fitted.transactions.static.cov",
slots = c(
cbs = "data.table"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
cbs = data.table()))
#' @importFrom methods new
clv.pnbd.static.cov <- function(cl, clv.data){
dt.cbs.pnbd <- pnbd_cbs(clv.data = clv.data)
clv.model <- clv.model.pnbd.static.cov()
return(new("clv.pnbd.static.cov",
clv.fitted.transactions.static.cov(cl=cl, clv.model=clv.model, clv.data=clv.data),
cbs = dt.cbs.pnbd))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_pnbd_staticcov.R
|
#' Time Unit defining conceptual periods
#'
#' Represents a time unit and offers methods for time unit related functionality.
#' It stores all information related to timepoints (i.e. time and dates) of the
#' estimation and holdout sample periods and offers methods to parse user input
#' and to do 'time-unit math'.
#'
#' This encapsulation of all time unit functionality in one class allows for custom type of
#' time units such as Bi-weekly or irregularly spaced time units.
#'
#' \code{clv.time} is a virtual class and sub-classes implement the actual parsing and calculations.
#'
#' \linkS4class{clv.time.date} uses data type \code{Date} for time units equal or
#' greater than a single day that do not require a time of day.
#'
#' \linkS4class{clv.time.datetime} uses data type \code{POSIXct} for
#' time units smaller than a single day.
#'
#'
#' @slot timepoint.estimation.start Single \code{Date} or \code{POSIXct} that stores the start of the estimation period.
#' @slot timepoint.estimation.end Single \code{Date} or \code{POSIXct} that stores the end of the estimation period.
#' @slot timepoint.holdout.start Single \code{Date} or \code{POSIXct} that stores the start of the holdout period.
#' @slot timepoint.holdout.end Single \code{Date} or \code{POSIXct} that stores the end of the holdout period.
#' @slot time.format Single character vector with the format that is used to parse dates and times given as characters.
#' @slot estimation.period.in.tu Single numeric indicating the length of the estimation period in number of time units.
#' @slot holdout.period.in.tu Single numeric indicating the length of the holdout period in number of time units.
#' @slot name.time.unit Single character vector storing the human-readable name of the time unit for output.
#'
#' @seealso \link{summary.clv.time} for a summary about an object of class \code{clv.time}
#' @seealso \linkS4class{clv.time.days} for an implementation of time unit 'Days'
#' @seealso \linkS4class{clv.time.weeks} for an implementation of time unit 'Weeks'
#' @seealso \linkS4class{clv.time.years} for an implementation of time unit 'Years'
#'
#'
#' @include all_generics.R
#' @keywords internal
setClass("clv.time", contains = "VIRTUAL",
slots = list(
timepoint.estimation.start = "ANY",
timepoint.estimation.end = "ANY",
timepoint.holdout.start = "ANY",
timepoint.holdout.end = "ANY",
estimation.period.in.tu = "numeric",
holdout.period.in.tu = "numeric",
time.format = "character",
name.time.unit = "character"),
prototype = list(
estimation.period.in.tu = numeric(0),
holdout.period.in.tu = numeric(0),
time.format = character(0),
name.time.unit = character(0)))
# No constructor function, as should not be instanciated
# **FUTURE: future usage:
# custom time interval appraoch:
# cut(hour(now()), breaks=c(0,6,12,18,24), include.lowest = TRUE, labels = FALSE)
clv.time.possible.time.units <- function(){
return(c("hours","days", "weeks", "years"))
}
clv.time.has.holdout <- function(clv.time){
return([email protected] > 0)
}
# set.sample.periods ------------------------------------------------------------------------
#' @importFrom lubridate period
clv.time.set.sample.periods <- function(clv.time, tp.first.transaction, tp.last.transaction, user.estimation.end){
tp.estimation.start <- tp.first.transaction
if(!is.null(user.estimation.end)){
# specific end
if(is.numeric(user.estimation.end)){
# Have to cut of because lubridate does not allow non-integer period() (to add to tp.first.transaction)
# This is the same behavior as in clv.time.get.prediction.table
if(user.estimation.end %%1 != 0)
warning("The parameter estimation.split may not indicate partial periods. Digits after the decimal point are cut off.")
user.estimation.end <- as.integer(user.estimation.end)
tp.estimation.end <- tp.estimation.start +
clv.time.number.timeunits.to.timeperiod(clv.time=clv.time, user.number.periods=user.estimation.end)
}else{
tp.estimation.end <- clv.time.convert.user.input.to.timepoint(clv.time=clv.time,
user.timepoint=user.estimation.end)
}
# Need to be 2 periods because otherwise for days, holdout can be not on estimation.end but still be of length zero
# ie 2 periods to still have 1 as holdout
if(tp.estimation.end > tp.last.transaction-clv.time.number.timeunits.to.timeperiod(clv.time, 2L))
stop("Parameter estimation.split needs to indicate a point at least 2 periods before the last transaction!", call. = FALSE)
# + 1 day is the same for all because most fine-grained change that Date can do
tp.holdout.start <- tp.estimation.end + clv.time.epsilon(clv.time=clv.time)
tp.holdout.end <- tp.last.transaction
holdout.period.in.tu <- clv.time.interval.in.number.tu(clv.time,
interv=interval(start = tp.holdout.start,
end = tp.holdout.end))
}else{
# NULL: no specific end - until end of data (last transaction)
# **TODO: last transaction or full period where last transaction is in?
# tp.holdout.start and .end HAVE to be end of estimation period as this is used elsewhere!
# ie to ensure prediction.end (with clv.time.get.prediction.table) finds correct end if user gives NULL
tp.estimation.end <- tp.last.transaction
tp.holdout.start <- tp.estimation.end
tp.holdout.end <- tp.estimation.end
holdout.period.in.tu <- 0
}
estimation.period.in.tu <- clv.time.interval.in.number.tu(clv.time,
interv=interval(start = tp.estimation.start,
end = tp.estimation.end))
if(estimation.period.in.tu < 1)
stop("Parameter estimation.split needs to be at least 1 time.unit after the start!", call. = FALSE)
[email protected] <- tp.estimation.start
[email protected] <- tp.estimation.end
[email protected] <- tp.holdout.start
[email protected] <- tp.holdout.end
[email protected] <- holdout.period.in.tu
[email protected] <- estimation.period.in.tu
return(clv.time)
}
clv.time.expectation.periods <- function(clv.time, user.tp.end){
period.num <- NULL
# Table with each row representing a period (with period number, start and end dates)
# required when executing plot() to calculate the unconditional expectation and to
# roll-join repeat transactions on
# First expectation period
# Start: estimation.start
# End: End of time.unit
# => This period is often/mostly only partial
#
# All other expectation periods:
# Start: Beginning of time.unit
# End: End of time.unit
#
# Period number: How many periods from min(Start) until end of the period in this row
# First period
tp.first.period.start <- [email protected]
tp.second.period.start <- clv.time.floor.date(clv.time = clv.time, timepoint = tp.first.period.start) +
clv.time.number.timeunits.to.timeperiod(clv.time = clv.time,
user.number.periods = 1L)
if(!is.null(user.tp.end)){
if(is.numeric(user.tp.end)){
# Make periods integer because of lubridate::period limitations
# This is the same behavior as in clv.time.set.sample.periods
if(user.tp.end %% 1 != 0){
warning("The parameter prediction.end may not indicate partial periods. Digits after the decimal point are cut off.",
call. = FALSE)
user.tp.end <- as.integer(user.tp.end)
}
# holdout.start + periods - epsilon
# or: estimation.end + periods
# NOT including tp of next period, because expectation is done including tp.expectation.end
tp.expectation.end <- [email protected] +
clv.time.number.timeunits.to.timeperiod(clv.time = clv.time,
user.number.periods = user.tp.end) - clv.time.epsilon(clv.time=clv.time)
}else{
# datey
tp.expectation.end <- clv.time.convert.user.input.to.timepoint(clv.time = clv.time,
user.timepoint = user.tp.end)
}
}else{
# Is null
tp.expectation.end <- [email protected]
}
# Check that input is valid for expectation sequence ------------------------------------------------
# if(tp.expectation.end <= [email protected])
# check_err_msg("The prediction end cannot be before the end of the estimation!")
if(tp.expectation.end <= tp.first.period.start)
check_err_msg("The end cannot be before the start of the estimation period!")
if(clv.time.interval.in.number.tu(clv.time = clv.time,
interv = interval(start = tp.first.period.start,
end = tp.expectation.end)) <= 3){
check_err_msg("The expectation needs to be calculated across a minimum of 3 periods!")
}
# Table
# The implementation of the dyncov expectation function requires each timepoint
# to be the start of a covariate time unit
# Because the expectation refers to the period covered by [0, date_i] and only calculates until the beginning
# of the period (ie backwards and not until end of the period marked by date_i), the
# expectation.end has to be included by the last timepoint (ie last timepoint is after expectation.end)
# All timepoints in the table need to be exactly 1 time unit apart because the
# incremental values are derived from the cumulative expectation function (ie "what is gain from 1 period difference").
# Except the first to second period which may be apart less
#
# Periods
# First: expectation.start
# expectation is 0 but always include because transaction data is counted
#
# Second: ceiling_tu(expectation.start)
# If first and second are same (ie expectation.start falls on period start), only use one
#
# All afterwards: +1 TU of previous
#
# Last: minimum required date
# minimum required date: max(expectation.end, ceiling_tu(expectation.end))
#
# The time/time.units/period math to actually calculate this has too many edgecases
# Therefore use a naive, but correct approach:
# Add more periods from the start of first full period (from which there are only full time.units)
# until the expectation end is covered.
# (also there is no seq(from,to,by="tu") currently implemented in clv.time)
# First period to start with:
# Either expectation.start if on time unit or expectation.start+ceiling_tu(expectation.start)
vec.tp.expectation.date.i <- clv.time.ceiling.date(clv.time=clv.time,
timepoint = tp.first.period.start)
if(vec.tp.expectation.date.i != tp.first.period.start)
vec.tp.expectation.date.i <- c(tp.first.period.start, vec.tp.expectation.date.i)
# Add time units until expectation.end is covered
repeat{
# last currently in vec
tp.current.end <- max(vec.tp.expectation.date.i)
# Add +1 TU at the RHS of the vec
vec.tp.expectation.date.i <-
c(vec.tp.expectation.date.i,
tp.current.end + clv.time.number.timeunits.to.timeperiod(clv.time=clv.time,
user.number.periods = 1L))
# Is already covered?
if(max(vec.tp.expectation.date.i) >= tp.expectation.end){
break
}
}
# Make data.table, sort, add period.num (used throughout)
dt.expectation <- data.table(period.until = vec.tp.expectation.date.i)
setkeyv(dt.expectation, cols = "period.until")
dt.expectation[, period.num := seq.int(from=1, to=.N)]
return(dt.expectation)
}
# Prediction table
# period.first: First tp belonging to prediction period. First possible point after estimation.end.
# period.last: Last tp belonging to prediction period.
# period.length: Total length of prediction period, including period.first and period.last
#
# Table for length 0 prediction period:
# period.length = 0
# For this to hold, period.first = period.last.
# Because no prediction period exists, period.first has to be on estimation.end. If it was on +epsilon,
# the prediction period was already > 0 length
# Therefore, period.first = period.last = estimation.end
#
#' @include class_clv_time.R
#' @importFrom lubridate interval
clv.time.get.prediction.table <- function(clv.time, user.prediction.end){
# Explanation of "period"
# Transactions can happen on estimation end
# Start of 1 period forward hence only is 1 timepoint after estimation.end
# End of 1 period forward should, including the start and end itself, represent a single period
# => This is + 1 lubridate::period to estimation.end
# Result is the end of 1 period forward, if end is counted towards the period
# Example:
# Estimation end: Sun 2019-10-06
# 1 week forward
# First timepoint of 1 period: Mon 2019-10-07
# Last timepoint of full 1 period: Sun 2019-10-13
# In lubridate:: Have to use estimation.end
# ymd("2019-10-06")+lubridate::period(1, "weeks") = ymd("2019-10-13")
# First timepoint of 1st period: Mon 2019-10-07
# Last timepoint of full 2nd period: Sun 2019-10-20 (14d = 2weeks)
# ymd("2019-10-06")+lubridate::period(2, "weeks") = ymd("2019-10-20")
#
# If the timepoint on which to end is given, it is counted towards / included in the prediction period.
# The length/number of periods has to account for this and the fact that the period only starts after
# the estimation end.
# Example:
# Estimation end: Wed 2019-06-12
# Prediction end: Wed 2019-06-19
# -> Prediction period is (Wed 2019-06-12 - Wed 2019-06-19] = [Thu 2019-06-13 - Wed 2019-06-19]
# Length = 7d = 1 week
# In lubridate: have to use estimation.end
# as.numeric(as.period(interval(start = ymd("2019-06-12"), end = ymd("2019-06-19"))), "week") = 1
# Estimation end: Wed 2019-06-12
# Prediction end: Fr 2019-06-28 (16d)
# -> Prediction period is (Wed 2019-06-12 - Wed 2019-06-28] = [Thu 2019-06-13 - Wed 2019-06-28]
# Length = 16d = 2+2/7 week
# as.numeric(as.period(interval(start = ymd("2019-06-12"), end = ymd("2019-06-28"))), "week") = 2.285
#
fct.make.prediction.table <- function(period.last, period.length){
# If there is no prediction period:
# - period.last is estimation.end
# - there is no period.first (ie no first timepoint of the prediction period)
if(period.length == 0){
period.first <- period.last <- [email protected]
}else{
period.first <- [email protected] + clv.time.epsilon(clv.time = clv.time)
}
if(period.length < 0 | period.last < period.first){
stop("The prediction period need to end after the estimation period!")
}
return(data.table(period.first = period.first,
period.last = period.last,
period.length = period.length))
}
# Prediction end given:
# Timepoint: Until and including this point. Length can be inferred from this.
# Numeric: This many periods. Due to limitations in lubridate's periods (and the Date class which
# represents only full days), only whole periods can be added up (because what is 0.2345 weeks even?)
if(!is.numeric(user.prediction.end)){
if(!is.null(user.prediction.end)){
# Calcuate number of periods bases on given date
# parse date, char, posixt. then count number of timeunits
prediction.end.date <- clv.time.convert.user.input.to.timepoint(clv.time=clv.time,
user.timepoint=user.prediction.end)
}else{
# Whether there is a holdout sample is checked in the predict inputchecks
prediction.end.date <- [email protected]
}
# As explained above, estimation.end has to be used as the start of the interval
# to correctly count the number of periods which are [estimation.end+1TP, prediction.end.date]
number.of.time.units <- clv.time.interval.in.number.tu(clv.time=clv.time,
interv=interval(start = [email protected],
end = prediction.end.date))
return(fct.make.prediction.table(period.last = prediction.end.date,
period.length = number.of.time.units))
}else{
# prediction.end is numeric
# Make periods integer because of lubridate::period limitations
# This is the same behavior as in clv.time.set.sample.periods
if(user.prediction.end %% 1 != 0)
warning("The parameter prediction.end may not indicate partial periods. Digits after the decimal point are cut off.",
call. = FALSE)
number.of.time.units <- as.integer(user.prediction.end)
# Alternatives to cutting off digits / partial
# - Strictly allow only full periods (ie stop in inputchecks)
# - Use lubridate::duration and round to closest full timepoint (day/second)
# and recalculate exact length from this TP
# Timepoint that marks the end of this many periods
# As explained above, the periods have to be added to estimation.end
prediction.end.date <- [email protected] +
clv.time.number.timeunits.to.timeperiod(clv.time = clv.time,
user.number.periods = number.of.time.units)
return(fct.make.prediction.table(period.last = prediction.end.date,
period.length = number.of.time.units))
}
}
clv.time.sequence.of.covariate.timepoints <- function(clv.time, tp.start, tp.end){
Cov.Date <- period.offset <- NULL
# Marks all timepoints for which covariates are required if dyncov models should work between start and end.
# First covariate is required at floor_timeunit(tp.start), last covariate is required at
# floor_timeunit(tp.end), because the covariate always is supposed to influence the upcoming period.
tp.cov.start <- clv.time.floor.date(clv.time=clv.time, timepoint=tp.start)
tp.cov.end <- clv.time.floor.date(clv.time=clv.time, timepoint=tp.end)
# create with the sequence from tp.cov.start until and including tp.cov.end
# period.offset marks the offset, ie number of periods to add
num.offsets <- clv.time.interval.in.number.tu(clv.time = clv.time,
interv = interval(start = tp.cov.start, end = tp.cov.end))
# If the num.offsets falls inbetween, but this should not happen
num.offsets <- ceiling(num.offsets)
if(num.offsets <= 1) # Offset of 1 is 2 periods only
stop("Cannot create covariate date sequence for 2 or less periods!")
dt.cov.seq <- data.table(period.offset = seq.int(from=0, to=num.offsets, by = 1))
# by period.offset because lubridate::period() only accepts length 1 inputs
dt.cov.seq[, Cov.Date := tp.cov.start +
clv.time.number.timeunits.to.timeperiod(clv.time = clv.time,
user.number.periods = period.offset),
by = "period.offset"]
dt.cov.seq[, period.offset := NULL]
# Key and order by Dates
setkeyv(dt.cov.seq, "Cov.Date")
return(dt.cov.seq)
}
# Stubs to catch un-inplemented methods ---------------------------------------------------------
# ie "abstract" methods
setMethod("clv.time.epsilon", signature = "clv.time", function(clv.time){
stop("This method needs to be implemented by a subclass.")
})
# convert user given date/datetimes
setMethod("clv.time.convert.user.input.to.timepoint", signature = "clv.time", function(clv.time, user.timepoint){
stop("This method needs to be implemented by a subclass.")
})
setMethod("clv.time.interval.in.number.tu", signature = "clv.time", def = function(clv.time, interv){
stop("This method needs to be implemented by a subclass.")
})
setMethod("clv.time.number.timeunits.to.timeperiod", signature = "clv.time", function(clv.time, user.number.periods){
stop("This method needs to be implemented by a subclass.")
})
setMethod("clv.time.tu.to.ly", signature = "clv.time", function(clv.time){
stop("This method needs to be implemented by a subclass.")
})
setMethod("clv.time.floor.date", signature = "clv.time", function(clv.time, timepoint){
stop("This method needs to be implemented by a subclass.")
})
# only for pnbd dyncov createwalks
setMethod("clv.time.ceiling.date", signature = "clv.time", function(clv.time, timepoint){
stop("This method needs to be implemented by a subclass.")
})
setMethod("clv.time.format.timepoint", signature = "clv.time", function(clv.time, timepoint){
stop("This method needs to be implemented by a subclass.")
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time.R
|
#' Date based time-units
#'
#' Virtual base class for time units that need only whole day granularity.
#' This class processes time and dates at day level ignoring the time of day
#' and stores all timepoints using data type \code{Date}.
#'
#' @slot timepoint.estimation.start Single \code{Date} that stores the start of the estimation period.
#' @slot timepoint.estimation.end Single \code{Date} that stores the end of the estimation period.
#' @slot timepoint.holdout.start Single \code{Date} that stores the start of the holdout period.
#' @slot timepoint.holdout.end Single \code{Date} that stores the end of the holdout period.
#'
#'
#' @seealso
#' For time unit implementations based on this class: \linkS4class{clv.time.days}, \linkS4class{clv.time.weeks}, \linkS4class{clv.time.years}
#'
#' @include class_clv_time.R all_generics.R
#' @keywords internal
setClass("clv.time.date", contains = c("clv.time", "VIRTUAL"),
slots = c(
timepoint.estimation.start = "Date",
timepoint.estimation.end = "Date",
timepoint.holdout.start = "Date",
timepoint.holdout.end = "Date"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
timepoint.estimation.start = as.Date(character(0)),
timepoint.estimation.end = as.Date(character(0)),
timepoint.holdout.start = as.Date(character(0)),
timepoint.holdout.end = as.Date(character(0))))
# Because this class is VIRTUAL, no instance can be created and the
# usual approach of using a constructor function where an instance is created
# does not work.
# In case validity methods are added, the "initialize" method needs to be
# defined and omit calling the parent class initialize (see PR linked to issue #47)
setMethod("clv.time.format.timepoint", signature = signature(clv.time="clv.time.date"), definition = function(clv.time, timepoint){
return(format.Date(timepoint, "%Y-%m-%d"))
})
#' @importFrom lubridate days
setMethod("clv.time.epsilon", signature = signature(clv.time="clv.time.date"), function(clv.time){
# Alternative: return 1L
return(days(x = 1L))
})
# Parsing methods ------------------------------------------------------------------------
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.date",
user.timepoint="Date"), definition = function(clv.time, user.timepoint){
# Date is Date, nothing to do
return(user.timepoint)
})
#' @importFrom lubridate floor_date
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.date",
user.timepoint="POSIXlt"), definition = function(clv.time, user.timepoint){
message("The time of day stored in the provided POSIXlt object is ignored (cut off).")
return(as.Date.POSIXlt(user.timepoint))
})
#' @importFrom lubridate tz
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.date",
user.timepoint="POSIXct"), definition = function(clv.time, user.timepoint){
message("The time of day stored in the provided data (of type POSIXct) is ignored (cut off).")
return(as.Date.POSIXct(x=user.timepoint, tz = tz(user.timepoint)))
})
#' @importFrom lubridate parse_date_time
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.date",
user.timepoint="character"), definition = function(clv.time, user.timepoint){
dates <- as.Date.POSIXct(parse_date_time(x=user.timepoint,
orders = [email protected],
tz="UTC",
quiet = TRUE),
tz = "UTC")
if(anyNA(dates))
stop("The provided date failed to parse with the previously set date.format!", call. = FALSE)
return(dates)
})
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.date",
user.timepoint="ANY"), definition = function(clv.time, user.timepoint){
# None of these cases
stop("The provided data is in an unknown format! Only Date, POSIXct/lt, and character are accepted!", call. = FALSE)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_date.R
|
#' POSIXct based time-units
#'
#' Virtual base class for time units that define periods smaller than a single day.
#' This class processes time and dates at the single seconds level and
#' stores all timepoints using data type \code{POSIXct}.
#'
#' @slot timepoint.estimation.start Single \code{POSIXct} that stores the start of the estimation period.
#' @slot timepoint.estimation.end Single \code{POSIXct} that stores the end of the estimation period.
#' @slot timepoint.holdout.start Single \code{POSIXct} that stores the start of the holdout period.
#' @slot timepoint.holdout.end Single \code{POSIXct} that stores the end of the holdout period.
#' @slot timezone Single character vector indicating the enforced timezone when parsing inputs to timepoints.
#' Defaults to UTC, but may be overwritten by a subclass to enforce a different timezone than UTC.
#' @seealso For time unit implementations based on this class: \linkS4class{clv.time.hours}
#'
#'
#' @include class_clv_time.R all_generics.R
#' @keywords internal
setClass("clv.time.datetime", contains = c("clv.time", "VIRTUAL"),
slots = list(
# Use ct because dates in transaction data have to be ct
timepoint.estimation.start = "POSIXct",
timepoint.estimation.end = "POSIXct",
timepoint.holdout.start = "POSIXct",
timepoint.holdout.end = "POSIXct",
timezone = "character"),
# Prototype is labeled not useful anymore, but still recommended by Hadley / Bioc
prototype = list(
timezone = character(0),
timepoint.estimation.start = as.POSIXct(character(0)),
timepoint.estimation.end = as.POSIXct(character(0)),
timepoint.holdout.start = as.POSIXct(character(0)),
timepoint.holdout.end = as.POSIXct(character(0))))
# Because this class is VIRTUAL, no instance can be created and the
# usual approach of using a constructor function where an instance is created
# does not work.
# In case validity methods are added, the "initialize" method needs to be
# defined and omit calling the parent class initialize (see PR linked to issue #47)
#' @importFrom lubridate seconds
setMethod("clv.time.epsilon", signature = signature(clv.time="clv.time.datetime"), function(clv.time){
# Alternative: return 1L
return(seconds(x = 1L))
})
setMethod("clv.time.format.timepoint", signature = signature(clv.time="clv.time.datetime"), definition = function(clv.time, timepoint){
return(format.POSIXct(timepoint, "%Y-%m-%d %H:%M:%S"))
})
# Parsing methods ------------------------------------------------------------------------
# Only allow one timezone set in clv.time@timezone: UTC, because it does not switch DST
# Any diverging timezone is blocked when converting. Also, otherwise it would
# be difficult to determine at runtime from userinput which timezone to enforce
# (ie first, or transaction dates)
# Can be changed by a subclass which overwrites the slot timezone
#' @importFrom lubridate force_tz
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.datetime",
user.timepoint="Date"),
definition = function(clv.time, user.timepoint){
# Treat Date as if at midnight
# enforce by cuting off any time with floor_date
# Convert Date to POSIXct:
# - as.POSIXct adds time and converts to local timezone. Setting timezone with as.POSIXct
# does not seem to have any effect but always uses local/Sys timezone.
# - as_datetime(x, tz) does tz conversion but can lead to unacceptable date switches
# (because Date as treated as UTC).
# - as.POSIXlt always converts Dates to midnight UTC
# - force_tz does not work on Dates (obviously)
# => convert to Midnight UTC with as.lt + set tz to the desired one + convert to .ct of same tz
# Should not result in another timezone than UTC because Midtnight / beginning of day always exists, even on DST switch
# Manual setting is slightly faster than force_tz. But it really is the internal base as.POSIXct that is slow
tp.lt.midnight <- as.POSIXlt.Date(user.timepoint)
attr(tp.lt.midnight, "tzone") <- clv.time@timezone
return(as.POSIXct.POSIXlt(tp.lt.midnight, tz = clv.time@timezone))
})
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.datetime",
user.timepoint="POSIXlt"),
definition = function(clv.time, user.timepoint){
if(tz(user.timepoint) != clv.time@timezone)
stop(paste0("Only POSIXlt objects with timezone ", clv.time@timezone, " are accepted!"))
return(as.POSIXct.POSIXlt(x = user.timepoint, tz = clv.time@timezone))
})
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.datetime",
user.timepoint="POSIXct"),
definition = function(clv.time, user.timepoint){
if(tz(user.timepoint) != clv.time@timezone)
stop(paste0("Only POSIXct objects with timezone ", clv.time@timezone, " are accepted!"))
# Correct timezone, can use directly
return(user.timepoint)
})
#' @importFrom lubridate parse_date_time
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.datetime",
user.timepoint="character"),
definition = function(clv.time, user.timepoint){
timepoints <- parse_date_time(x = user.timepoint,
orders = [email protected],
tz = clv.time@timezone,
quiet = TRUE)
if(anyNA(timepoints))
stop("The provided date and time failed to parse with the previously set date.format!", call. = FALSE)
return(timepoints)
})
setMethod("clv.time.convert.user.input.to.timepoint", signature = signature(clv.time="clv.time.datetime",
user.timepoint="ANY"),
definition = function(clv.time, user.timepoint){
# None of these cases
stop("The provided data is in an unknown format! Only Date, POSIXct/lt, and character are accepted!", call. = FALSE)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_datetime.R
|
#' Time unit representing a single Day
#'
#' @template template_clvdate_description
#'
#' @seealso \linkS4class{clv.time}
#' @seealso \linkS4class{clv.time.date}
#'
#' @include class_clv_time.R class_clv_time_date.R all_generics.R
#' @keywords internal
setClass("clv.time.days", contains = "clv.time.date")
# Constructor
# Cannot set estimation/holdout start/end here because for this it needs transaction dates, which first
# need to be converted to dates and then returned to the transaction data table
#' @importFrom methods new
clv.time.days <- function(time.format){
return(new("clv.time.days",
time.format = time.format,
name.time.unit = "Days"))
}
#' @importFrom lubridate period
setMethod("clv.time.number.timeunits.to.timeperiod", signature = signature(clv.time="clv.time.days"), function(clv.time, user.number.periods){
# with periods not integers, in case its added to posix
return(period(num=as.integer(user.number.periods), units="days"))
})
#' @importFrom lubridate time_length
setMethod("clv.time.interval.in.number.tu", signature = signature(clv.time="clv.time.days"), function(clv.time, interv){
return(time_length(interv, unit = "days"))
})
setMethod("clv.time.tu.to.ly", signature = signature(clv.time="clv.time.days"), function(clv.time){
return("Daily")
})
#' @importFrom lubridate floor_date
setMethod("clv.time.floor.date", signature = signature(clv.time="clv.time.days"), function(clv.time,timepoint){
return(floor_date(x=timepoint, unit="days"))
})
#' @importFrom lubridate ceiling_date
setMethod("clv.time.ceiling.date", signature = signature(clv.time="clv.time.days"), function(clv.time,timepoint){
return(ceiling_date(x=timepoint, unit="days", change_on_boundary = TRUE))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_days.R
|
#' Time unit representing a single hour
#'
#' @include class_clv_time.R class_clv_time_datetime.R all_generics.R
#' @keywords internal
setClass("clv.time.hours", contains = "clv.time.datetime")
# Constructor
# Cannot set estimation/holdout start/end here because for this it needs transaction dates, which first
# need to be converted to dates and then returned to the transaction data table
#' @importFrom methods new
clv.time.hours <- function(time.format){
return(new("clv.time.hours",
time.format = time.format,
timezone = "UTC",
name.time.unit = "Hours"))
}
#' @importFrom lubridate period
setMethod("clv.time.number.timeunits.to.timeperiod", signature = signature(clv.time="clv.time.hours"), function(clv.time, user.number.periods){
return(period(num=as.integer(user.number.periods), units="hours"))
})
#' @importFrom lubridate time_length
setMethod("clv.time.interval.in.number.tu", signature = signature(clv.time="clv.time.hours"), function(clv.time, interv){
return(time_length(interv, unit = "hours"))
})
setMethod("clv.time.tu.to.ly", signature = signature(clv.time="clv.time.hours"), function(clv.time){
return("Hourly")
})
#' @importFrom lubridate floor_date
setMethod("clv.time.floor.date", signature = signature(clv.time="clv.time.hours"), function(clv.time,timepoint){
return(floor_date(x=timepoint, unit="hours"))
})
#' @importFrom lubridate ceiling_date
setMethod("clv.time.ceiling.date", signature = signature(clv.time="clv.time.hours"), function(clv.time,timepoint){
return(ceiling_date(x=timepoint, unit="hours", change_on_boundary = TRUE))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_hours.R
|
#' Time unit representing a single Week
#'
#' @template template_clvdate_description
#'
#' @include class_clv_time.R class_clv_time_date.R all_generics.R
#' @keywords internal
setClass("clv.time.weeks", contains = "clv.time.date")
# Constructor
# Cannot set estimation/holdout start/end here because for this it needs transaction dates, which first
# need to be converted to dates and then returned to the transaction data table
#' @importFrom methods new
clv.time.weeks <- function(time.format){
return(new("clv.time.weeks",
time.format = time.format,
name.time.unit = "Weeks"))
}
#' @importFrom lubridate period
setMethod("clv.time.number.timeunits.to.timeperiod", signature = signature(clv.time="clv.time.weeks"), function(clv.time, user.number.periods){
# with periods not integers, in case its added to posix
return(period(num=as.integer(user.number.periods), units="weeks"))
})
#' @importFrom lubridate time_length
setMethod("clv.time.interval.in.number.tu", signature = signature(clv.time="clv.time.weeks"), function(clv.time, interv){
return(time_length(interv, unit = "weeks"))
})
setMethod("clv.time.tu.to.ly", signature = signature(clv.time="clv.time.weeks"), function(clv.time){
return("Weekly")
})
#' @importFrom lubridate floor_date
setMethod("clv.time.floor.date", signature = signature(clv.time="clv.time.weeks"), function(clv.time,timepoint){
# getOption is default, but be explicit and might change in the future
return(floor_date(x=timepoint, unit="weeks", week_start = getOption("lubridate.week.start", 7)))
})
#' @importFrom lubridate ceiling_date
setMethod("clv.time.ceiling.date", signature = signature(clv.time="clv.time.weeks"), function(clv.time,timepoint){
# getOption is default, but be explicit and might change in the future
return(ceiling_date(x=timepoint, unit="weeks", week_start = getOption("lubridate.week.start", 7), change_on_boundary = TRUE))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_weeks.R
|
#' Time unit representing a single Year
#'
#' @template template_clvdate_description
#'
#' @include class_clv_time.R class_clv_time_date.R all_generics.R
#' @keywords internal
setClass("clv.time.years", contains = "clv.time.date")
# Constructor
# Cannot set estimation/holdout start/end here because for this it needs transaction dates, which first
# need to be converted to dates and then returned to the transaction data table
#' @importFrom methods new
clv.time.years <- function(time.format){
return(new("clv.time.years",
time.format = time.format,
name.time.unit = "Years"))
}
#' @importFrom lubridate period
setMethod("clv.time.number.timeunits.to.timeperiod", signature = signature(clv.time="clv.time.years"), function(clv.time, user.number.periods){
# with periods, years have different length
return(period(num=as.integer(user.number.periods), units="years"))
})
#' @importFrom lubridate time_length
setMethod("clv.time.interval.in.number.tu", signature = signature(clv.time="clv.time.years"), function(clv.time, interv){
return(time_length(interv, unit = "years"))
})
setMethod("clv.time.tu.to.ly", signature = signature(clv.time="clv.time.years"), function(clv.time){
return("Yearly")
})
#' @importFrom lubridate floor_date
setMethod("clv.time.floor.date", signature = signature(clv.time="clv.time.years"), function(clv.time,timepoint){
return(floor_date(x=timepoint, unit="years"))
})
#' @importFrom lubridate ceiling_date
setMethod("clv.time.ceiling.date", signature = signature(clv.time="clv.time.years"), function(clv.time,timepoint){
return(ceiling_date(x=timepoint, unit="years", change_on_boundary = TRUE))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/class_clv_time_years.R
|
clv.template.controlflow.estimate <- function(clv.fitted,
start.params.model,
optimx.args,
verbose,
...){
# input checks ------------------------------------------------------------------------------------------
# checks for model first
clv.controlflow.estimate.check.inputs(clv.fitted=clv.fitted, start.params.model=start.params.model,
optimx.args=optimx.args, verbose=verbose, ...)
clv.model.check.input.args([email protected], clv.fitted=clv.fitted, start.params.model=start.params.model,
optimx.args=optimx.args, verbose=verbose, ...)
# Store user input for estimation ----------------------------------------------------------------------------
clv.fitted <- clv.controlflow.estimate.put.inputs(clv.fitted=clv.fitted, verbose=verbose, ...)
[email protected] <- clv.model.put.estimation.input([email protected], ...)
# Generate start params ---------------------------------------------------------------------------------------
start.params.all <- clv.controlflow.estimate.generate.start.params(clv.fitted=clv.fitted, start.params.model=start.params.model, verbose=verbose, ...)
# prepare optimx args ------------------------------------------------------------------------------------------
# model needed to prepare LL part of optimx args
prepared.optimx.args <- clv.controlflow.estimate.prepare.optimx.args(clv.fitted=clv.fitted, start.params.all=start.params.all)
prepared.optimx.args <- clv.model.prepare.optimx.args([email protected], clv.fitted=clv.fitted, prepared.optimx.args=prepared.optimx.args)
# Parameter names are removed by some optimx methods
# Save only after all parameters were prepared
prepared.optimx.args[["LL.param.names.to.optimx"]] <- names(prepared.optimx.args$par)
# No matter what the (model) defaults, the user arguments are written on top of what is generated
prepared.optimx.args <- modifyList(prepared.optimx.args, optimx.args, keep.null = FALSE)
# optimize LL --------------------------------------------------------------------------------------------------
# Just call optimx. Nothing model specific or similar is done.
if(verbose)
message("Starting estimation...")
res.optimx <- do.call(what = optimx, args = prepared.optimx.args)
if(verbose)
message("Estimation finished!")
# **FUTURE only: Extract results ---------------------------------------------------------------------------------
# Extract results needed to build the final object
# the final object is in a separate builder function because it might / will be exported to use
# together with prepare.only=T
# could move to separate function because of possible mcmc estimation (clv.controlflow.post.estimation.steps())
# Extracted: last used method's Hessian + coefs, kkt, LL value, ...
# # dont call controlflow.xx because possibly exported
# clv.post.optimization.processing(clv.pre.fitted, estimated.coefs, hessian=NULL)
# clv.post.fitting.processing(clv.pre.fitted, estimated.coefs, hessian=NULL)
# - set prediction parameters
# need to be set already to to some of the post estimation process steps such as running the LL again
# - model post processing steps
# Store results ------------------------------------------------------------------------------------------------
# also model-specifc storage and processing of optimx outputs
clv.fitted <- clv.controlflow.estimate.process.post.estimation(clv.fitted=clv.fitted, res.optimx=res.optimx)
clv.fitted <- clv.model.process.post.estimation([email protected], clv.fitted=clv.fitted, res.optimx=res.optimx)
# Set prediction params from coef()
# Do after process.post.estimate because needs optimx result stored
# Needed for predict/plot/fitted (incl when processing newdata) but set here already instead of in every of these
clv.fitted <- clv.controlflow.predict.set.prediction.params(clv.fitted=clv.fitted)
return(clv.fitted)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/clv_template_controlflow_estimate.R
|
clv.template.controlflow.pmf <- function(clv.fitted, x){
clv.controlflow.check.prediction.params(clv.fitted)
x <- sort(unique(x))
l.res.pmf <- lapply(x, function(i){
dt.pmf <- clv.model.pmf(clv.model = [email protected], clv.fitted = clv.fitted, x = i)
# measure.vars = NULL: all except id vars
return(melt(dt.pmf, id.vars="Id", measure.vars=NULL, variable.name="pmf", na.rm=FALSE))
})
return(dcast(rbindlist(l.res.pmf), Id~pmf))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/clv_template_controlflow_pmf.R
|
clv.template.controlflow.predict <- function(clv.fitted, verbose, user.newdata, ...){
# Check if can predict -----------------------------------------------------------------------------------------
# Cannot predict if there are any NAs in any of the prediction.params
clv.controlflow.check.prediction.params(clv.fitted = clv.fitted)
# Process Newdata -------------------------------------------------------------------------------------
# Because many of the following steps refer to the data stored in the fitted model,
# it first is replaced with newdata before any other steps are done
if(!is.null(user.newdata)){
# check newdata
clv.controlflow.check.newdata(clv.fitted = clv.fitted, user.newdata = user.newdata, ...)
# Replace data in model with newdata
# Deep copy to not change user input
[email protected] <- copy(user.newdata)
# Do model dependent steps of adding newdata
clv.fitted <- clv.model.process.newdata(clv.model = [email protected], clv.fitted=clv.fitted, verbose=verbose)
}
# Input checks ----------------------------------------------------------------------------------------
# Only after newdata replaced clv.data stored in clv.fitted because inputchecks use [email protected]
clv.controlflow.predict.check.inputs(clv.fitted=clv.fitted, verbose=verbose, ...)
# Prediction result table -----------------------------------------------------------------------------
dt.predictions <- clv.controlflow.predict.build.result.table(clv.fitted=clv.fitted, verbose=verbose, ...)
# Model prediction ------------------------------------------------------------------------------------
dt.predictions <- clv.model.predict(clv.model = [email protected], clv.fitted = clv.fitted,
dt.predictions = dt.predictions, verbose = verbose, ...)
setkeyv(dt.predictions, "Id")
# Actuals ---------------------------------------------------------------------------------------------
has.actuals <- clv.controlflow.predict.get.has.actuals(clv.fitted, dt.predictions = dt.predictions)
dt.predictions <- clv.controlflow.predict.add.actuals(clv.fitted = clv.fitted, dt.predictions = dt.predictions,
has.actuals = has.actuals, verbose = verbose, ...)
# post.process / add any additional steps -------------------------------------------------------------
# set col order etc
dt.predictions <- clv.controlflow.predict.post.process.prediction.table(clv.fitted = clv.fitted,
has.actuals = has.actuals,
dt.predictions = dt.predictions,
verbose = verbose, ...)
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.predictions[]
return(dt.predictions)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/clv_template_controlflow_predict.R
|
#' @title CDNOW dataset
#' @description
#' A dataset containing the entire purchase history up to the end of June 1998
#' of the cohort of 23,570 individuals who made their first-ever purchase at CDNOW in the first quarter
#' of 1997.
#'
#' @format A \code{data.table} with 6696 rows and 4 variables:
#' \describe{
#' \item{\code{Id}}{Customer Id}
#' \item{\code{Date}}{Date of purchase}
#' \item{\code{CDs}}{Amount of CDs purchased}
#' \item{\code{Price}}{Price of purchase}
#' }
#'
#' @usage data("cdnow")
#' @docType data
#' @keywords datasets
#' @references
#' Fader, Peter S. and Bruce G.,S. Hardie, (2001), "Forecasting Repeat Sales at CDNOW:
#' A Case Study," Interfaces, 31 (May-June), Part 2 of 2, p94-107.
"cdnow"
#' @title Apparel Retailer Dataset
#'
#' @description
#' This is a simulated dataset containing the entire purchase history of customers made their first purchase at an
#' apparel retailer on January 3rd 2005. In total the dataset contains 250 customers who made
#' 3648 transactions between January 2005 and mid July 2006.
#'
#' @format A \code{data.table} with 2353 rows and 3 variables:
#' \describe{
#' \item{\code{Id}}{Customer Id}
#' \item{\code{Date}}{Date of purchase}
#' \item{\code{Price}}{Price of purchase}
#' }
#'
#' @usage data("apparelTrans")
#' @docType data
#' @keywords datasets
"apparelTrans"
#' @name apparelStaticCov
#' @title Time-invariant Covariates for the Apparel Retailer Dataset
t
#' @description
#' This simulated data contains additional demographic information on all 250 customers in the
#' "apparelTrans" dataset. This information can be used as time-invariant covariates.
#'
#' @format A \code{data.table} with 250 rows and 3 variables:
#'
#' \describe{
#' \item{Id}{Customer Id}
#' \item{Gender}{0=male, 1=female}
#' \item{Channel}{Acquisition channel: 0=online, 1=offline}
#' }
#'
#' @docType data
#' @keywords datasets
#' @usage data("apparelStaticCov")
"apparelStaticCov"
#' @name apparelDynCov
#' @title Time-varying Covariates for the Apparel Retailer Dataset
#' @description
#' This simulated data contains direct marketing information on all 250 customers in the "apparelTrans" dataset.
#' This information can be used as time-varying covariates.
#'
#' @format A data.table with 20500 rows and 5 variables
#' \describe{
#' \item{Id}{Customer Id}
#' \item{Cov.Date}{Date of contextual factor}
#' \item{Marketing}{Direct marketing variable: number of times a customer was contacted with direct marketing in this time period}
#' \item{Gender}{0=male, 1=female}
#' \item{Channel}{Acquisition channel: 0=online, 1=offline}
#' }
#'
#' @keywords datasets
#' @usage data("apparelDynCov")
#' @docType data
"apparelDynCov"
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/data.R
|
# params_i: parameters and first transaction for each customer. passed on to fct.expectation.
# dates.periods: at which dates to calculate expectation
# fct.expectation: function to calculate expectation value at point t
DoExpectation <- function(dt.expectation.seq, params_i, fct.expectation, clv.time){
period.num <- date.first.actual.trans <- expectation <- expectation_i <- date.period <- number.of.tu <- t_i <- period.until.trans <- NULL
# Table with expectation periods
# period.until: Here we stand, only customers already alive here
# For every period in table, calculate expectation
for(p.no in dt.expectation.seq$period.num){
period.until <- dt.expectation.seq[period.num == p.no, period.until]
# Remove who is not alive yet
alive.params_i <- params_i[date.first.actual.trans <= period.until]
# calculate model prediction for this customers at point t
# t_i: Individual time alive until the beginning of this period (ie first trans to period.until)
alive.params_i[, t_i := clv.time.interval.in.number.tu(clv.time = clv.time,
interv = interval(start = date.first.actual.trans,
end = period.until))]
# Calculate expectation for each alive customer
alive.params_i[, expectation_i := fct.expectation(.SD)]
# expectation is sum of all single customer's expectation
dt.expectation.seq[period.num == p.no , expectation := alive.params_i[, sum(expectation_i, na.rm=TRUE)]]
}
# Transform cumulative back to incremental ------------------------------------------
# First entry is already correct because for k=1: incremental == cumulative
# All afterwards are the incremental differences
# -> Subtract previous element, for first subtract 0
# Same as: [first, diff(expectation)]
dt.expectation.seq[order(period.until, decreasing = FALSE), expectation := expectation - c(0, expectation[seq(from=1, to=.N-1)])]
return(dt.expectation.seq)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_DoExpectation.R
|
# function to to check if there are error messages and print+stop them
check_err_msg <- function(err.msg){
if(length(err.msg) > 0)
stop(c("\n",paste0(err.msg, sep="\n")),call. = FALSE)
}
.check_user_data_single_boolean <- function(b, var.name){
err.msg <- c()
if(!is.logical(b))
return(paste0("The parameter ", var.name, " needs to be of type logical (True/False)!"))
if(length(b)>1)
err.msg <- c(err.msg, paste0("The parameter ", var.name, " can only contain 1 element!"))
if(anyNA(b))
err.msg <- c(err.msg, paste0("The parameter ", var.name, " cannot be NA!"))
return(err.msg)
}
.check_userinput_charactervec <- function(char, var.name, n){
err.msg <- c()
if(!is.character(char))
return(paste0(var.name, " needs to be of type character (text)!"))
if(length(char) != n)
err.msg <- c(err.msg, paste0(var.name, " must contain exactly ", n, " element(s)!"))
if(anyNA(char))
err.msg <- c(err.msg, paste0(var.name, " may not contain any NA!"))
if(length(err.msg) == 0){
# is non empty vec, but check is not no text ("")
if(any(sapply(char, nchar) == 0)){
err.msg <- c(err.msg, paste0(var.name, " may not contain elements which are empty text!"))
}
}
return(err.msg)
}
.convert_userinput_dataid <- function(id.data){
return(as.character(id.data))
}
.check_userinput_matcharg <- function(char, choices, var.name){
if(is.null(char))
return(paste0("Parameter ",var.name, " cannot be NULL!"))
if(!is.character(char))
return(paste0(var.name, " needs to be of type character (text)!"))
err.msg <- c()
if(anyNA(char))
err.msg <- c(err.msg, paste0(var.name, " may not contain any NA!"))
# use pmatch to match the input against the possible choices
# match.arg would throw undescriptive error if not found
# this also accounts for empty texts
if(length(err.msg) == 0) # may fail ungracefully if inproper input
if(!all(pmatch(x=tolower(char), table=tolower(choices), nomatch = FALSE)))
err.msg <- c(err.msg, paste0("Please choose one of the following values for ",var.name,": ",
paste(choices, collapse = ", "), "!"))
return(err.msg)
}
.check_userinput_integer_vector <- function(vec.int, var.name){
if(is.null(vec.int))
return(paste0(var.name, " cannot be NULL!"))
if(anyNA(vec.int))
return(paste0(var.name, " cannot contain any NA values!"))
if(length(vec.int) == 0)
return(paste0(var.name, " has to contain values!"))
if(!is.numeric(vec.int))
return(paste0(var.name, " has to be a vector of integer numbers!"))
# all integers
if(!all(vec.int == as.integer(vec.int))){
return(paste0(var.name, " must be all integer numbers!"))
}
return(c())
}
check_userinput_datanocov_transbins <- function(trans.bins, count.repeat.trans){
err.msg <- .check_userinput_integer_vector(vec.int=trans.bins, var.name="trans.bins")
if(length(err.msg))
return(err.msg)
if(count.repeat.trans){
if(any(trans.bins < 0))
return("trans.bins has to be a vector of positive integers (>=0)!")
}else{
if(any(trans.bins < 1))
return("trans.bins has to be a vector of strictly positive integers (>=1)!")
}
return(c())
}
check_userinput_datanocov_ids <- function(Ids){
err.msg <- c()
if(is.null(Ids)){
return(err.msg)
}
if(anyNA(Ids)){
return("Ids may not contain any NA!")
}
if(!is.numeric(Ids) & !is.character(Ids)){
return("Ids has to be a single numeric value or a character vector!")
}
if(is.numeric(Ids)){
err.msg <- c(err.msg, .check_user_data_single_numeric(Ids, var.name = 'Ids'))
# if(any(!is.finite(Ids))){
# return("Ids may not contain any non-finite elements if numeric!")
# }
# if(length(Ids) != 1){
# return("Ids has to be of length 1 if numeric!")
# }
if(!all(Ids > 0)){
err.msg <- c(err.msg, "Ids has to be strictly positive (>0)")
}
}
if(is.character(Ids)){
if(length(Ids) == 0){
err.msg <- c(err.msg, "Ids has to contain at least 1 element if character vector")
}else{
if(any(nchar(Ids) == 0)){
err.msg <- c(err.msg, "Ids may not be empty text")
}
}
}
return(err.msg)
}
check_userinput_datanocov_columnname <- function(name.col, data){
if(is.null(name.col))
return("Column names cannot be NULL!") #return already as NULL will break code
err.msg <- .check_userinput_charactervec(char=name.col, var.name="Column names", n=1)
# check if column is exactly in data
if(length(err.msg) == 0)
if(!(name.col %in% colnames(data)))
err.msg <- c(err.msg, paste0("The column named \"", name.col, "\" could not be found in the data!"))
return(err.msg)
}
check_userinput_datanocov_timeunit <- function(time.unit){
if(is.null(time.unit))
return("Time unit cannot be NULL!") #return already as NULL will break code
err.msg <- .check_userinput_charactervec(char=time.unit, var.name = "time.unit", n=1)
# use pmatch to match the input againts the possible time units
# this also accounts for empty texts
# use tolower to allow capital/mixed spelling
# match.arg would throw undescriptive error if not found
if(length(err.msg) == 0) # may fail ungracefully if inproper input
if(!(pmatch(x=tolower(time.unit), table=tolower(clv.time.possible.time.units()), nomatch = FALSE)))
err.msg <- c(err.msg, paste0("Please choose one of the following time units: ", paste(clv.time.possible.time.units(), collapse = ", "), "!"))
return(err.msg)
}
# Check type
# estimation.split can be
# - NULL: no split
# - char: convert to date
# - date: split here
# - numeric: split after this many number of time units
#' @importFrom lubridate is.POSIXt is.Date parse_date_time
check_userinput_datanocov_estimationsplit <- function(estimation.split, date.format){
if(is.null(estimation.split))
return(c())
#cannot use .single_character helper to check because may be numeric or date
if(length(estimation.split) != 1)
return("estimation.split must contain exactly one single element!")
if(anyNA(estimation.split))
return("estimation.split may not contain any NAs!")
if(!is.character(estimation.split) & !is.numeric(estimation.split) &
!is.Date(estimation.split) & !is.POSIXt(estimation.split))
return("estimation.split needs to either of type character, numeric, or Date (Date or POSIXt)")
if(is.character(estimation.split))
if(anyNA(parse_date_time(x=estimation.split, quiet=TRUE, orders=date.format)))
return("Please provide a valid estimation.split to that can be converted with the given date.format!")
# Whether estimation.split lies in data will only be checked when it is converted!
return(c())
}
#' @importFrom lubridate is.POSIXct
check_userinput_datanocov_datatransactions <- function(data.transactions.dt, has.spending){
Id <- Date <- Price <- NULL
err.msg <- c()
if(!is.data.table(data.transactions.dt))
return("Something went wrong. Transactions could not be converted to data.table!")
if(nrow(data.transactions.dt) == 0)
return("Transactions may not be empty!")
if(any(!c("Id", "Date") %in% colnames(data.transactions.dt)))
return("The column names could not be set in the transaction data!")
# Id can be char, number, or factor
err.msg <- c(err.msg, check_userinput_data_id(dt.data = data.transactions.dt, name.id = "Id", name.var = "transaction data"))
err.msg <- c(err.msg, check_userinput_data_date(dt.data = data.transactions.dt, name.date = "Date", name.var = "transaction data"))
# Price can only be numeric
if(has.spending){
if(!(data.transactions.dt[,is.numeric(Price)]))
err.msg <- c(err.msg, "The Price column in the transaction data needs to be of type \"numeric\"!")
if(data.transactions.dt[, anyNA(Price)])
err.msg <- c(err.msg, "The \"Price\" column in the transaction data contains NAs!")
}
# No NAs
if(data.transactions.dt[, anyNA(Id)])
err.msg <- c(err.msg, "The \"Id\" column in the transaction data contains NAs!")
if(data.transactions.dt[, anyNA(Date)])
err.msg <- c(err.msg, "The \"Date\" column in the transaction data contains NAs!")
return(err.msg)
}
check_userinput_datanocov_namescov <- function(names.cov, data.cov.df, name.of.covariate){
err.msg <- c()
if(is.null(names.cov))
return(paste0("Covariate names for the ",name.of.covariate," covariate may not be NULL!"))
if(!is.character(names.cov))
return(paste0("Covariate names for the ",name.of.covariate," covariate have to be character vector!"))
if(length(names.cov) < 1)
return(paste0("There needs to be at least one covariate name for the ",name.of.covariate," covariate!"))
if(anyNA(names.cov))
err.msg <- c(err.msg, "Column names may not contain any NAs!")
for(n in names.cov)
if(!(n %in% colnames(data.cov.df)))
err.msg <- c(err.msg, paste0("The column named ", n, " could not be found in the ",name.of.covariate," covariate data!"))
if(length(names.cov) != length(unique(names.cov)))
err.msg <- c(err.msg, paste0("Column names for the ",name.of.covariate," covariate may not contain any duplicates!"))
return(err.msg)
}
check_userinput_datanocov_datastaticcov <- function(clv.data, dt.data.static.cov, names.cov, name.of.covariate){
err.msg <- c()
# Cov data checks ------------------------------------------------------------------------
# the cov data itself needs to be numeric, char or factor
if(dt.data.static.cov[, !all(sapply(.SD, is.numeric) | sapply(.SD, is.character) |sapply(.SD, is.factor)),
.SDcols = names.cov])
err.msg <- c(err.msg, paste0("All ",name.of.covariate," covariate data (except Id) needs to be of type numeric, character, or factor!"))
# Categorical cov data cannot be only a single category
if(dt.data.static.cov[, any(sapply(.SD, uniqueN) == 1), .SDcols = names.cov])
err.msg <- c(err.msg, "Covariate variables with only a single category cannot be used as covariates.")
# Id checks ----------------------------------------------------------------------------
# Exactly 1 cov per customer
dt.uniq.id <- unique([email protected][, "Id"])
if(nrow(dt.uniq.id) != nrow(dt.data.static.cov))
err.msg <- c(err.msg, paste0("Every Id has to appear exactly once in the ", name.of.covariate ," covariate data!"))
# every Id in cbs needs to be in covariate Id
# use data.table::fsetdiff which returns a data.table
if(nrow(fsetdiff(dt.uniq.id, dt.data.static.cov[, "Id"])) > 0)
err.msg <- c(err.msg, paste("Every Id in the transaction data needs to be in the ",name.of.covariate," covariate data as well!"))
# No NAs in Id and relevant cov data
if(dt.data.static.cov[, anyNA(.SD), .SDcols=c("Id", names.cov)])
err.msg <- c(err.msg, paste0("The ",name.of.covariate," covariate data may not contain any NAs!"))
return(err.msg)
}
check_userinput_data_id <- function(dt.data, name.id, name.var){
err.msg <- c()
if(!dt.data[, (sapply(.SD, is.numeric) | sapply(.SD, is.character) | sapply(.SD, is.factor)), .SDcols=name.id])
err.msg <- c(paste0("The Id column in the ",name.var," needs to be of type \"numeric\", \"character\", or \"factor\"!"))
return(err.msg)
}
check_userinput_data_date <- function(dt.data, name.date, name.var){
err.msg <- c()
# Date can be Date, character, or Posixct (but not posixlt because of data.table!)
if(!dt.data[, (sapply(.SD, is.Date) | sapply(.SD, is.character) | sapply(.SD, is.POSIXct)), .SDcols=name.date])
err.msg <- c(paste0("The Date column in the ",name.var," needs to be of type \"Date\", \"character\", or \"POSIXct\"!"))
return(err.msg)
}
# The cov data is already cut to range when given
check_userinput_datadyncov_datadyncovspecific <- function(dt.data.dyn.cov, dt.required.dates, clv.time, dt.required.ids, names.cov, name.of.covariate){
Cov.Date <- Id <- Max.Cov.Date <- is.long.enough <- Min.Cov.Date <- N <- has.req.dates <- num.dates <- NULL
# Better be sure
setkeyv(dt.data.dyn.cov, cols = c("Id", "Cov.Date"))
err.msg <- c()
# Cov data checks -------------------------------------------------------------------------------
# Categorical cov data cannot be only a single category
if(dt.data.dyn.cov[, any(sapply(.SD, uniqueN) == 1), .SDcols = names.cov])
err.msg <- c(err.msg, "Covariate variables with only a single category cannot be used as covariates.")
# NA checked outside / before
# the cov data itself needs to be numeric, char or factor
if(dt.data.dyn.cov[, !all(sapply(.SD, is.numeric) | sapply(.SD, is.character) |sapply(.SD, is.factor)),
.SDcols = names.cov])
err.msg <- c(err.msg, paste0("All ",name.of.covariate," covariate data (except Id and Date) needs to be of type numeric, character, or factor!"))
# Id checks ------------------------------------------------------------------------------------
# every Id needs to be in covariate Id
if(nrow(fsetdiff(dt.required.ids, dt.data.dyn.cov[, "Id"])) > 0)
err.msg <- c(err.msg, paste0("Every Id in the transaction data needs to be in the ",name.of.covariate," covariate data as well!"))
# Date checks -----------------------------------------------------------------------------------
# Last date, for every Id:
# - the last Date is at least until the specified end
# - the last Date is the same for all Ids
# - the first Date is the same for all Ids
# - the number of Dates is the same for all customers
# - there are no other dates than the required ones
# last.cov.date.per.cust <- dt.data.dyn.cov[, list("Max.Cov.Date" = max(Cov.Date)), by=Id]
# Check that every customer has a cov for exactly the required dates
# there are no other dates than the required ones, across all customers
# it only concerns the relevant range because the data was cut to this range
# (all=FALSE = does not need to have the required dates multiple times)
if(!fsetequal(dt.data.dyn.cov[, "Cov.Date"],
dt.required.dates,
all=FALSE))
err.msg <- c(err.msg, paste0("There need to be ",tolower(clv.time.tu.to.ly(clv.time))," covariate data exactly from ",
clv.time.format.timepoint(clv.time=clv.time, timepoint=dt.required.dates[, min(Cov.Date)]),
" until ",
clv.time.format.timepoint(clv.time=clv.time, timepoint=dt.required.dates[, max(Cov.Date)])))
# It can still be that some customers dont have all these dates, ie have some dates missing
# (even only have 1 ) and can still have duplicated
# - check that everybody has the same number of Dates
# (= together with the last test this implies that these are the required Dates)
# - check that everybody has every Date only once
# Everybody has the correct number of Dates.
# all() because could be vector of different values from unique()
if(!all(dt.data.dyn.cov[, list(num.dates = uniqueN(Cov.Date)), by="Id"][, unique(num.dates)] == nrow(dt.required.dates)))
err.msg <- c(err.msg, paste0("All customers in the ",name.of.covariate,
" covariate data need to have the same number of Dates: ", nrow(dt.required.dates)))
# Everybody has the correct number of observations
# Needed as otherwise can have duplicate observations
# all() because could be vector of different values from unique()
if(!all(dt.data.dyn.cov[, .N, by="Id"][, unique(N)] == nrow(dt.required.dates)))
err.msg <- c(err.msg, paste0("All customers in the ",name.of.covariate,
" covariate data need to have the same number of Dates: ", nrow(dt.required.dates)))
return(err.msg)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_clvdata_inputchecks.R
|
.check_user_data_single_numeric <- function(n, var.name){
err.msg <- c()
if(!is.numeric(n))
return(paste0(var.name, " has to be numeric!"))
if(length(n)!=1)
err.msg <- c(err.msg, paste0(var.name," has to be exactly 1 single number!"))
if(anyNA(n))
err.msg <- c(err.msg, paste0(var.name," may not be NA!"))
if(any(!is.finite(n)))
err.msg <- c(err.msg, paste0(var.name," may not contain any non-finite items!"))
return(err.msg)
}
check_user_data_integer_vector_greater0 <- function(vec, var.name){
err.msg <- .check_userinput_integer_vector(vec.int=vec, var.name=var.name)
if(length(err.msg))
return(err.msg)
if(any(vec < 0)){
return(paste0(var.name, " has to be a vector of all positive integer numbers (>=0)!"))
}
return(c())
}
# Can be
# - NULL (= all in holdout)
# - numeric (=this many periods)
# - char (convertable!)
# - Date (posixt, Date)
#' @importFrom lubridate is.Date is.POSIXt
#' @importFrom methods is
check_user_data_predictionend <- function(clv.fitted, prediction.end){
# NULL is valid input to prediction end
if(is.null(prediction.end))
return(c())
if(length(prediction.end) > 1)
return("prediction.end can only be of length 1!")
if(anyNA(prediction.end))
return("prediction.end may not contain any NAs!")
if(!is.numeric(prediction.end))
if(!is.character(prediction.end))
if(!is.Date(prediction.end))
if(!is.POSIXt(prediction.end))
return("prediction.end needs to be either of type character, numeric, or Date (Date or POSIXct/lt)!")
# dont check for conversion with date.format because not needed and
# will often fail (no time in date.format because only daily data)
if(is.POSIXt(prediction.end))
return(c())
# clv.fitted or clv.data object (to check prediction.end in plot())
if(is(clv.fitted, "clv.fitted"))
clv.time <- [email protected]@clv.time
else
clv.time <- [email protected]
# if its a char or Date -> see if can convert
if(is.character(prediction.end))
if(anyNA( parse_date_time(x=prediction.end, orders = [email protected])))
return("Please provide prediction.end in a format that can be parsed with the set date.format when creating the object!")
# Whether the date itself is ok will be checked when converting!
return(c())
}
check_user_data_startparams <- function(start.params, vector.names, param.names){
err.msg <- c()
if(is.null(start.params))
return(err.msg)
if(anyNA(start.params))
err.msg <- c(err.msg, paste0("There may be no NAs in the ", param.names,"s!"))
if(!is.numeric(start.params))
err.msg <- c(err.msg, paste0("Please provide a numeric vector as ",param.names,"s!"))
if(is.null(names(start.params)))
err.msg <- c(err.msg, paste0("Please provide a named vector as ",param.names,"s!"))
# check that every name is not only "" (ie some are unnamed)
for(n in names(start.params))
if(nchar(n) < 1)
err.msg <- c(err.msg, paste0("Please provide names for every parameter in the ",param.names, "s!"))
# compare to parameters required by model/covariate
if(length(start.params) != length(vector.names))
err.msg <- c(err.msg, paste0("Please provide exactly ", length(vector.names), " ", param.names, "s named ", paste(vector.names, collapse = ", "), "!"))
# check that every required parameter is present as name
for(n in vector.names)
if(!(n %in% names(start.params)))
err.msg <- c(err.msg, paste0("Please provide the ",param.names, " for ", n, "!"))
return(err.msg)
}
check_user_data_startparamscov <- function(start.params.cov, names.params.cov, name.of.cov){
return(check_user_data_startparams(start.params = start.params.cov, vector.names = names.params.cov,
param.names = paste0(name.of.cov, " covariate start parameter")))
}
check_user_data_namescov_reduce <- function(names.cov, data.cov.dt, name.of.cov){
err.msg <- c()
if(is.null(names.cov))
return(c()) #return("Covariate names may not be NULL")
if(!is.character(names.cov))
return(paste0("Covariate names for ", name.of.cov," covariates must be an unnamed character vector!"))
if(!is.null(names(names.cov)))
err.msg <- c(err.msg, paste0("Covariate names for ", name.of.cov," covariates should be provided as named vector!"))
if(anyNA(names.cov))
err.msg <- c(err.msg, paste0("There may be no NAs in the covariate names in the ", name.of.cov," covariates!"))
for(n in names.cov)
if(!(n %in% colnames(data.cov.dt)))
err.msg <- c(err.msg, paste0("The column named ", n, " could not be found in the ",name.of.cov," covariate data!"))
if(length(names.cov) != length(unique(names.cov)))
err.msg <- c(err.msg, "Every covariate name for ",name.of.cov," covariates may only appear once!")
return(err.msg)
}
check_user_data_reglambdas <- function(reg.lambdas){
err.msg <- c()
if(is.null(reg.lambdas))
return(err.msg)
if(!is.numeric(reg.lambdas))
return("The regularization lambdas have to be a numeric vector!")
if(anyNA(reg.lambdas))
return("The regularization lambdas may not contain any NAs!")
if(any(reg.lambdas < 0))
err.msg <- c(err.msg, "The regularization lambdas have to be positive or 0!")
if(length(reg.lambdas) != 2)
err.msg <- c(err.msg, "Exactly 2 regularization lambdas need to be given!")
if(!all(c("life", "trans") %in% names(reg.lambdas)))
err.msg <- c(err.msg, "The regularization lambdas need to be named \"life\" and \"trans\"!")
return(err.msg)
}
#' @importFrom optimx optimx
#' @importFrom methods formalArgs
#' @importFrom utils getFromNamespace
check_user_data_optimxargs <- function(optimx.args){
err.msg <- c()
if(is.null(optimx.args))
return("The parameter \"optimx.args\" may not be NULL!")
if(!is.list(optimx.args) | is.data.frame(optimx.args))
return("Please provide \"optimx.args\" as a list!")
# further checks only if not empty list (ie no argument passed)
if(length(optimx.args) > 0){
if(is.null(names(optimx.args)))
err.msg <- c(err.msg, "Please provide a named list for \"optimx.args\"!")
for(n in names(optimx.args))
if(nchar(n) < 1){
err.msg <- c(err.msg, "Please provide names for every element in \"optimx.args\"!")
break
}
# the names need to match the inputs to optimx
optimx.allowed <- formalArgs(getFromNamespace("optimx",ns="optimx"))
# optimx.allowed <- c("gr", "hess", "lower", "upper", "method", "itnmax", "hessian")
for(n in names(optimx.args))
if(!(n %in% optimx.allowed))
err.msg <- c(err.msg, paste0("The element ",n," in optimx.args is not a valid input to optimx()!"))
# Now, multiple optimization methods are allowed and the last one is used
# only one method allowed
# if("method" %in% names(optimx.args))
# if(length(optimx.args$method) > 1)
# err.msg <- c(err.msg, paste0("Only a single method can be used at a time!"))
}
return(err.msg)
}
check_user_data_continuousdiscountfactor <- function(continuous.discount.factor){
if(is.null(continuous.discount.factor))
return("continuous.discount.factor cannot be NULL!")
err.msg <- .check_user_data_single_numeric(n = continuous.discount.factor,
var.name = "continuous.discount.factor")
if(!(continuous.discount.factor < 1 & continuous.discount.factor >= 0))
return("continuous.discount.factor needs to be in the interval [0,1)")
return(c())
}
check_user_data_startparamcorm <- function(start.param.cor, use.cor){
err.msg <- c()
# Null implies that start params need to be generated
if(is.null(start.param.cor))
return(err.msg)
if(!is.null(use.cor))
if((!anyNA(use.cor)) & use.cor == FALSE)
err.msg <- c(err.msg, "start.param.cor cannot be set if no correlation shall be used!")
err.msg <- c(err.msg, .check_user_data_single_numeric(n = start.param.cor,
var.name ="start.param.cor"))
if(length(err.msg)==0)
if(start.param.cor > 1 | start.param.cor < -1)
err.msg <- c(err.msg, "start.param.cor has to be in the interval [-1, 1]!")
# no names needed
return(err.msg)
}
check_user_data_startparamconstr <- function(start.params.constr, names.cov.constr){
if(missing(start.params.constr))
return(c())
if(is.null(start.params.constr))
return(c())
if(missing(names.cov.constr) | is.null(names.cov.constr))
return("Start parameters for constraint covariates should only be provided if the names for the constraint parameters are provided as well!")
# Re-use as exactly the same checks are needed
return(check_user_data_startparamscov(start.params.cov = start.params.constr,
names.params.cov = names.cov.constr,
name.of.cov = "Constraint"))
}
check_user_data_namesconstr <- function(clv.fitted, names.cov.constr){
err.msg <- c()
if(is.null(names.cov.constr))
return(err.msg) #return("Covariate names may not be NULL")
if(!is.character(names.cov.constr))
return("Covariate names for constraint covariates must be an unnamed character vector!")
if(!is.null(names(names.cov.constr)))
err.msg <- c(err.msg, "Covariate names for constraint covariates have to be provided as unnamed vector!")
if(length(names.cov.constr) == 0)
err.msg <- c(err.msg, "The names for constraint covariates may not be empty!")
if(anyNA(names.cov.constr))
err.msg <- c(err.msg, "There may be no NAs in the covariate names for constraint covariates!")
# Check that every name is in both data
for(n in names.cov.constr){
if(!(n %in% colnames([email protected]@data.cov.life)))
err.msg <- c(err.msg, paste0("The constraint covariate named ", n, " could not be found in the Lifetime covariate data!"))
if(!(n %in% colnames([email protected]@data.cov.trans)))
err.msg <- c(err.msg, paste0("The constraint covariate named ", n, " could not be found in the Transaction covariate data!"))
}
# Found only once
if(length(names.cov.constr) != length(unique(names.cov.constr)))
err.msg <- c(err.msg, "Every covariate name for constraint covariates may only appear exactly once!")
return(err.msg)
}
check_user_data_emptyellipsis <- function(...){
err.msg <- c()
if(...length() > 0)
err.msg <- c(err.msg, "Any further parameters passed in ... are ignored because they are not needed!")
return(err.msg)
}
check_user_data_containsspendingdata <- function(clv.data){
err.msg <- c()
if(!clv.data.has.spending(clv.data))
err.msg <- c(err.msg, "The data object is required to contain spending data!")
return(err.msg)
}
check_user_data_othermodels <- function(other.models){
if(!is.list(other.models)){
return("Parameter other.models has to be a list of fitted transaction models!")
}
# each element in list is a transaction model
if(!all(sapply(other.models, is, class2 = "clv.fitted.transactions"))){
return("All elements in 'other.models' have to be fitted transaction models, e.g the output of pnbd(), bgnbd(), or ggomnbd()!")
}
return(c())
}
check_user_data_label <- function(label, other.models){
if(is.null(label)){
# null is allowed = std. model name(s)
return(c())
}
if(length(other.models)==0){
return(.check_userinput_charactervec(char=label, var.name="label", n=1))
}else{
# requires names for main and all other models
err.msg <- .check_userinput_charactervec(char=label, var.name="label", n=1+length(other.models))
if(length(err.msg)){
return(err.msg)
}
if(any(duplicated(label))){
err.msg <- c(err.msg, "Parameter label may not contain any duplicates!")
}
return(err.msg)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_clvfitted_inputchecks.R
|
# . clv.controlflow.plot.check.inputs ------------------------------------------------------------------------
setMethod("clv.controlflow.plot.check.inputs", signature(obj="clv.fitted"), function(obj, prediction.end, cumulative, plot, label.line, verbose){
# Empty fallback method.
})
# . clv.controlflow.check.prediction.params -----------------------------------------------------------------
setMethod("clv.controlflow.check.prediction.params", signature = signature(clv.fitted = "clv.fitted"), function(clv.fitted){
# Do not check coef() because correlation coef may be NA and can still predict
if(anyNA([email protected])){
check_err_msg("Cannot proceed because there are NAs in the estimated model coefficients!")
}
})
# . clv.controlflow.predict.set.prediction.params ------------------------------------------------------------------------
setMethod(f = "clv.controlflow.predict.set.prediction.params", signature = signature(clv.fitted="clv.fitted"), definition = function(clv.fitted){
[email protected] <- coef(clv.fitted)[[email protected]@names.original.params.model]
return(clv.fitted)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfitted.R
|
# . clv.controlflow.estimate.check.inputs ------------------------------------------------------------------------
setMethod(f = "clv.controlflow.estimate.check.inputs", signature = signature(clv.fitted="clv.fitted"), definition = function(clv.fitted, start.params.model, optimx.args, verbose, ...){
# Check only basic structure
err.msg <- c()
if(!is.null(start.params.model)){
# may be NULL = use model default
err.msg <- c(err.msg, check_user_data_startparams(start.params = start.params.model,
vector.names = [email protected]@names.original.params.model,
param.names = "model start parameter"))
}
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name ="verbose"))
# Check additional optimx args
err.msg <- c(err.msg, check_user_data_optimxargs(optimx.args=optimx.args))
check_err_msg(err.msg)
})
# . clv.controlflow.estimate.put.inputs ------------------------------------------------------------------------
setMethod("clv.controlflow.estimate.put.inputs", signature = signature(clv.fitted="clv.fitted"), definition = function(clv.fitted, verbose, ...){
return(clv.fitted)
})
# . clv.controlflow.estimate.generate.start.params ------------------------------------------------------------------------
setMethod("clv.controlflow.estimate.generate.start.params", signature = signature(clv.fitted="clv.fitted"), definition = function(clv.fitted, start.params.model, verbose, start.param.cor, ...){
# Model params
if(is.null(start.params.model)){
untransformed.start.params.model <- setNames([email protected]@start.params.model, [email protected]@names.original.params.model)
}else{
untransformed.start.params.model <- start.params.model[[email protected]@names.original.params.model] # ensure order
}
transformed.start.params.model <- clv.model.transform.start.params.model(clv.model = [email protected],
original.start.params.model = untransformed.start.params.model)
names(transformed.start.params.model) <- [email protected]@names.prefixed.params.model
if(clv.model.supports.correlation([email protected])){
# If the model supports correlation, start.param.cor is passed, otherwise not
transformed.start.params.model <- clv.model.generate.start.param.cor([email protected], start.param.cor=start.param.cor, transformed.start.params.model=transformed.start.params.model)
}
return(transformed.start.params.model)
})
# . clv.controlflow.estimate.prepare.optimx.args ------------------------------------------------------------------------
# Put together the individual parts needed to call optimx
# Adding the variables needed to call the LL function is left to the model-specific optimizeLL functions as they are unknonwn at this point
#' @importFrom utils modifyList
setMethod("clv.controlflow.estimate.prepare.optimx.args", signature = signature(clv.fitted="clv.fitted"), def=function(clv.fitted, start.params.all){
# Start with model defaults
optimx.args <- [email protected]@optimx.defaults
# Everything to call optimx and the interlayer manager
optimx.args <- modifyList(optimx.args, list(fn = interlayer_manager,
par = start.params.all,
hessian = TRUE),
keep.null = TRUE)
# By default dont use any covariate specific interlayers ---------------------------------------------------
# For no covariates objects only the correlation interlayer can be used
#
# However, not passing the parameters for the other interlayers results in missing parameters for
# the interlayer manager. This could be handled by using default parameters or with missing there,
# but passing them with "False" is much cleaner
optimx.args <- modifyList(optimx.args, list(use.interlayer.constr = FALSE,
names.original.params.constr = character(0),
names.prefixed.params.constr = character(0),
use.interlayer.reg = FALSE,
reg.lambda.trans = numeric(0),
reg.lambda.life = numeric(0),
names.prefixed.params.after.constr.life = character(0),
names.prefixed.params.after.constr.trans = character(0)),
keep.null = TRUE)
# Default is no correlation
optimx.args <- modifyList(optimx.args, list(use.cor = FALSE,
name.prefixed.cor.param.m = character(0),
# By default, always check the bounds of param m
check.param.m.bounds = TRUE),
keep.null = TRUE)
# Correlation interlayer ---------------------------------------------------------------------
# Only turn on if needed
if(clv.model.estimation.used.correlation([email protected])){
optimx.args <- modifyList(optimx.args, list(use.cor = TRUE,
name.prefixed.cor.param.m = [email protected]@name.prefixed.cor.param.m,
# By default, always check the bounds of param m
check.param.m.bounds = TRUE),
keep.null = TRUE)
# Use NM as default if correlation is estimated because the interlayer may return Inf
# if the params are out-of-bound
optimx.args <- modifyList(optimx.args, list(method = "Nelder-Mead"))
# Use a custom gradient function that signals the correlation layer to
# not check the boundaries of param m
# Otherwise, the Hessian likely contains NAs because numDeriv often,
# also with small stepsizes, wanders accross the boundaries
# Not checking the boundaries of param m is no issue for the gradient and hessian only,
# the bound checks are enforced for the param during regular optimization evaluations
# Custom Gradient function
# Use optixm::grad because also used in optimx::optimx.setup:
# "ugr <- function(par, userfn = ufn, ...) { tryg <- grad(userfn, par, ...)}"
fct.no.check.grad <- function(x, fn.to.call.from.gr, ...){
# ... contains all the other arguments given to interlayer(s) and LL function
# fn.to.call.from.gr is what optimx(fn) calls (ie the interlayer manager)
all.other.args <- list(...)
all.other.args <- modifyList(all.other.args,
# dont check boundaries during gradient
alist(check.param.m.bounds = FALSE))
do.call(what=grnd, c(alist(par = x,
userfn = fn.to.call.from.gr),
all.other.args))
}
# For the gradient, call the wrapper around optmix::grnd
optimx.args <- modifyList(optimx.args,
list(gr= fct.no.check.grad,
# function to call when doing numerical grad. Do whatever is done for optimx
fn.to.call.from.gr = optimx.args$fn))
}
return(optimx.args)
})
# . clv.controlflow.estimate.process.post.estimation ------------------------------------------------------------------------
#' @importFrom optimx coef<-
#' @importFrom utils tail
setMethod(f = "clv.controlflow.estimate.process.post.estimation", signature = signature(clv.fitted="clv.fitted"), definition = function(clv.fitted, res.optimx){
[email protected] <- res.optimx
optimx.last.row <- tail([email protected], n=1)
if(anyNA(coef(optimx.last.row))){
warning(paste0("Estimation failed with NA coefficients. The returned object contains results but further usage is restricted.",
" You might want to try to fit the model again with method Nelder-Mead (using optimx.args=list(method=\"Nelder-Mead\")) or try different starting values. See examples."),
immediate. = TRUE, call. = FALSE)
}
# extract hessian from "details" attribute which is a list (if more then 1 method given)
# name it the same as the coefs for reading out later on
[email protected] <- as.matrix(tail(attr(optimx.last.row, "details")[, "nhatend"], n=1)[[1]])
if(length([email protected])==1 & all(is.na([email protected]))){
[email protected] <- matrix(data = NA_real_, nrow = ncol(coef(optimx.last.row)),
ncol = ncol(coef(optimx.last.row)))
warning("Hessian could not be derived. Setting all entries to NA.",
call. = FALSE, immediate. = TRUE)
}
colnames([email protected]) <- rownames([email protected]) <- colnames(tail(coef(res.optimx), n=1))
return(clv.fitted)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfitted_estimate.R
|
# . clv.controlflow.estimate.put.inputs -----------------------------------------------------------------
setMethod("clv.controlflow.estimate.put.inputs", signature = signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, remove.first.transaction, ...){
clv.fitted <- callNextMethod()
[email protected] <- remove.first.transaction
return(clv.fitted)
})
# . clv.controlflow.predict.check.inputs -----------------------------------------------------------------
setMethod(f = "clv.controlflow.predict.check.inputs", signature = signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, ...){
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose"))
check_err_msg(err.msg)
})
# . clv.controlflow.check.newdata ------------------------------------------------------------------------
#' @importFrom methods is
setMethod("clv.controlflow.check.newdata", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, user.newdata, ...){
err.msg <- c()
# Check newdata
if(!is(object = user.newdata, class2 = "clv.data")){
# This also catches NULL, NA, empty vecs, and so on
# but allows all cov data subclasses
err.msg <- c(err.msg, paste0("The parameter newdata needs to be a clv data object of class clv.data or a subclass thereof."))
}else{
# Is actually a clv.data object
# Also check if it has spending
if(!clv.data.has.spending(user.newdata))
err.msg <- c(err.msg, paste0("The newdata object needs to contain spending data in order to predict spending with it."))
}
check_err_msg(err.msg)
})
# . clv.controlflow.predict.build.result.table -----------------------------------------------------------------
setMethod("clv.controlflow.predict.build.result.table", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, ...){
dt.predictions <- copy(clv.fitted@cbs[, "Id"])
return(dt.predictions)
})
# . clv.controlflow.predict.get.has.actuals -----------------------------------------------------------------
setMethod("clv.controlflow.predict.get.has.actuals", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, dt.predictions){
return(clv.data.has.holdout([email protected]))
})
# . clv.controlflow.predict.add.actuals ----------------------------------------------------------------------
setMethod("clv.controlflow.predict.add.actuals", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, dt.predictions, has.actuals, verbose, ...){
actual.mean.spending <- i.actual.mean.spending <- Price <- NULL
# Spending models have no prediction.end
# Therefore all data in holdout period
# actual.mean.spending: mean spending per transaction
if(!has.actuals){
return(dt.predictions)
}else{
# only what is in prediction period!
dt.actual.spending <- clv.data.get.transactions.in.holdout.period([email protected])
dt.actual.spending <- dt.actual.spending[, list(actual.mean.spending = mean(Price)), keyby="Id"]
# Add to prediction table. Customers with no actual spending (not in table) are set to 0
dt.predictions[dt.actual.spending, actual.mean.spending := i.actual.mean.spending, on="Id"]
dt.predictions[is.na(actual.mean.spending), actual.mean.spending := 0]
return(dt.predictions)
}
})
# . clv.controlflow.predict.post.process.prediction.table ------------------------------------------------------------------------------
setMethod("clv.controlflow.predict.post.process.prediction.table", signature = signature(clv.fitted="clv.fitted.spending"), function(clv.fitted, dt.predictions, has.actuals, verbose, ...){
# Present cols in desired order ------------------------------------------------------------
if(has.actuals){
cols <- c("Id", "actual.mean.spending", "predicted.mean.spending")
}else{
cols <- c("Id", "predicted.mean.spending")
}
setcolorder(dt.predictions, cols)
return(dt.predictions)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfittedspending.R
|
# . clv.controlflow.predict.check.inputs ------------------------------------------------------------------------
setMethod(f = "clv.controlflow.predict.check.inputs", signature = signature(clv.fitted="clv.fitted.transactions"), definition = function(clv.fitted, verbose, prediction.end, continuous.discount.factor, predict.spending, ...){
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose"))
err.msg <- c(err.msg, check_user_data_predictionend(clv.fitted=clv.fitted, prediction.end=prediction.end))
# Cannot predict if no prediction.end (=null) and no holdout
if(is.null(prediction.end) & clv.data.has.holdout([email protected]) == FALSE)
err.msg <- c(err.msg, "Cannot predict without prediction.end if there is no holdout!")
err.msg <- c(err.msg, check_user_data_continuousdiscountfactor(continuous.discount.factor=continuous.discount.factor))
# predict.spending
# Spending can be predicted using either a function (ie gg), a logical (ie FALSE), or an
# already fitted spending model
if(is(object = predict.spending, class2 = "clv.fitted.spending")){
# Check if usable for prediction
if(anyNA(coef(predict.spending)))
err.msg <- c(err.msg, "The provided spending model in parameter 'predict.spending' cannot be used because its estimated coefficents contain NA!")
}else{
if(is.function(predict.spending)){
# has to be a CLVTools spending model
if(!isTRUE(all.equal(predict.spending, CLVTools::gg)))
err.msg <- c(err.msg, "The method to predict spending has to be a spending model from CLVTools (ie gg)!")
}else{
# None of the above: Then it has to be a logical
# cannot use .check_user_data_single_boolean() because it will return message "has to be logical" what is not true
# for predict.spending
if(!is.logical(predict.spending)){
err.msg <- c(err.msg, "The parameter predict.spending has to be either an already fitted spending model, a method from CLVTools to fit a spending model (ie gg) or a logical (True/False)!")
# Cannot continue if not a logical
}else{
# Is logical
if(length(predict.spending)>1)
err.msg <- c(err.msg, paste0("The parameter predict.spending can only contain 1 element!"))
if(anyNA(predict.spending))
err.msg <- c(err.msg, paste0("The parameter predict.spending cannot be NA!"))
}
}
}
# predict.spending has to be valid already
check_err_msg(err.msg)
# There has to be spending data if it should be predicted from it
if(is.logical(predict.spending)){
if(predict.spending == TRUE & clv.data.has.spending([email protected]) == FALSE)
err.msg <- c(err.msg, "Cannot predict spending if there is no spending data!")
}else{
# function or fitted spending model but both required spending data
if(clv.data.has.spending([email protected]) == FALSE)
err.msg <- c(err.msg, "Cannot predict spending if there is no spending data!")
}
check_err_msg(err.msg)
# nothing to return
})
# . clv.controlflow.check.newdata ------------------------------------------------------------------------
#' @importFrom methods is extends
setMethod("clv.controlflow.check.newdata", signature(clv.fitted="clv.fitted.transactions"), definition = function(clv.fitted, user.newdata, prediction.end, ...){
err.msg <- c()
# Check newdata
if(!is(object = user.newdata, class2 = "clv.data")){
# This also catches NULL, NA, empty vecs, and so on
# but allows all cov data subclasses
err.msg <- c(err.msg, paste0("The parameter newdata needs to be a clv data object of class ",
class([email protected])))
}else{
# Is actually a clv.data object Also check if it is the right type
# Check if the provided newdata is of the exact same class as the currently
# stored data object.
# Cannot use is() because subclasses are recognized as well
# (ie clv.data.static.cov is recognized as clv.data)
# Use extends with fullInfo=TRUE. If it is the exact same class, no distance object is
# returned but only TRUE. Use isTRUE to check for equality because can also return non boolean
if(!isTRUE(extends(class1 = class([email protected]), class2 = class(user.newdata), fullInfo = TRUE)))
err.msg <- c(err.msg, paste0("An object of class ", class([email protected]),
" needs to be supplied for parameter newdata."))
}
check_err_msg(err.msg)
})
# . clv.controlflow.predict.build.result.table ---------------------------------------------------------------------
setMethod("clv.controlflow.predict.build.result.table", signature(clv.fitted="clv.fitted.transactions"), definition = function(clv.fitted, verbose, prediction.end, ...){
period.last <- period.first <- period.length <- NULL
dt.predictions <- copy(clv.fitted@cbs[, "Id"])
# Add information about range of prediction period
# tp.prediction.start: Start of prediction, including this timepoint
# tp.prediction.end: End of prediction period which includes this timepoint
# prediction.length: Length of period for which predictions should be made, in number of periods
# Whether the prediction.end is valid after conversion is done in
# clv.time.get.prediction.table(). Cannot be done before because
# the end of the prediction period cannot be determined until after newdata is set
dt.prediction.time.table <- clv.time.get.prediction.table(clv.time = [email protected]@clv.time,
user.prediction.end = prediction.end)
# Add information to prediction table
dt.predictions <- cbind(dt.predictions, dt.prediction.time.table)
timepoint.prediction.first <- dt.predictions[1, period.first]
timepoint.prediction.last <- dt.predictions[1, period.last]
prediction.period.length <- dt.predictions[1, period.length]
if(verbose)
message("Predicting from ", timepoint.prediction.first, " until (incl.) ",
timepoint.prediction.last, " (", format(prediction.period.length, digits = 4, nsmall=2)," ",
[email protected]@[email protected],").")
return(dt.predictions)
})
# clv.controlflow.predict.get.has.actuals ---------------------------------------------------------------------------------
setMethod("clv.controlflow.predict.get.has.actuals", signature(clv.fitted="clv.fitted.transactions"), definition = function(clv.fitted, dt.predictions){
period.last <- NULL
# Only if:
# - there is a holdout
# - the prediction is not beyond holdout
timepoint.prediction.last <- dt.predictions[1, period.last]
return(clv.data.has.holdout([email protected]) & (timepoint.prediction.last <= [email protected]@[email protected]))
})
# .clv.controlflow.predict.add.actuals ---------------------------------------------------------------------------------
setMethod("clv.controlflow.predict.add.actuals", signature(clv.fitted="clv.fitted.transactions"), definition = function(clv.fitted, dt.predictions, has.actuals, verbose, ...){
actual.total.spending <- i.actual.total.spending <- Price <- Date <- period.first <- period.last <- actual.x <- i.actual.x <- NULL
# Only if:
# - there is a holdout
# - the prediction is not beyond holdout
#
# Data until prediction end
# actual.x: number of transactions
# actual.total.spending: total spending
timepoint.prediction.first <- dt.predictions[1, period.first]
timepoint.prediction.last <- dt.predictions[1, period.last]
if(!has.actuals){
return(dt.predictions)
}else{
# only what is in prediction period!
dt.holdout.transactions <- clv.data.get.transactions.in.holdout.period([email protected])
dt.actuals.transactions <- dt.holdout.transactions[between(x = Date,
lower = timepoint.prediction.first,
upper = timepoint.prediction.last,
incbounds = TRUE)]
if(clv.data.has.spending([email protected])){
dt.actuals <- dt.actuals.transactions[, list(actual.x = .N,
actual.total.spending = sum(Price)),
keyby="Id"]
}else{
dt.actuals <- dt.actuals.transactions[, list(actual.x = .N), keyby="Id"]
}
dt.predictions[dt.actuals, actual.x := i.actual.x, on="Id"]
dt.predictions[is.na(actual.x), actual.x := 0]
if(clv.data.has.spending([email protected])){
dt.predictions[dt.actuals, actual.total.spending := i.actual.total.spending, on="Id"]
dt.predictions[is.na(actual.total.spending), actual.total.spending := 0]
}
return(dt.predictions)
}
})
# . clv.controlflow.predict.post.process.prediction.table ------------------------------------------------------------------------------
setMethod("clv.controlflow.predict.post.process.prediction.table", signature = signature(clv.fitted="clv.fitted.transactions"), function(clv.fitted, dt.predictions, has.actuals, verbose, predict.spending, ...){
predicted.mean.spending <- i.predicted.mean.spending <- actual.total.spending <- i.actual.total.spending <- NULL
predicted.CLV <- DECT <- DERT <- NULL
# Predict spending ---------------------------------------------------------------------------------------
# depends on content of predict.spending:
# Predict spending
# logical TRUE: fit gg on data and predict
# function: fit method on data and predict
# fitted model: predict
#
# Add predicted spending to prediction table
# Input checks already checked whether there is spending data in clv.data
# Add spending data and actuals to prediction table
fct.add.spending.data <- function(dt.spending, dt.predictions){
dt.predictions[dt.spending, predicted.mean.spending := i.predicted.mean.spending, on = "Id"]
# The actual.mean.spending from dt.spending is not added anymore
# actual.total.spending is already in prediction table
return(dt.predictions)
}
# Fit, predict, and add to prediction table
fct.fit.and.predict.spending.model <- function(spending.method, verbose, dt.predictions){
name.model <- as.character(spending.method@generic)
if(verbose){
message(paste0("Estimating ",name.model," model to predict spending..."))
}
# Fit spending method onto data
fitted.spending <- do.call(what = spending.method, args = list(clv.data = [email protected],
verbose = verbose))
if(anyNA(coef(fitted.spending))){
warning(paste0("The ",name.model," spending model could not be fit. All spending is set to 0."), immediate. = TRUE, call. = FALSE)
dt.predictions[, predicted.mean.spending := 0]
}else{
# Did fit fine
res.sum <- summary(fitted.spending)
if(res.sum$kkt1 == FALSE | res.sum$kkt2 == FALSE){
warning(paste0("The KKT optimality conditions are not both met for the fitted ",name.model," spending model."), immediate. = TRUE, call. = FALSE)
}
dt.spending <- predict(fitted.spending)
dt.predictions <- fct.add.spending.data(dt.spending = dt.spending, dt.predictions = dt.predictions)
}
return(dt.predictions)
}
# Predict spending in any case except if predict.spending == FALSE
# use all.equal because can also be function or fitted spending model
do.predict.spending <- !isTRUE(all.equal(predict.spending, FALSE))
if(do.predict.spending){
if(is.logical(predict.spending)){
# Is TRUE because FALSE would not be here
dt.predictions <- fct.fit.and.predict.spending.model(spending.method = gg, verbose = verbose,
dt.predictions = dt.predictions)
}else{
if(is.function(predict.spending)){
# Use the method provided by the user
dt.predictions <- fct.fit.and.predict.spending.model(spending.method = predict.spending, verbose = verbose,
dt.predictions = dt.predictions)
}else{
# is already fitted model
# no further checks, the user is (hopefully) happy with how it fitted (coef not NA is checking in inputchecks)
# newdata: Predict for data in transaction model, dont predict spending for data on which the spending model was fit
dt.spending <- predict(object = predict.spending, newdata = [email protected], verbose = verbose)
dt.predictions <- fct.add.spending.data(dt.spending = dt.spending, dt.predictions = dt.predictions)
}
}
# If spending is predicted, CLV is also calculated
# CLV: DERT/DECT * Spending
if("DERT" %in% colnames(dt.predictions))
dt.predictions[, predicted.CLV := DERT * predicted.mean.spending]
if("DECT" %in% colnames(dt.predictions))
dt.predictions[, predicted.CLV := DECT * predicted.mean.spending]
}
# Present cols in desired order ------------------------------------------------------------
cols <- c("Id", "period.first", "period.last", "period.length")
if(has.actuals){
cols <- c(cols, "actual.x")
# cannot determine otherwise alone from has.actuals
if("actual.total.spending" %in% colnames(dt.predictions))
cols <- c(cols, "actual.total.spending")
}
if("DERT" %in% colnames(dt.predictions))
cols <- c(cols, "PAlive", "CET", "DERT")
if("DECT" %in% colnames(dt.predictions))
cols <- c(cols, "PAlive", "CET", "DECT")
if(do.predict.spending)
cols <- c(cols, "predicted.mean.spending")
if("predicted.CLV" %in% colnames(dt.predictions))
cols <- c(cols, "predicted.CLV")
setcolorder(dt.predictions, cols)
return(dt.predictions)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfittedtransactions.R
|
# . clv.controlflow.plot.check.inputs ------------------------------------------------------------------------
setMethod("clv.controlflow.plot.check.inputs", signature(obj="clv.fitted.transactions.dynamic.cov"), function (obj, prediction.end, cumulative, plot, label.line, verbose) {
period.until <- Cov.Date <- NULL
# No nocov /staticcov checks (no need to call super method)
err.msg <- c()
# Check that dyncov covariate is long enough for prediction end
# Convert prediction.end already for this
dt.expectation <- clv.time.expectation.periods(clv.time = [email protected]@clv.time, user.tp.end = prediction.end)
# only need to check one cov data, guaranteed that both are of same length
if(dt.expectation[, max(period.until)] > [email protected]@data.cov.trans[, max(Cov.Date)])
err.msg <- c(err.msg, "The dynamic covariates in the fitted model are not long enough for the given prediction.end!")
check_err_msg(err.msg)
})
# . clv.controlflow.check.newdata ------------------------------------------------------------------------
#' @importFrom methods callNextMethod
setMethod("clv.controlflow.check.newdata", signature(clv.fitted="clv.fitted.transactions.dynamic.cov"), definition = function(clv.fitted, user.newdata, prediction.end, ...){
# Do static cov (and hence also nocov) inputchecks first for newdata
callNextMethod()
period.last <- Cov.Date <- NULL
# prediction.end needs to be ok to work with it
check_err_msg(check_user_data_predictionend(clv.fitted=clv.fitted, prediction.end=prediction.end))
err.msg <- c()
# Check that dyncov covariate is long enough for prediction end
# Convert prediction.end already for this
# newdata will replace existing data therefore check its cov
# Also clv.time in newdata has to be used for conversion of prediction.end
dt.predictions <- clv.time.get.prediction.table(clv.time = [email protected],
user.prediction.end = prediction.end)
tp.last.required.cov.period <- clv.time.floor.date(clv.time = [email protected],
timepoint = dt.predictions[1, period.last])
# only need to check one cov data, guaranteed that both are same length
if(tp.last.required.cov.period > [email protected][, max(Cov.Date)])
err.msg <- c(err.msg, "The dynamic covariates in parameter newdata are not long enough for the given parameter prediction.end!")
check_err_msg(err.msg)
})
# . clv.controlflow.predict.check.inputs ------------------------------------------------------------------------
#' @importFrom methods callNextMethod
setMethod(f = "clv.controlflow.predict.check.inputs", signature = signature(clv.fitted="clv.fitted.transactions.dynamic.cov"), function(clv.fitted, verbose, prediction.end, continuous.discount.factor, predict.spending, ...){
# Do static cov (and hence also nocov) inputchecks first
# After this, newdata is basically ok
callNextMethod()
period.last <- Cov.Date <- NULL
err.msg <- c()
# Check that dyncov covariate is long enough for prediction end
# Convert prediction.end already for this
dt.predictions <- clv.time.get.prediction.table(clv.time = [email protected]@clv.time,
user.prediction.end = prediction.end)
tp.last.required.cov.period <- clv.time.floor.date(clv.time = [email protected]@clv.time,
timepoint = dt.predictions[1, period.last])
# only need to check one cov data, guaranteed that both are same length
if(tp.last.required.cov.period > [email protected]@data.cov.trans[, max(Cov.Date)])
err.msg <- c(err.msg, "The dynamic covariates in the fitted model are not long enough for the given parameter prediction.end!")
check_err_msg(err.msg)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfittedtransactionsdyncov.R
|
# . clv.controlflow.predict.set.prediction.params ------------------------------------------------------------------------
#' @importFrom methods callNextMethod
setMethod(f = "clv.controlflow.predict.set.prediction.params", signature = signature(clv.fitted="clv.fitted.transactions.static.cov"), definition = function(clv.fitted){
# Get no cov model params
clv.fitted <- callNextMethod()
# Set life and trans params
# All params: Re-name to original names to match name of data
# Constraint params: The prediction params for both processes need to contain the constraint params (in original names)
# Ordering: Ensure same ordering as data
# Covariate params in coef() are always prefixed to distinguish them per process
# This could be achieved much simpler by relying on character(0) in param names but be explicit for clarity
if([email protected]){
named.params.constr <- setNames(coef(clv.fitted)[[email protected]],
[email protected])
# concatenate with free params, if there are any.
# Else only from constr params
if(length([email protected])>0){
prediction.params.life <- c(setNames(coef(clv.fitted)[[email protected]],
[email protected]),
named.params.constr)
}else{
prediction.params.life <- named.params.constr # no free in lifetime, only constr
}
if(length([email protected])>0){
prediction.params.trans <- c(setNames(coef(clv.fitted)[[email protected]],
[email protected]),
named.params.constr)
}else{
prediction.params.trans <- named.params.constr # no free in transaction, only constr
}
}else{
# no constraints is simple
prediction.params.life <- setNames(coef(clv.fitted)[[email protected]], [email protected])
prediction.params.trans <- setNames(coef(clv.fitted)[[email protected]], [email protected])
}
# Order like data
prediction.params.life <- prediction.params.life[clv.data.get.names.cov.life([email protected])]
prediction.params.trans <- prediction.params.trans[clv.data.get.names.cov.trans([email protected])]
[email protected] <- prediction.params.life
[email protected] <- prediction.params.trans
return(clv.fitted)
})
# . clv.controlflow.check.prediction.params -----------------------------------------------------------------
setMethod("clv.controlflow.check.prediction.params", signature = signature(clv.fitted = "clv.fitted.transactions.static.cov"), function(clv.fitted){
# Check model prediction params
callNextMethod()
# Do not check coef() because correlation coef may be NA and can still predict
if(anyNA([email protected]) | anyNA([email protected])){
check_err_msg("Cannot proceed because there are NAs in the estimated covariate coefficients!")
}
})
# . clv.controlflow.check.newdata ------------------------------------------------------------------------------
setMethod("clv.controlflow.check.newdata", signature(clv.fitted="clv.fitted.transactions.static.cov"), definition = function(clv.fitted, user.newdata, prediction.end, ...){
# Do nocov newdata checks first
# newdata fulfills all basic properties after this
callNextMethod()
err.msg <- c()
# Check that it does have the same covariates as the ones used for fitting
# nocov already checked that is of correct class
if(!setequal([email protected], [email protected]@names.cov.data.life))
err.msg <- c(err.msg, "Not all Lifetime covariates used for fitting are present in the 'newdata' object!")
if(!setequal([email protected], [email protected]@names.cov.data.trans))
err.msg <- c(err.msg, "Not all Transaction covariates used for fitting are present in the 'newdata' object!")
check_err_msg(err.msg)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfittedtransactionsstaticcov.R
|
# . clv.controlflow.estimate.check.inputs ------------------------------------------------------------------------------
setMethod(f = "clv.controlflow.estimate.check.inputs", signature = signature(clv.fitted="clv.fitted.transactions.static.cov"), definition = function(clv.fitted, start.params.model, optimx.args, verbose, # clv.fitted input args
names.cov.life, names.cov.trans,
start.params.life, start.params.trans,
reg.lambdas,
names.cov.constr, start.params.constr, cl, ...){
# check input for clv.fitted.transactions
callNextMethod()
# Additional covariates input args checks
err.msg <- c()
err.msg <- c(err.msg, check_user_data_namescov_reduce(names.cov = names.cov.life, data.cov.dt = [email protected]@data.cov.life, name.of.cov = "Lifetime"))
err.msg <- c(err.msg, check_user_data_namescov_reduce(names.cov = names.cov.trans, data.cov.dt = [email protected]@data.cov.trans, name.of.cov = "Transaction"))
check_err_msg(err.msg)
# Get names as needed for startparams
# no name was provided / NULL: use all covariate names
# some name provided: use this name(s)
if(length(names.cov.life)==0)
names.cov.life <- clv.data.get.names.cov.life([email protected])
if(length(names.cov.trans)==0)
names.cov.trans <- clv.data.get.names.cov.trans([email protected])
# Check first - if names are wrong they will be wrong as in put to check_startparams as well
err.msg <- c(err.msg, check_user_data_startparamscov(start.params.cov=start.params.life, names.params.cov = names.cov.life, name.of.cov="Lifetime"))
err.msg <- c(err.msg, check_user_data_startparamscov(start.params.cov=start.params.trans, names.params.cov = names.cov.trans, name.of.cov="Transaction"))
# Check reg lambdas
err.msg <- c(err.msg, check_user_data_reglambdas(reg.lambdas=reg.lambdas))
# Check constraint params input
err.msg <- c(err.msg, check_user_data_namesconstr(clv.fitted=clv.fitted, names.cov.constr = names.cov.constr))
check_err_msg(err.msg) # check because names are needed for start params
err.msg <- c(err.msg, check_user_data_startparamconstr(start.params.constr = start.params.constr, names.cov.constr = names.cov.constr))
check_err_msg(err.msg)
# if any param is constraint, it may not be given as start parameters in the free cov params
if(length(names.cov.constr)>0){
if(any(names.cov.constr %in% names(start.params.life)))
err.msg <- c("There may be no start parameters for the constraint parameters in start.params.life")
if(any(names.cov.constr %in% names(start.params.trans)))
err.msg <- c("There may be no start parameters for the constraint parameters in start.params.trans")
}
check_err_msg(err.msg)
# Do not warn if there are additional args in ... as they can be for a model
# without ... in clv.fitted.transactions.static.cov estimate not possible
})
# . clv.controlflow.estimate.put.inputs ------------------------------------------------------------------------------
#' @importFrom methods callNextMethod
setMethod("clv.controlflow.estimate.put.inputs", signature = signature(clv.fitted="clv.fitted.transactions.static.cov"), definition = function(clv.fitted, verbose, reg.lambdas, names.cov.constr, names.cov.life, names.cov.trans, ...){
# clv.fitted put inputs
clv.fitted <- callNextMethod()
# Reduce to user's desired covariates only -----------------------------------------------------------
[email protected] <- clv.data.reduce.covariates([email protected], names.cov.life=names.cov.life,
names.cov.trans=names.cov.trans)
# is regularization used? ---------------------------------------------------------------------------
# Yes: Indicate and store lambdas
# No: Indicate
if(!is.null(reg.lambdas) & !all(reg.lambdas == 0)){
# Regularization: Store
[email protected] <- TRUE
[email protected] <- reg.lambdas[["life"]]
[email protected] <- reg.lambdas[["trans"]]
}else{
# No regularization
[email protected] <- FALSE
[email protected] <- numeric(0)
[email protected] <- numeric(0)
}
# Are some parameters constraint? --------------------------------------------------------------------
if(!is.null(names.cov.constr)){
# Using constraints
# Set up original and prefixed names for constraint and free
[email protected] <- TRUE
[email protected] <- names.cov.constr
[email protected] <- paste("constr", [email protected], sep = ".")
original.free.life <- unique(setdiff(clv.data.get.names.cov.life([email protected]), [email protected])) #unique not needed but be sure
original.free.trans <- unique(setdiff(clv.data.get.names.cov.trans([email protected]), [email protected]))
if(length(original.free.life)>0){
[email protected] <- original.free.life
[email protected] <- paste("life", [email protected], sep = ".")
}else{
[email protected] <- character(0)
[email protected] <- character(0)
}
if(length(original.free.trans)>0){
[email protected] <- original.free.trans
[email protected] <- paste("trans", [email protected], sep = ".")
}else{
[email protected] <- character(0)
[email protected] <- character(0)
}
}else{
# No constraints used
[email protected] <- FALSE
[email protected] <- clv.data.get.names.cov.life([email protected])
[email protected] <- clv.data.get.names.cov.trans([email protected])
[email protected] <- character(0)
[email protected] <- paste("life", [email protected], sep = ".")
[email protected] <- paste("trans", [email protected], sep = ".")
[email protected] <- character(0)
}
# independent of using constraints or not. These are used in LL and Reg interlayer after the
# potential constraint interlayer has doubled the parameters and therefore need to contain all names
[email protected] <- paste("life", clv.data.get.names.cov.life([email protected]), sep=".")
[email protected] <- paste("trans", clv.data.get.names.cov.trans([email protected]), sep=".")
return(clv.fitted)
})
# . clv.controlflow.estimate.generate.start.params ------------------------------------------------------------------------------
setMethod("clv.controlflow.estimate.generate.start.params", signature = signature(clv.fitted="clv.fitted.transactions.static.cov"),
# original signature: clv.fitted, start.params.model
definition = function(clv.fitted,
start.params.model,
start.params.life,
start.params.trans,
start.params.constr,
verbose,
...){
# Call clv.fitted start params generation
transformed.start.params.model <- callNextMethod()
# Covariates part
start.params.free.life <- c()
start.params.free.trans <- c()
start.params.constr <- c()
# any free params?
if(length([email protected]) > 0){
# start params given?
if(is.null(start.params.life)){
start.params.free.life <- rep([email protected]@start.param.cov, length([email protected]))
names(start.params.free.life) <- [email protected]
}else{
# correct order
start.params.free.life <- start.params.life[[email protected]]
}
# apply model transformation to start params
start.params.free.life <- clv.model.transform.start.params.cov([email protected], start.params.free.life)
names(start.params.free.life) <- [email protected]
}
# any free params?
if(length([email protected]) > 0){
if(is.null(start.params.trans)){
start.params.free.trans <- rep([email protected]@start.param.cov, length([email protected]))
names(start.params.free.trans) <- [email protected]
}else{
# correct order
start.params.free.trans <- start.params.trans[[email protected]]
}
# apply model transformation to start params
start.params.free.trans <- clv.model.transform.start.params.cov([email protected], start.params.free.trans)
names(start.params.free.trans) <- [email protected]
}
# any constrain params?
if(length([email protected]) > 0){
if(is.null(start.params.constr)){
# none user given
start.params.constr <- rep([email protected]@start.param.cov, length([email protected]))
names(start.params.constr) <- [email protected]
}else{
start.params.constr <- start.params.constr[[email protected]] #ensure order
}
# apply model transformation to start params
start.params.constr <- clv.model.transform.start.params.cov([email protected], start.params.constr)
names(start.params.constr) <- [email protected]
}
# NULL if not needed
all.cov.params <- c(start.params.free.life, start.params.free.trans, start.params.constr)
return(c(transformed.start.params.model, all.cov.params))
})
# . clv.controlflow.estimate.prepare.optimx.args ------------------------------------------------------------------------------
#' @importFrom utils modifyList
setMethod("clv.controlflow.estimate.prepare.optimx.args", signature = signature(clv.fitted="clv.fitted.transactions.static.cov"),
def=function(clv.fitted, start.params.all){
# Call clv.fitted prepare.optimx.args
prepared.nocov.optimx.args <- callNextMethod()
# Add covariates interlayer parameters ---------------------------------------------------------------------
# keep.null = T, needed so that if reg.lambda or names.original.params.constr params are NULL,
# they are given to optimx/interlayer_manager as well
# Everything to call the regularization layer
optimx.args <- modifyList(prepared.nocov.optimx.args,
list(use.interlayer.reg = [email protected],
names.prefixed.params.after.constr.trans = [email protected],
names.prefixed.params.after.constr.life = [email protected],
reg.lambda.life = [email protected],
reg.lambda.trans = [email protected],
num.observations = nobs(object = clv.fitted)),
keep.null = TRUE)
# Everything to call the constraints layer
optimx.args <- modifyList(optimx.args, list(use.interlayer.constr = [email protected],
names.original.params.constr = [email protected],
names.prefixed.params.constr = [email protected]),
keep.null = TRUE)
return(optimx.args)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvfittedtransactionsstaticcov_estimate.R
|
# . clv.controlflow.estimate.generate.start.params ------------------------------------------------------------------------------
#' @importFrom methods as
#' @importFrom methods callNextMethod
setMethod("clv.controlflow.estimate.generate.start.params", signature = signature(clv.fitted="clv.pnbd.dynamic.cov"),definition = function(clv.fitted,
start.params.model,
start.params.life,
start.params.trans,
start.params.constr,
verbose,
...){
# Before calling the parent (static.cov and nocov) start param generation methods
# set the model start params to nocov model coefs if the user did not provide
# any start params for the model
# This has to be done here, and cannot be done in the model.prepare.optimx.args function
# because there the original estimation input is unknown
# ie it is not known if the user actually did supply start params or not
# Also, doing it as part of clv.fitted.transactions.dynamic.cov is not possible because the model
# to call (ie pnbd()) is unknown
if(is.null(start.params.model)){
# Generate start params from nocov model
if(verbose)
message("Generating model start parameters by fitting a no covariate pnbd model...")
# Do optimization
nocov.coefs <- tryCatch(coef(pnbd(clv.data = as(object = [email protected], Class = "clv.data", strict = TRUE),
start.params.model = c(r=1, s=1, alpha=1, beta=1),
verbose = FALSE)),
error = function(e){stop(paste0("Failed to estimate a pnbd no covariate model: ",
e$message), call. = FALSE)})
if(any(!is.finite(nocov.coefs)))
stop("The parameters from the pnbd no covariate model yielded non finite values. Please revise your data!", call. = FALSE)
if(verbose){
coef.brakets <- paste0("(", paste(c("r", "alpha", "s", "beta"), "=", format(nocov.coefs, digits=4), collapse = ", ", sep=""), ")")
message("Optimization of no covariate model found model start parameters ", coef.brakets)
}
# fake that the user input (start.params.model) was given as the params obtained here
start.params.model <- nocov.coefs
}
# Continue with ordinary start parameter generation process
return(callNextMethod())
})
# . clv.model.put.estimation.input ------------------------------------------------------------------------------------------------
setMethod(f = "clv.controlflow.estimate.put.inputs", signature = signature(clv.fitted="clv.pnbd.dynamic.cov"), definition = function(clv.fitted, verbose, ...){
# Create walks - they are specific to the pnbd dyncov model
clv.fitted <- callNextMethod()
if(verbose)
message("Creating walks...")
l.walks <- pnbd_dyncov_createwalks(clv.data = [email protected])
[email protected] <- l.walks[["data.walks.life.aux"]]
[email protected] <- l.walks[["data.walks.life.real"]]
[email protected] <- l.walks[["data.walks.trans.aux"]]
[email protected] <- l.walks[["data.walks.trans.real"]]
if(verbose)
message("Walks created.")
return(clv.fitted)
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_generics_clvpnbddyncov.R
|
#' @name bgbb
#' @title BG/BB models - Work In Progress
#'
#' @description Fits BG/BB models on transactional data with static and without covariates. Not yet implemented.
#'
#' @template template_params_estimate
#' @template template_params_estimate_cov
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @return No value is returned.
#'
NULL
#' @exportMethod bgbb
setGeneric("bgbb", def = function(clv.data, start.params.model=c(), optimx.args=list(), verbose=TRUE, ...)
standardGeneric("bgbb"))
#' @include class_clv_data.R
#' @rdname bgbb
setMethod("bgbb", signature = signature(clv.data="clv.data"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,...){
stop("This model has not yet been implemented!")
})
#' @include class_clv_data_staticcovariates.R
#' @rdname bgbb
setMethod("bgbb", signature = signature(clv.data="clv.data.static.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(), start.params.constr=c(),
reg.lambdas = c(), ...){
stop("This model has not yet been implemented!")
})
#' @include class_clv_data_dynamiccovariates.R
#' @rdname bgbb
setMethod("bgbb", signature = signature(clv.data="clv.data.dynamic.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(),start.params.constr=c(),
reg.lambdas = c(), ...){
stop("This model cannot be fitted on this type of data!")
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_bgbb.R
|
#' @exportMethod bgnbd
setGeneric("bgnbd", def = function(clv.data, start.params.model=c(), optimx.args=list(), verbose=TRUE, ...)
standardGeneric("bgnbd"))
#' @name bgnbd
#' @aliases bgnbd,clv.data.dynamic.covariates-method
#'
#' @title BG/NBD models
#'
#' @template template_params_estimate
#' @template template_params_estimate_cov
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @template template_param_dots
#'
#'
#' @description
#' Fits BG/NBD models on transactional data without and with static covariates.
#'
#'
#' @template template_details_paramsbgnbd
#'
#' @details If no start parameters are given, r = 1, alpha = 3, a = 1, b = 3 is used.
#' All model start parameters are required to be > 0. If no start values are given for the
#' covariate parameters, 0.1 is used.
#'
#' Note that the DERT expression has not been derived (yet) and it consequently is not possible to calculated
#' values for DERT and CLV.
#'
#'
#'
#' \subsection{The BG/NBD model}{
#' The BG/NBD is an "easy" alternative to the Pareto/NBD model that is easier to implement. The BG/NBD model slight adapts
#' the behavioral "story" associated with the Pareto/NBD model in order to simplify the implementation. The BG/NBD model uses a beta-geometric and
#' exponential gamma mixture distributions to model customer behavior. The key difference to the Pareto/NBD model is that a customer can only
#' churn right after a transaction. This simplifies computations significantly, however has the drawback that a customer cannot churn until he/she
#' makes a transaction. The Pareto/NBD model assumes that a customer can churn at any time.
#' }
#'
#' \subsection{BG/NBD model with static covariates}{
#' The standard BG/NBD model captures heterogeneity was solely using Gamma distributions.
#' However, often exogenous knowledge, such as for example customer demographics, is available.
#' The supplementary knowledge may explain part of the heterogeneity among the customers and
#' therefore increase the predictive accuracy of the model. In addition, we can rely on these
#' parameter estimates for inference, i.e. identify and quantify effects of contextual factors
#' on the two underlying purchase and attrition processes. For technical details we refer to
#' the technical note by Fader and Hardie (2007).
#'
#' The likelihood function is the likelihood function associated with the basic model where
#' alpha, a, and b are replaced with alpha = alpha0*exp(-g1z1), a = a_0*exp(g2z2), and b = b0*exp(g3z2)
#' while r remains unchanged. Note that in the current implementation, we constrain the covariate parameters
#' and data for the lifetime process to be equal (g2=g3 and z2=z3).
#' }
#'
#' @return Depending on the data object on which the model was fit, \code{bgnbd} returns either an object of
#' class \linkS4class{clv.bgnbd} or \linkS4class{clv.bgnbd.static.cov}.
#'
#' @template template_clvfitted_returnvalue
#'
#' @template template_clvfittedtransactions_seealso
#'
#' @template template_references_bgnbd
#'
#' @templateVar name_model_short bgnbd
#' @templateVar vec_startparams_model c(r=0.5, alpha=15, a = 2, b=5)
#' @template template_examples_nocovmodelinterface
#' @templateVar name_model_short bgnbd
#' @template template_examples_staticcovmodelinterface
NULL
#' @rdname bgnbd
#' @include class_clv_data.R
setMethod("bgnbd", signature = signature(clv.data="clv.data"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.bgnbd(cl=cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model,
optimx.args = optimx.args, verbose=verbose))
})
#' @rdname bgnbd
#' @include class_clv_data_staticcovariates.R
setMethod("bgnbd", signature = signature(clv.data="clv.data.static.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(),start.params.constr=c(),
reg.lambdas = c(), ...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.bgnbd.static.cov(cl=cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model,
optimx.args = optimx.args, verbose=verbose,
names.cov.life=names.cov.life, names.cov.trans=names.cov.trans,
start.params.life=start.params.life, start.params.trans=start.params.trans,
names.cov.constr=names.cov.constr,start.params.constr=start.params.constr,
reg.lambdas = reg.lambdas))
})
#' @include class_clv_data_dynamiccovariates.R
#' @keywords internal
setMethod("bgnbd", signature = signature(clv.data="clv.data.dynamic.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
...){
stop("This model cannot be fitted on this type of data!")
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_bgnbd.R
|
#' @name clvdata
#' @md
#'
#' @title Create an object for transactional data required to estimate CLV
#'
#' @param data.transactions Transaction data as \code{data.frame} or \code{data.table}. See details.
#' @templateVar name_param_trans data.transactions
#' @template template_params_clvdata
#'
#' @description
#' Creates a data object that contains the prepared transaction data and that is used as input for
#' model fitting. The transaction data may be split in an estimation and holdout sample if desired.
#' The model then will only be fit on the estimation sample.
#'
#' If covariates should be used when fitting a model, covariate data can be added
#' to an object returned from this function.
#'
#' @details
#' \code{data.transactions} A \code{data.frame} or \code{data.table} with customers' purchase history.
#' Every transaction record consists of a purchase date and a customer id.
#' Optionally, the price of the transaction may be included to also allow for prediction
#' of future customer spending.
#'
#' \code{time.unit} The definition of a single period. Currently available are \code{"hours"}, \code{"days"}, \code{"weeks"}, and \code{"years"}.
#' May be abbreviated.
#'
#' \code{date.format} A single format to use when parsing any date that is given as character input. This includes
#' the dates given in \code{data.transaction}, \code{estimation.split}, or as an input to any other function at
#' a later point, such as \code{prediction.end} in \code{predict}.
#' The function \code{\link[lubridate]{parse_date_time}} of package \code{lubridate} is used to parse inputs
#' and hence all formats it accepts in argument \code{orders} can be used. For example, a date of format "year-month-day"
#' (i.e., "2010-06-17") is indicated with \code{"ymd"}. Other combinations such as \code{"dmy"}, \code{"dym"},
#' \code{"ymd HMS"}, or \code{"HMS dmy"} are possible as well.
#'
#' \code{estimation.split} May be specified as either the number of periods since the first transaction or the timepoint
#' (either as character, Date, or POSIXct) at which the estimation period ends. The indicated timepoint itself will be part of the estimation sample.
#' If no value is provided or set to \code{NULL}, the whole dataset will used for fitting the model (no holdout sample).
#'
#' @details ## Aggregation of Transactions
#'
#' Multiple transactions by the same customer that occur on the minimally representable temporal resolution are aggregated to a
#' single transaction with their spending summed. For time units \code{days} and any other coarser \code{Date}-based
#' time units (i.e. \code{weeks}, \code{years}), this means that transactions on the same day are combined.
#' When using finer time units such as \code{hours} which are based on \code{POSIXct}, transactions on the same second are aggregated.
#'
#' For the definition of repeat-purchases, combined transactions are viewed as a single transaction. Hence, repeat-transactions
#' are determined from the aggregated transactions.
#'
#' @return
#' An object of class \code{clv.data}.
#' See the class definition \linkS4class{clv.data}
#' for more details about the returned object.
#'
#' The function \code{summary} can be used to obtain and print a summary of the data.
#' The generic accessor function \code{nobs} is available to read out the number of customers.
#'
#' @seealso \code{\link[CLVTools:SetStaticCovariates]{SetStaticCovariates}} to add static covariates
#' @seealso \code{\link[CLVTools:SetDynamicCovariates]{SetDynamicCovariates}} for how to add dynamic covariates
#' @seealso \code{\link[CLVTools:plot.clv.data]{plot}} to plot the repeat transactions
#' @seealso \code{\link[CLVTools:summary.clv.data]{summary}} to summarize the transaction data
#' @seealso \code{\link[CLVTools:pnbd]{pnbd}} to fit Pareto/NBD models on a \code{clv.data} object
#'
#' @examples
#'
#' \donttest{
#'
#' data("cdnow")
#'
#' # create clv data object with weekly periods
#' # and no splitting
#' clv.data.cdnow <- clvdata(data.transactions = cdnow,
#' date.format="ymd",
#' time.unit = "weeks")
#'
#' # same but split after 37 periods
#' clv.data.cdnow <- clvdata(data.transactions = cdnow,
#' date.format="ymd",
#' time.unit = "w",
#' estimation.split = 37)
#'
#' # same but estimation end on the 15th Oct 1997
#' clv.data.cdnow <- clvdata(data.transactions = cdnow,
#' date.format="ymd",
#' time.unit = "w",
#' estimation.split = "1997-10-15")
#'
#' # summary of the transaction data
#' summary(clv.data.cdnow)
#'
#' # plot the total number of transactions per period
#' plot(clv.data.cdnow)
#'
#' \dontrun{
#' # create data with the weekly periods defined to
#' # start on Mondays
#'
#' # set start of week to Monday
#' oldopts <- options("lubridate.week.start"=1)
#'
#' # create clv.data while Monday is the beginning of the week
#' clv.data.cdnow <- clvdata(data.transactions = cdnow,
#' date.format="ymd",
#' time.unit = "weeks")
#'
#' # Dynamic covariates now have to be supplied for every Monday
#'
#' # set week start to what it was before
#' options(oldopts)
#' }
#'
#'}
#'
#'
#' @export
clvdata <- function(data.transactions, date.format, time.unit, estimation.split=NULL, name.id="Id", name.date="Date", name.price="Price"){
# silence CRAN notes
Date <- Price <- Id <- x <- previous <- date.first.actual.trans <- NULL
cl <- match.call(expand.dots = TRUE)
# Check input parameters ---------------------------------------------------------
# Before breaking anything
if(!is.data.frame(data.transactions))
stop("Only transaction data of type data.frame or data.table can be processed!", call. = FALSE)
# Check user data. This also checks the given column names
err.msg <- c()
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.date, data=data.transactions))
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.id, data=data.transactions))
if(!is.null(name.price)) # May be NULL to indicate no Spending data
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.price, data=data.transactions))
check_err_msg(err.msg) # check already if colnames are wrong
err.msg <- c(err.msg, check_userinput_datanocov_timeunit(time.unit=time.unit))
err.msg <- c(err.msg, .check_userinput_charactervec(char=date.format, var.name = "date.format", n=1))
err.msg <- c(err.msg, check_userinput_datanocov_estimationsplit(estimation.split=estimation.split, date.format=date.format))
check_err_msg(err.msg)
# transaction data to data.table --------------------------------------------------
# Convert transaction data to data.table already to better process in the check and convert function
# Copy data because it will be manipulated by reference
dt.trans <- copy(data.transactions)
if(!is.data.table(dt.trans))
dt.trans <- setDT(dt.trans)
has.spending <- (!is.null(name.price))
# Reduce to named columns.
# This is needed if the data contains a column "Date"/"Id"/"Price" which is not actually selected
# as the renaming will leave it undetermined what is then used (2 columns with the same name)
if(has.spending){
dt.trans <- dt.trans[, .SD, .SDcols = c(name.id, name.date, name.price)]
setnames(dt.trans, old = c(name.id, name.date, name.price), new = c("Id", "Date", "Price"))
# reduce transactions to only 3 columns, in case there is more data
dt.trans <- dt.trans[, c("Id", "Date", "Price")]
}else{
dt.trans <- dt.trans[, .SD, .SDcols = c(name.id, name.date)]
setnames(dt.trans, old = c(name.id, name.date), new = c("Id", "Date"))
dt.trans <- dt.trans[, c("Id", "Date")]
}
# Check transaction data type ------------------------------------------------------
# check data only after it is data.table because relies on data table syntas
check_err_msg(check_userinput_datanocov_datatransactions(data.transactions.dt = dt.trans,
has.spending = has.spending))
# clv time -----------------------------------------------------------------------
# a match should be garantueed as allowed input was checked in check_user_data
clv.t <- switch(EXPR = match.arg(arg = tolower(time.unit),
choices = tolower(clv.time.possible.time.units())),
"hours" = clv.time.hours(time.format=date.format),
"days" = clv.time.days(time.format=date.format),
"weeks" = clv.time.weeks(time.format=date.format),
"years" = clv.time.years(time.format=date.format))
# with clv time, can convert transaction data to correct type -------------------------------
dt.trans[, Id := .convert_userinput_dataid(id.data = Id)]
dt.trans[, Date := clv.time.convert.user.input.to.timepoint(clv.t, user.timepoint = Date)]
if(has.spending){
dt.trans[, Price := as.numeric(Price)] # already checked that is numeric
}
setkeyv(dt.trans, cols = c("Id", "Date"))
# Aggregate transactions at the same timepoint ------------------------------------------------
# Aggregate what is on same smallest scale representable by time
# aggregating in the same time.unit does not make sense
# Date: on same day
# posix: on same second
dt.trans <- clv.data.aggregate.transactions(dt.transactions = dt.trans, has.spending = has.spending)
# Set estimation and holdout periods ---------------------------------------------------------
tp.first.transaction <- dt.trans[, min(Date)]
tp.last.transaction <- dt.trans[, max(Date)]
clv.t <- clv.time.set.sample.periods(clv.time = clv.t,
tp.first.transaction = tp.first.transaction,
tp.last.transaction = tp.last.transaction,
user.estimation.end = estimation.split)
if([email protected] > dt.trans[, max(Date)])
stop("Parameter estimation.split needs to indicate a point in the data!", call. = FALSE)
if([email protected] < 1)
stop("Parameter estimation.split needs to be at least 1 time.unit after the start!", call. = FALSE)
# Check if the estimation.split is valid ----------------------------------------
# - estimation period long enough
# - in transaction data
# - at least 2 periods
# Estimation end has to be at least cohort length
# otherwise there will be customers in holdout which never were
# in cbs (and many other problems)
# = Everyone's first actual transaction needs to be until calibration end
everyones.first.trans <- dt.trans[, list(date.first.actual.trans = min(Date)), by="Id"]
date.last.first.trans <- everyones.first.trans[, max(date.first.actual.trans)]
if([email protected] < date.last.first.trans)
stop("The estimation split is too short! Not all customers of this cohort had their first actual transaction until the specified estimation.split!", call. = F)
# Repeat Transactions ------------------------------------------------------------
# Save because used when plotting
# Remove the first transaction per customer
dt.repeat.trans <- clv.data.make.repeat.transactions(dt.transactions = dt.trans)
# Create clvdata object ----------------------------------------------------------
obj <- clv.data(call=cl,
data.transactions = dt.trans,
data.repeat.trans = dt.repeat.trans,
has.spending = has.spending,
clv.time=clv.t)
return(obj)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_clvdata.R
|
#' @name gg
#'
#' @title Gamma/Gamma Spending model
#'
#' @template template_params_estimate
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @template template_param_dots
#' @param remove.first.transaction Whether customer's first transaction are removed. If \code{TRUE} all zero-repeaters are excluded from model fitting.
#'
#' @description
#' Fits the Gamma-Gamma model on a given object of class \code{clv.data} to predict customers' mean
#' spending per transaction.
#'
#'
#' @details Model parameters for the G/G model are \code{p, q, and gamma}. \cr
#' \code{p}: shape parameter of the Gamma distribution of the spending process. \cr
#' \code{q}: shape parameter of the Gamma distribution to account for customer heterogeneity. \cr
#' \code{gamma}: scale parameter of the Gamma distribution to account for customer heterogeneity.\cr
#' If no start parameters are given, 1.0 is used for all model parameters. All parameters are required
#' to be > 0.
#'
#' The Gamma-Gamma model cannot be estimated for data that contains negative prices.
#' Customers with a mean spending of zero or a transaction count of zero are ignored during model fitting.
#'
#' \subsection{The G/G model}{
#' The G/G model allows to predict a value for future customer transactions. Usually, the G/G model is used
#' in combination with a probabilistic model predicting customer transaction such as the Pareto/NBD or the BG/NBD model.
#' }
#'
#' @return
#' An object of class \linkS4class{clv.gg} is returned.
#'
#' @template template_clvfitted_returnvalue
#'
#' @seealso \code{\link[CLVTools:clvdata]{clvdata}} to create a clv data object.
#' @seealso \code{\link[CLVTools:plot.clv.data]{plot}} to plot diagnostics of the transaction data, incl. of spending.
#' @seealso \code{\link[CLVTools:predict.clv.fitted.spending]{predict}} to predict expected mean spending for every customer.
#' @seealso \code{\link[CLVTools:plot.clv.fitted.spending]{plot}} to plot the density of customer's mean transaction value compared to the model's prediction.
#'
#' @template template_references_gg
#'
#' @templateVar name_model_short gg
#' @templateVar vec_startparams_model c(p=0.5, q=15, gamma=2)
#' @template template_examples_spendingmodelinterface
#'
NULL
#' @exportMethod gg
setGeneric("gg", def = function(clv.data, start.params.model=c(), remove.first.transaction = TRUE, optimx.args=list(), verbose=TRUE, ...)
standardGeneric("gg"))
#' @include class_clv_data.R
#' @rdname gg
setMethod("gg", signature = signature(clv.data="clv.data"), definition = function(clv.data,
start.params.model=c(),
remove.first.transaction = TRUE,
optimx.args=list(),
verbose=TRUE,
...){
err.msg <- c()
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
# Check here already because inputs are already needed to build the cbs (remove.first.transaction and data)
err.msg <- c(err.msg, .check_user_data_single_boolean(remove.first.transaction, var.name = "remove.first.transaction"))
err.msg <- c(err.msg, check_user_data_containsspendingdata(clv.data = clv.data))
check_err_msg(err.msg)
if(clv.data.has.negative.spending(clv.data)){
check_err_msg("The Gamma-Gamma spending model cannot be fit on data that contains negative prices!")
}
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.gg(cl=cl, clv.data=clv.data, remove.first.transaction = remove.first.transaction)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model,
optimx.args = optimx.args, verbose = verbose,
remove.first.transaction = remove.first.transaction))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_gg.R
|
#' @exportMethod ggomnbd
setGeneric("ggomnbd", def = function(clv.data, start.params.model=c(), optimx.args=list(), verbose=TRUE, ...)
standardGeneric("ggomnbd"))
#' @name ggomnbd
#' @aliases ggomnbd,clv.data.dynamic.covariates-method
#'
#' @title Gamma-Gompertz/NBD model
#'
#' @description Fits Gamma-Gompertz/NBD models on transactional data with static and without covariates.
#' @template template_params_estimate
#' @template template_params_estimate_cov
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @template template_details_paramsggomnbd
#'
#' @details If no start parameters are given, r = 1, alpha = 1, beta = 1, b = 1, s = 1 is used.
#' All model start parameters are required to be > 0. If no start values are given for the covariate parameters,
#' 0.1 is used.
#'
#' Note that the DERT expression has not been derived (yet) and it consequently is not possible to calculated
#' values for DERT and CLV.
#'
#' \subsection{The Gamma-Gompertz/NBD model}{
#' There are two key differences of the gamma/Gompertz/NBD (GGompertz/NBD) model compared to the relative to the well-known Pareto/NBD
#' model: (i) its probability density function can exhibit a mode at zero or an interior mode, and (ii) it can be skewed
#' to the right or to the left. Therefore, the GGompertz/NBD model is more flexible than the Pareto/NBD model.
#' According to Bemmaor and Glady (2012) can indicate substantial differences in expected residual lifetimes compared to the Pareto/NBD.
#' The GGompertz/NBD tends to be appropriate when firms are reputed and their offerings are differentiated.
#' }
#'
#' @return Depending on the data object on which the model was fit, \code{ggomnbd} returns either an object of
#' class \linkS4class{clv.ggomnbd} or \linkS4class{clv.ggomnbd.static.cov}.
#'
#' @template template_clvfitted_returnvalue
#'
#' @template template_clvfittedtransactions_seealso
#'
#' @template template_references_ggomnbd
#'
#' @templateVar vec_startparams_model c(r=0.5, alpha=15, b=5, beta=10, s=0.5)
#' @templateVar name_model_short ggomnbd
#' @template template_examples_nocovmodelinterface
#' @templateVar name_model_short ggomnbd
#' @template template_examples_staticcovmodelinterface
NULL
#' @include class_clv_data.R
#' @rdname ggomnbd
setMethod("ggomnbd", signature = signature(clv.data="clv.data"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.ggomnbd(cl=cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model,
optimx.args = optimx.args, verbose=verbose))
})
#' @rdname ggomnbd
#' @include class_clv_data_staticcovariates.R
setMethod("ggomnbd", signature = signature(clv.data="clv.data.static.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(), start.params.constr=c(),
reg.lambdas = c(), ...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.ggomnbd.static(cl=cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model,
optimx.args = optimx.args, verbose=verbose,
names.cov.life=names.cov.life, names.cov.trans=names.cov.trans,
start.params.life=start.params.life, start.params.trans=start.params.trans,
names.cov.constr=names.cov.constr,start.params.constr=start.params.constr,
reg.lambdas = reg.lambdas))
})
#' @include class_clv_data_dynamiccovariates.R
#' @keywords internal
setMethod("ggomnbd", signature = signature(clv.data="clv.data.dynamic.covariates"), definition = function(clv.data,
start.params.model=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(),start.params.constr=c(),
reg.lambdas = c(), ...){
stop("This model cannot be fitted on this type of data!")
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_ggomnbd.R
|
#' Formula Interface for Latent Attrition Models
#' @template template_param_formulainterface_data
#' @template template_param_formulainterface_formula
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @param cov Optional \code{data.frame} or \code{data.table} of covariate data for the lifetime and transaction process. See Details.
#'
#' @description
#' Fit latent attrition models for transaction with a formula interface
#'
#' @details
#' \subsection{Formula}{
#' A multi-part formula describing how to prepare data and fit the model.
#'
#' Formula left hand side (LHS) specifies the data preparation which depends on the provided argument \code{data}.
#' \itemize{
#' \item If \code{data} is \code{clvdata}: Nothing, LHS is required to be empty.
#' \item If \code{data} is a \code{data.frame}: Data preparation using formula special \code{clvdata(time.unit, date.format, split)}. The formula is required to have a LHS.
#' }
#'
#' Formula right hand side (RHS) specifies the model fitting and follows a multi-part notation.
#' \itemize{
#' \item 1st part (required): The model to fit. One of either \code{\link{pnbd}}, \code{\link{bgnbd}}, or \code{\link{ggomnbd}}. Depending on the model additional arguments may be given. See the respective model functions for details.
#' }
#'
#' If the model is fit with covariates, further parts separated by \code{|} are required:
#' \itemize{
#' \item 2nd part (required): Which covariates to include for the lifetime process, potentially transforming them and adding interactions. The dot ('.') refers to all columns in the data except the identifier variables.
#' \item 3rd part (required): Which covariates to include for the transaction process, potentially transforming them and adding interactions. The dot ('.') refers to all columns in the data except the identifier variables.
#' \item 4th part (optional): Formula special \code{regularization(trans=, life=)} to specify the lambdas for regularization and \code{constraint(...)} to specify parameters to be equal on both processes.
#' Both specials separated by \code{+} may be given.
#' }
#'
#' See the example section for illustrations on how to specify the formula parameter.
#' }
#'
#' \subsection{Covariate Data}{
#'
#' For time-invariant covariates the data contains exactly one single row of covariate data for every customer appearing in the transaction data.
#' Requires a column \code{Id} of customer identifiers.
#' See \code{\link[CLVTools:SetStaticCovariates]{SetStaticCovariates}} for details.
#'
#' For time-varying covariates the data contains exactly 1 row for every combination of timepoint and customer.
#' Requires a column \code{Id} of customer identifiers and a column \code{Cov.Date} of dates.
#' For each customer appearing in the transaction data there needs to be covariate data at every timepoint that marks the start of a period as defined
#' by time.unit. It has to range from the start of the estimation sample (timepoint.estimation.start) until the end of
#' the period in which the end of the holdout sample (timepoint.holdout.end) falls.
#' Covariates of class character or factor are converted to k-1 numeric dummies.
#' See \code{\link[CLVTools:SetDynamicCovariates]{SetDynamicCovariates}} and the the provided dataset \code{\link{apparelDynCov}} for illustration.
#' }
#'
#'
#' @seealso Models for inputs to: \link{pnbd}, \link{ggomnbd}, \link{bgnbd}.
#' @seealso \link{spending} to fit spending models with a formula interface
#'
#' @examples
#' \donttest{
#'
#' data("apparelTrans")
#' data("apparelStaticCov")
#'
#' clv.nocov <-
#' clvdata(apparelTrans, time.unit="w", date.format="ymd")
#'
#' # Create static covariate data with 2 covariates
#' clv.staticcov <-
#' SetStaticCovariates(clv.nocov,
#' data.cov.life = apparelStaticCov,
#' names.cov.life = c("Gender", "Channel"),
#' data.cov.trans = apparelStaticCov,
#' names.cov.trans = c("Gender", "Channel"))
#'
#' # Fit pnbd without covariates
#' latentAttrition(~pnbd(), data=clv.nocov)
#' # Fit bgnbd without covariates
#' latentAttrition(~bgnbd(), data=clv.nocov)
#' # Fit ggomnbd without covariates
#' latentAttrition(~ggomnbd(), data=clv.nocov)
#'
#' # Fit pnbd with start parameters and correlation
#' latentAttrition(~pnbd(start.params.model=c(r=1, alpha=10, s=2, beta=8),
#' use.cor=TRUE),
#' data=clv.nocov)
#'
#' # Fit pnbd with all present covariates
#' latentAttrition(~pnbd()|.|., clv.staticcov)
#'
#' # Fit pnbd with selected covariates
#' latentAttrition(~pnbd()|Gender|Channel+Gender, data=clv.staticcov)
#'
#' # Fit pnbd with start parameters for covariates
#' latentAttrition(~pnbd(start.params.life = c(Gender = 0.6, Channel = 0.4),
#' start.params.trans = c(Gender = 0.6, Channel = 0.4))|.|., data=clv.staticcov)
#'
#' # Fit pnbd with transformed covariate data
#' latentAttrition(~pnbd()|Gender|I(log(Channel+2)), data=clv.staticcov)
#'
#' # Fit pnbd with all covs and regularization
#' latentAttrition(~pnbd()|.|.|regularization(life=3, trans=8), clv.staticcov)
#'
#' # Fit pnbd with all covs and constraint parameters for Channel
#' latentAttrition(~pnbd()|.|.|constraint(Channel), clv.staticcov)
#'
#' # Fit pnbd on given data.frame, no split
#' latentAttrition(data()~pnbd(), data=apparelTrans)
#'
#' # Fit pnbd, split data after 39 periods
#' latentAttrition(data(split=39)~pnbd(), data=apparelTrans)
#' # Same but also give date format and period definition
#' latentAttrition(data(split=39, format=ymd, unit=w)~pnbd(), data=apparelTrans)
#'
#' # Fit pnbd on given data.frames w/ all covariates
#' latentAttrition(data()~pnbd()|.|., data=apparelTrans, cov=apparelStaticCov)
#'
#' # Fit pnbd on given data.frames w/ selected covariates
#' latentAttrition(data()~pnbd()|Channel+Gender|Gender,
#' data=apparelTrans, cov=apparelStaticCov)
#'
#' }
#'
#'
#' @importFrom Formula as.Formula
#' @importFrom stats terms formula
#' @export
latentAttrition <- function(formula, data, cov, optimx.args=list(), verbose=TRUE){
cl <- match.call(call = sys.call(), expand.dots = TRUE)
check_err_msg(check_userinput_formula(formula, name.specials.model = c("pnbd", "bgnbd", "ggomnbd")))
check_err_msg(check_userinput_formula_data(data))
check_err_msg(check_userinput_formula_cov(cov=cov))
check_err_msg(check_userinput_latentattrition_formulavsdata(formula=formula, data=data, cov=cov))
F.formula <- as.Formula(formula)
# Turn data.frame/table into data if needed
if(is.data.frame(data) || is.data.table(data)){
# Verified to be data.frame/table
data <- formulainterface_dataframe_toclvdata(F.formula = F.formula, data=data, cl=cl)
# Add covariate data if needed
# if indicated in formula RHS2&3 or cov data given
if(!missing(cov)){
data <-formulainterface_create_clvdataobj(F.formula = F.formula, clv.data.nocov = data,
create.dyncov = ("Cov.Date" %in% colnames(cov)),
dt.cov.life = cov, dt.cov.trans = cov)
}
}else{
# data is clv.data object
# if it has covariates, they need to be transformed
if(is(data, "clv.data.static.covariates")){
if(is(data, "clv.data.dynamic.covariates")){
# better to remove tp.cov.x columns here than trying to figure out whether
# there are any in formulainterface_create_clvdataobj()
data <- formulainterface_create_clvdataobj(F.formula = F.formula, clv.data.nocov = as(data, "clv.data"),
create.dyncov = TRUE,
dt.cov.life = [email protected][, !c("tp.cov.lower", "tp.cov.upper")],
dt.cov.trans = [email protected][, !c("tp.cov.lower", "tp.cov.upper")])
}else{
# Dont need to remove Id column
data <- formulainterface_create_clvdataobj(F.formula = F.formula, clv.data.nocov = as(data, "clv.data"),
create.dyncov = FALSE,
dt.cov.life = [email protected],
dt.cov.trans = [email protected])
}
}
}
# Fit model ---------------------------------------------------------------------------------------------------
# default args from explicitly passed args
args <- list(clv.data = data, verbose=verbose, optimx.args=optimx.args)
# add model call args
model <- formula_read_model_name(F.formula)
l.model.args <- formula_parse_args_of_special(F.formula = F.formula, name.special = model, from.lhs = 0, from.rhs = 1)
args <- modifyList(args, l.model.args, keep.null = TRUE)
# args passed to model special functions
# if any given
if(is(data, "clv.data.static.covariates") & length(F.formula)[2] == 4){
l.args.reg <- formula_parse_args_of_special(F.formula = F.formula, name.special = "regularization", from.lhs=0, from.rhs = 4)
if(length(l.args.reg)){
args <- modifyList(args, list(reg.lambdas = c(life=l.args.reg[["life"]], trans=l.args.reg[["trans"]])), keep.null = TRUE)
}
# read char vec of variables to constrain
# do not need to concat multiple separate constraint() if params.as.chars.only=TRUE
names.constr <- formula_readout_special_arguments(F.formula = F.formula, name.special = "constraint", from.lhs = 0, from.rhs = 4,
params.as.chars.only = TRUE)
if(length(names.constr)){
# To have names match covariate data names if there are any transformations applied or special symbols in the cov name
# spaces in operations are handled by
# Will make empty names.constr (NULL) to character(0) which is illegal input. Therefore have to wrap in if(length)
names.constr <- make.names(names.constr)
args <- modifyList(args, list(names.cov.constr=unname(names.constr)), keep.null = TRUE)
}
}
# Fit model
obj <- do.call(what = model, args)
# Replace call with call to latentAttrition()
obj@call <- cl
return(obj)
}
# Create clv.data object if needed
# Apply needed transformations to given data
formulainterface_dataframe_toclvdata <- function(F.formula, data, cl){
# Verified to be data.frame/table
# std args to create data object with
l.data.args <- list(data.transactions = data, date.format="ymd", time.unit="w",
name.id ="Id", name.date="Date", name.price="Price")
# Overwrite with what is given in data() special
l.data.special.args <- formula_parse_args_of_data(F.formula)
# rename names in formula specials to data parameters
names(l.data.special.args) <- sapply(names(l.data.special.args), function(x){
switch(EXPR = x, "unit"="time.unit", "split"="estimation.split", "format"="date.format")})
l.data.args <- modifyList(l.data.args, l.data.special.args, keep.null = TRUE)
data <- do.call(what = clvdata, args = l.data.args)
data@call <- cl
return(data)
}
#' @importFrom stats update
formulainterface_create_clvdataobj <- function(F.formula, create.dyncov, clv.data.nocov, dt.cov.life, dt.cov.trans){
if(create.dyncov){
cov.id.vars <- c("Id", "Cov.Date")
}else{
cov.id.vars <- "Id"
}
# Have to use model.matrix() in order to build interactions from given data
# model.frame() would otherwise be more desirable as it creates the relevant cols (incl transformations) but without dummifying
# model.matrix() also creates the intercept and expands the dot to include Id and Cov.Date which are dummified. Therefore need to remove ids vars and intercept from formula by subtracting with '-Id-1'
# update.formula() requires expanding the dot '.' with the names in the given data.
# use terms() so subset Formula to relevant rhs and expand dot.
# Considered alternatives:
# - reformulate(terms(F, data), intercept=F) but remove Id, Cov.Date lables from returned terms object. Good option but manipulating formula seems more natural.
# - use terms() but remove columns Id and Cov.Date from data to not expand dot to include these. May incur substantial overhead if data is large.
# f.remove: formula to remove intercept and covariate ids
f.remove <- eval(parse(text=paste0('~ . - 1 - ', paste0(cov.id.vars, collapse = '-'))))
f.formula.life <- update(terms(F.formula, lhs=0, rhs=2, data=dt.cov.life), f.remove)
f.formula.trans <- update(terms(F.formula, lhs=0, rhs=3, data=dt.cov.trans), f.remove)
# Apply formula on cov data
mm.cov.life <- as.data.table(model.matrix(f.formula.life, data=dt.cov.life ))
mm.cov.trans <- as.data.table(model.matrix(f.formula.trans, data=dt.cov.trans))
# Add Id vars to data
mm.cov.life <- cbind(mm.cov.life, dt.cov.life[, .SD, .SDcols=cov.id.vars])
mm.cov.trans <- cbind(mm.cov.trans, dt.cov.trans[, .SD, .SDcols=cov.id.vars])
# Create new cov data object
# from given clvdata object, is copy-ed in Set*Cov()
if(create.dyncov){
data <- SetDynamicCovariates(clv.data = clv.data.nocov,
data.cov.life = mm.cov.life, names.cov.life = setdiff(colnames(mm.cov.life), cov.id.vars),
data.cov.trans = mm.cov.trans, names.cov.trans = setdiff(colnames(mm.cov.trans), cov.id.vars),
name.id = "Id", name.date = "Cov.Date")
}else{
data <- SetStaticCovariates(clv.data = clv.data.nocov,
data.cov.life = mm.cov.life, names.cov.life = setdiff(colnames(mm.cov.life), cov.id.vars),
data.cov.trans = mm.cov.trans, names.cov.trans = setdiff(colnames(mm.cov.trans), cov.id.vars),
name.id = "Id")
}
return(data)
}
#' @importFrom Formula as.Formula is.Formula
#' @importFrom stats terms formula
#' @importFrom methods is
check_userinput_formula <- function(formula, name.specials.model){
err.msg <- c()
if(missing(formula))
return("Please provide a valid formula object as \'formula\' parameter.")
if(is.null(formula))
return("Please provide a valid formula object as \'formula\' parameter.")
# Check if it is a formula
if(!is(object = formula, class2 = "formula") && !is.Formula(formula))
return("Please provide a valid formula object as \'formula\' parameter.")
F.formula <- as.Formula(formula)
# Verify LHS ------------------------------------------------------------------------------------------
# Check that formula has maximum 1 LHS
if(length(F.formula)[1] > 1)
return("Please specify maximum 1 dependent variable (data()).")
# Only verify if there is LHS 1
if(length(F.formula)[1] == 1){
# if(length(all.vars(formula(F.formula, lhs=1, rhs=0))) > 0)
# err.msg <- c(err.msg, "Please specify nothing else but data() in the LHS.")
# Check that has exactly one special and nothing else in LHS
num.lhs1.specials <- formula_num_specials(F.formula, lhs=1, rhs=0, specials = "data")
# should exactly be list(data(...))
num.variables.content <- length(attr(terms(F.formula, lhs=1, rhs=0, specials="data"), "variables"))
if(num.lhs1.specials != 1 || num.variables.content != 2)
return("Please specify exactly data() in the LHS.")
# Verify can parse inputs to special
l.data.args <- formula_parse_args_of_data(F.formula)
if(any(sapply(l.data.args, is, "error")))
err.msg <- c(err.msg, paste0("Please provide only arguments to data() which can be parsed!"))
# **TODO: check that also fails data()+1 ~ pnbd() and pnbd()+1
# ... no other special function than model in LHS1
# ***TODO: There is a bug in Formula: labels() is inconsistent in recognizing specials in the LHS
#
# Does not recognize abc() special in LHS1:
# # only special in lhs1
# labels(terms(as.Formula(abc()~n), lhs=1, rhs=0, specials="abc"))
# # also var in rhs1
# labels(terms(as.Formula(abc()~n), lhs=1, rhs=1, specials="abc"))
# # also special in rhs1
# labels(terms(as.Formula(abc()~xyz()), lhs=1, rhs=1, specials=c("abc", "xyz")))
# # also special and var in rhs1
# labels(terms(as.Formula(abc()~n+xyz()), lhs=1, rhs=1, specials=c("abc", "xyz")))
#
# Recognizes abc() in LHS1
# # when adding another variable in LHS1 besides special
# labels(terms(as.Formula(abc()+k~n), lhs=1, rhs=0, specials="abc"))
# # when adding another special in LHS1
# labels(terms(as.Formula(abc()+xyz()~n), lhs=1, rhs=0, specials=c("abc", "xyz")))
#
# Seems related that there is only a single special in LHS1. A single special in RHS1 is however always recognized
# labels(terms(as.Formula(~abc()), lhs=1, rhs=1, specials="abc"))
}
# Verify RHS ------------------------------------------------------------------------------------------
if("." %in% all.vars(formula(F.formula, rhs=1)))
return(paste0("Please choose exactly one of the following models as the first RHS: ",
paste0(paste0(name.specials.model, "()"), collapse = ", "),"."))
# Check that has exactly one model special and ..
num.model.specials <- formula_num_specials(F.formula, rhs=1, lhs=0, specials=name.specials.model)
F.terms.rhs1 <- terms(F.formula, lhs=0, rhs=1, specials=name.specials.model)
# ... no other special function than model in RHS1
if(num.model.specials !=1 || length(labels(F.terms.rhs1)) != 1)
err.msg <- c(err.msg, paste0("Please choose exactly one of the following models as the first RHS: ",
paste0(paste0(name.specials.model, "()"), collapse = ", "),"."))
# Formula too badly structured, unable to do further tests
if(length(err.msg)>0)
return(err.msg)
# Verify that can parse all args in model special ...
model <- formula_read_model_name(F.formula)
l.model.args <- formula_parse_args_of_special(F.formula = F.formula, name.special=model, from.lhs=0, from.rhs=1)
if(any(sapply(l.model.args, is, "error")))
err.msg <- c(err.msg, paste0("Please provide only arguments to ",model,"() which can be parsed!"))
# ... and none of the explicit args
if(any(c("verbose","optimx.args") %in% names(l.model.args)))
err.msg <- c(err.msg, paste0("Please do not specify arguments 'verbose' and 'optimx.args' in ",model,"()!"))
return(err.msg)
}
check_userinput_formula_data <- function(data){
if(missing(data))
return("Please provide an object of class clv.data, data.frame, or data.table for parameter 'data'!")
if(!is(data, "clv.data") && !is.data.frame(data) && !is.data.table(data)){
return("Please provide an object of class clv.data, data.frame, or data.table for parameter 'data'!")
}else{
return(c())
}
}
check_userinput_formula_cov <- function(cov){
if(missing(cov)){
return(c())
}
if(!is.data.frame(cov) && !is.data.table(cov)){
return("Please provide an object of class data.frame or data.table for parameter 'cov'!")
}
# if(!("Id"%in%colnames(cov))){
# return("Please provide covariate data with a column named 'Id'.")
# }
}
check_userinput_latentattrition_formulavsdata_LHS1 <- function(F.formula){
err.msg <- c()
# always requires LHS1
if(length(F.formula)[1] == 0){
return("Please specify a LHS with data() in the formula when supplying a data.frame/table for parameter data.")
}
# requires to have data special in LHS1
if(formula_num_specials(F.formula, lhs=1, rhs=0, specials="data") != 1){
return("Please specify a LHS with data() in the formula when supplying a data.frame/table for parameter data.")
}
# Verify only allowed args are given to data()
names.params.data <- names(formula_readout_special_arguments(F.formula = F.formula, from.lhs = 1, from.rhs = 0,
name.special = "data", params.as.chars.only = FALSE)[[1]])
if("" %in% names.params.data){
err.msg <- c(err.msg, "Please specify all inputs to data() as named parameters.")
}
# remove unnamed args because cannot be verified
names.params.data <- names.params.data[names.params.data != ""]
for(n in names.params.data){
if(!(n %in% c("unit", "split", "format"))){
err.msg <- c(err.msg, paste0("The parameter ",n," is not valid input to data()!"))
}
}
# already verified in formula alone that all args to data() are parsable
return(err.msg)
}
check_userinput_latentattrition_formulavsdata_RHS23 <- function(F.formula, names.cov.data.life, names.cov.data.trans){
err.msg <- c()
# verify the specified cov data is in clv.data
# "." is by definition always in the data but remove from names
vars.life <- setdiff(all.vars(formula(F.formula, lhs=0, rhs=2)), ".")
vars.trans <- setdiff(all.vars(formula(F.formula, lhs=0, rhs=3)), ".")
# may be character(0) if only "."
if(length(vars.life)){
if(!all(vars.life %in% names.cov.data.life)){
err.msg <- c(err.msg, "Not all lifetime covariates specified in the formula could be found in the data!")
}
}
if(length(vars.trans)){
if(!all(vars.trans %in% names.cov.data.trans)){
err.msg <- c(err.msg, "Not all transaction covariates specified in the formula could be found in the data!")
}
}
return(err.msg)
}
check_userinput_latentattrition_formulavsdata_RHS4 <- function(F.formula){
err.msg <- c()
# If has RHS4, may only be allowed ones
# "regularization" or "constraint"
# Check that has only allowed specials and nothing else allowed
if("." %in% all.vars(formula(F.formula, lhs=0, rhs=4))){
# no suitable data argument to terms() as required to resolve "."
err.msg <- c(err.msg, "Please do not use <.> in the fourth RHS.")
}else{
F.terms.rhs4 <- terms(F.formula, lhs=0, rhs=4, specials=c("regularization", "constraint"))
num.rhs4.specials <- formula_num_specials(F.formula, lhs=0, rhs=4, specials=c("regularization", "constraint"))
if(length(labels(F.terms.rhs4)) != num.rhs4.specials)
err.msg <- c(err.msg, "Please choose only from the following for the fourth RHS: regularization(), constraint().")
# if has regularization(), check that only once, with allowed args and are parsable
if(!is.null(attr(F.terms.rhs4, "specials")[["regularization"]])){
if(length(attr(F.terms.rhs4, "specials")[["regularization"]]) > 1)
err.msg <- c(err.msg, "Please specify regularization() only once!")
l.reg.args <- formula_parse_args_of_special(F.formula=F.formula, name.special="regularization", from.lhs=0, from.rhs=4)
names.reg.args <- names(l.reg.args)
if(!setequal(names.reg.args, c("life", "trans"))){
err.msg <- c(err.msg, "Please give specify arguments life and trans in regularization()! (ie regularization(trans=5, life=7) )")
}
# and each only given once
if(length(names.reg.args) != length(unique(names.reg.args))){
err.msg <- c(err.msg, "Please specify every argument in regularization() exactly once!")
}
if(any(sapply(l.reg.args, is, "error")) | !all(sapply(l.reg.args, is.numeric))){
err.msg <- c(err.msg, "Please specify every argument in regularization() as number!")
}
}
# if has constraint(), check that only names (not named arguments) and parsable
if(!is.null(attr(F.terms.rhs4, "specials")[["constraint"]])){
l.constr.args <- formula_readout_special_arguments(F.formula = F.formula, name.special="constraint",
from.lhs = 0, from.rhs=4, params.as.chars.only=FALSE)
# concat args in multiple constraint() specials
l.constr.args <- do.call(c, l.constr.args)
if(any(names(l.constr.args) != "")){
err.msg <- c(err.msg, "Please provide only unnamed arguments to constraint()!")
}
}
}
return(err.msg)
}
#' @importFrom Formula as.Formula
#' @importFrom stats terms
check_userinput_latentattrition_formulavsdata <- function(formula, data, cov){
err.msg <- c()
# formula is verified to be basic correct
F.formula <- as.Formula(formula)
# raw data
if(is.data.frame(data) || is.data.table(data)){
err.msg <- check_userinput_latentattrition_formulavsdata_LHS1(formula)
if(length(err.msg)){
return(err.msg)
}
}else{
if(!missing(cov)){
return("Please do not give covariate data if an object of clv.data is given for parameter data!")
}
if(length(F.formula)[1] != 0){
err.msg <- c(err.msg, "Please do not specify any LHS if a clv.data object is given for parameter data!")
}
}
# No covariate data given
# either clv.data w/o cov OR data.frame and no cov object
# nocov data: only 1 RHS
# excludes static and dyn cov
if(is(data, "clv.data") && !is(data, "clv.data.static.covariates")){
if(length(F.formula)[2] != 1){
err.msg <- c(err.msg, "The formula may only contain 1 part specifiying the model for data without covariates!")
}
}
if((is.data.frame(data)|| is.data.table(data)) && missing(cov)){
if(length(F.formula)[2] != 1){
err.msg <- c(err.msg, "The formula may only contain 1 part specifiying the model if no covariate data is given!")
}
}
# Covariate data
# either clv.data obj w/ cov OR data.frame/table with cov
# cov data: requires at least 3 RHS (model, trans, life), max 4
# includes static and dyn covs
if(is(data, "clv.data.static.covariates") || !(missing(cov))){
if(length(F.formula)[2] < 3){
err.msg <- c(err.msg, "The formula needs to specify the model as well as the transaction and the lifetime covariates for data with covariates!")
return(err.msg)
}
if(length(F.formula)[2] > 4){
err.msg <- c(err.msg, "The formula may consist of a maximum of 4 parts!")
}
# Verify RHS2&3
if(is(data, "clv.data.static.covariates")){
err.msg <- c(err.msg, check_userinput_latentattrition_formulavsdata_RHS23(F.formula, names.cov.data.life = [email protected],
names.cov.data.trans = [email protected]))
}else{
cov.names <- setdiff(colnames(cov), c("Id", "Cov.Date"))
err.msg <- c(err.msg, check_userinput_latentattrition_formulavsdata_RHS23(F.formula, names.cov.data.life = cov.names, names.cov.data.trans = cov.names))
}
if(length(err.msg)){
return(err.msg)
}
# Verify RHS4
if(length(F.formula)[2] == 4){
err.msg <- c(err.msg, check_userinput_latentattrition_formulavsdata_RHS4(F.formula))
}
}
return(err.msg)
}
# only works if special exists once
formula_parse_args_of_special <- function(F.formula, name.special, from.lhs, from.rhs){
# read out args of "model" special. First element because has special only once
l.args <- formula_readout_special_arguments(F.formula = F.formula, name.special=name.special,
from.lhs = from.lhs, from.rhs=from.rhs, params.as.chars.only=FALSE)[[1]]
# Turn args of special function which are chars into objects
# error obj if not parse-able
return(lapply(l.args, function(arg){
if(is.null(arg)){
return(arg)
}else{
return(tryCatch(eval(parse(text=arg)),
error=function(e)e))
}
}))
}
#' @importFrom stats terms
formula_num_specials <- function(F.formula, lhs, rhs, specials){
F.terms <- terms(F.formula, lhs=lhs, rhs=rhs, specials=specials)
return(sum(sapply(attr(F.terms, "specials"), length)))
}
#' @importFrom stats terms formula
formula_read_model_name <- function(F.formula){
F.terms.rhs1 <- terms(formula(F.formula, lhs=0, rhs=1), specials=c("pnbd", "bgnbd", "ggomnbd", "gg"))
return(names(unlist(attr(F.terms.rhs1, "specials"))))
}
# Needed to parse inputs to data() special because parameters needs to be parsed differently
formula_parse_args_of_data <- function(F.formula){
# list of chars
l.args <- formula_readout_special_arguments(F.formula = F.formula, name.special = "data",
from.lhs = 1, from.rhs = 0, params.as.chars.only = FALSE)[[1]]
if("split" %in% names(l.args)){
user.split <- l.args[["split"]]
# leave NULL if is NULL
if(!is.null(user.split)){
# Parse split to numeric
l.args[["split"]] <- tryCatch(eval(parse(text=user.split)), error=function(e)e)
}
}
# unit and format are left as os (characters or NULL)
return(l.args)
}
# params.as.chars.only=TRUE returns a vector of chars with the parameter names in it.
# Used to readout given param name
# Example: continuous(X1, X2)
# => c("X1", "X2")
# params.as.chars.only=FALSE returns a list of list. The inner list is named after the arg
# and the element contains the actual input as char. Elements in sub-lists have
# to be named so that they do not get matched to unintended args because of their
# position (ie X2 to g)
# Example: IIV(g=x2, iiv=gp, X1, X2) + IIV()
# => list(list(g="x2",iiv="gp", X1="X1",X2="X2"), list(..),..)
#' @importFrom stats terms formula
formula_readout_special_arguments <- function(F.formula, name.special, from.lhs, from.rhs, params.as.chars.only = TRUE){
F.terms <- terms(formula(F.formula, lhs=from.lhs, rhs=from.rhs), specials = name.special)
# Read out positions in formula
# NULL if there are no specials
ind.special <- attr(F.terms, "specials")[[name.special]]
# End if there are no such special in the formula
if(is.null(ind.special))
return(NULL)
# Read out commands
# +1 because first is "list"
lang.special <- attr(F.terms, "variables")[1L+ind.special]
# Obtain column name is indicated in the function
# create function that is exectuted and simply returns the specified inputs as strings
# create new function named after special which simply returns the input given
assign(x = paste0("fct.", name.special), value = function(...){ return(match.call()[-1])})
# Execute this function for each special by adding "fct." at the beginning and evaluating
names.special <- lapply(paste0("fct.",lang.special), FUN=function(str){
eval(expr=parse(text=str))})
if(params.as.chars.only){
# Return vector with (unique) parameter names only
names.special <- lapply(names.special, function(call){as.character(as.list(call))})
names.special <- unique(unlist(names.special))
names(names.special) <- names.special
}else{
# return list with names=args, entry = arg data
# here:list of language object
names.special <- lapply(names.special, as.list)
# here: nested list of arg-lists
names.special <- lapply(names.special, lapply, deparse) # make char representation
# replace the "", "NULL" as actual NULLs
names.special <- lapply(names.special, lapply, function(char.arg){if(char.arg%in%c("NULL", "", "NA")) NULL else char.arg})
# Name unnamed elements (=args) in sublists after the elements
# names.special <- lapply(names.special, function(subl){
# unnamed.ind <- which(names(subl)=="")
# names(subl)[unnamed.ind] <- subl[unnamed.ind]
# return(subl)})
# Does not need be unique per list, will not mixup entries if regressors are named same as g/iiv
# rather it is caught that they may not be twice
}
return(names.special)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_latentattrition.R
|
#' @name pmf
#'
#' @title Probability Mass Function
#' @param object The fitted transaction model.
#' @param x Vector of positive integer numbers (>=0) indicating the number of repeat transactions x for
#' which the PMF should be calculated.
#'
#' @description
#' Calculate P(X(t)=x), the probability to make exactly \code{x} repeat transactions in
#' the interval (0, t]. This interval is in the estimation period and excludes values of \code{t=0}.
#' Note that here \code{t} is defined as the observation period \code{T.cal} which differs by customer.
#'
#'
#' @returns
#' Returns a \code{data.table} with ids and depending on \code{x}, multiple columns of PMF values, each column
#' for one value in \code{x}.
#' \item{Id}{customer identification}
#' \item{pmf.x.Y}{PMF values for Y number of transactions}
#'
#' @seealso The model fitting functions \code{\link[CLVTools:pnbd]{pnbd},
#' \link[CLVTools:bgnbd]{bgnbd}, \link[CLVTools:ggomnbd]{ggomnbd}}.
#' @seealso \code{\link[CLVTools:plot.clv.fitted.transactions]{plot}} to visually compare
#' the PMF values against actuals.
#'
#' @examples
#' \donttest{
#' data("cdnow")
#'
#' # Fit the ParetoNBD model on the CDnow data
#' pnbd.cdnow <- pnbd(clvdata(cdnow, time.unit="w",
#' estimation.split=37,
#' date.format="ymd"))
#'
#' # Calculate the PMF for 0 to 10 transactions
#' # in the estimation period
#' pmf(pnbd.cdnow, x=0:10)
#'
#' # Compare vs. actuals (CBS in estimation period):
#' # x mean(pmf) actual percentage of x
#' # 0 0.616514 1432/2357= 0.6075519
#' # 1 0.168309 436/2357 = 0.1849809
#' # 2 0.080971 208/2357 = 0.0882478
#' # 3 0.046190 100/2357 = 0.0424268
#' # 4 0.028566 60/2357 = 0.0254561
#' # 5 0.018506 36/2357 = 0.0152737
#' # 6 0.012351 27/2357 = 0.0114552
#' # 7 0.008415 21/2357 = 0.0089096
#' # 8 0.005822 5/2357 = 0.0021213
#' # 9 0.004074 4/2357 = 0.0016971
#' # 10 0.002877 7/2357 = 0.0029699
#' }
#'
NULL
#' @exportMethod pmf
setGeneric(name = "pmf", def = function(object, x=0:5)
standardGeneric("pmf"))
#' @include class_clv_fitted_transactions.R
#' @rdname pmf
setMethod(f = "pmf", signature = signature(object="clv.fitted.transactions"), definition = function(object, x=0:5){
check_err_msg(check_user_data_integer_vector_greater0(vec=x, var.name="x"))
return(clv.template.controlflow.pmf(clv.fitted=object, x=x))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_pmf.R
|
#' @name pnbd
#'
#' @title Pareto/NBD models
#'
#' @template template_params_estimate
#' @template template_params_estimate_cov
#' @template template_param_optimxargs
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @param use.cor Whether the correlation between the transaction and lifetime process should be estimated.
#' @param start.param.cor Start parameter for the optimization of the correlation.
#'
#' @description
#' Fits Pareto/NBD models on transactional data with and without covariates.
#'
#'
#' @details
#' Model parameters for the Pareto/NBD model are \code{alpha, r, beta, and s}. \cr
#' \code{s}: shape parameter of the Gamma distribution for the lifetime process.
#' The smaller s, the stronger the heterogeneity of customer lifetimes. \cr
#' \code{beta}: rate parameter for the Gamma distribution for the lifetime process. \cr
#' \code{r}: shape parameter of the Gamma distribution of the purchase process.
#' The smaller r, the stronger the heterogeneity of the purchase process.\cr
#' \code{alpha}: rate parameter of the Gamma distribution of the purchase process.
#'
#' Based on these parameters, the average purchase rate while customers are active
#' is r/alpha and the average dropout rate is s/beta.
#'
#' Ideally, the starting parameters for r and s represent your best guess
#' concerning the heterogeneity of customers in their buy and die rate.
#' If covariates are included into the model additionally parameters for the
#' covariates affecting the attrition and the purchase process are part of the model.
#'
#' If no start parameters are given, 1.0 is used for all model parameters and 0.1 for covariate parameters.
#' The model start parameters are required to be > 0.
#'
#' \subsection{The Pareto/NBD model}{
#' The Pareto/NBD is the first model addressing the issue of modeling customer purchases and
#' attrition simultaneously for non-contractual settings. The model uses a Pareto distribution,
#' a combination of an Exponential and a Gamma distribution, to explicitly model customers'
#' (unobserved) attrition behavior in addition to customers' purchase process.\cr
#' In general, the Pareto/NBD model consist of two parts. A first process models the purchase
#' behavior of customers as long as the customers are active. A second process models customers'
#' attrition. Customers live (and buy) for a certain unknown time until they become inactive
#' and "die". Customer attrition is unobserved. Inactive customers may not be reactivated.
#' For technical details we refer to the original paper by Schmittlein, Morrison and Colombo
#' (1987) and the detailed technical note of Fader and Hardie (2005).
#' }
#'
#' \subsection{Pareto/NBD model with static covariates}{
#' The standard Pareto/NBD model captures heterogeneity was solely using Gamma distributions.
#' However, often exogenous knowledge, such as for example customer demographics, is available.
#' The supplementary knowledge may explain part of the heterogeneity among the customers and
#' therefore increase the predictive accuracy of the model. In addition, we can rely on these
#' parameter estimates for inference, i.e. identify and quantify effects of contextual factors
#' on the two underlying purchase and attrition processes. For technical details we refer to
#' the technical note by Fader and Hardie (2007).
#' }
#'
#' \subsection{Pareto/NBD model with dynamic covariates}{
#' In many real-world applications customer purchase and attrition behavior may be
#' influenced by covariates that vary over time. In consequence, the timing of a purchase
#' and the corresponding value of at covariate a that time becomes relevant. Time-varying
#' covariates can affect customer on aggregated level as well as on an individual level:
#' In the first case, all customers are affected simultaneously, in the latter case a
#' covariate is only relevant for a particular customer. For technical details we refer to
#' the paper by Bachmann, Meierer and Näf (2020).
#' }
#'
#' @note
#'
#' The Pareto/NBD model with dynamic covariates can currently not be fit with data that has a temporal resolution
#' of less than one day (data that was built with time unit \code{hours}).
#'
#' @return Depending on the data object on which the model was fit, \code{pnbd} returns either an object of
#' class \linkS4class{clv.pnbd}, \linkS4class{clv.pnbd.static.cov}, or \linkS4class{clv.pnbd.dynamic.cov}.
#'
#' @template template_clvfitted_returnvalue
#'
#' @template template_clvfittedtransactions_seealso
#' @seealso \code{\link[CLVTools:SetDynamicCovariates]{SetDynamicCovariates}} to add dynamic covariates on which the \code{pnbd} model can be fit.
#'
#'
#' @template template_references_pnbd
#'
#' @templateVar name_model_short pnbd
#' @templateVar vec_startparams_model c(r=0.5, alpha=15, s=0.5, beta=10)
#' @template template_examples_nocovmodelinterface
#' @examples \donttest{
#' # Estimate correlation as well
#' pnbd(clv.data.apparel, use.cor = TRUE)
#' }
#' @templateVar name_model_short pnbd
#' @template template_examples_staticcovmodelinterface
#' @examples
#' # Add dynamic covariates data to the data object
# # To estimate the PNBD model with dynamic covariates,
#' # add dynamic covariates to the data
#' \donttest{
#' \dontrun{
#' data("apparelDynCov")
#' clv.data.dyn.cov <-
#' SetDynamicCovariates(clv.data = clv.data.apparel,
#' data.cov.life = apparelDynCov,
#' data.cov.trans = apparelDynCov,
#' names.cov.life = c("Marketing", "Gender", "Channel"),
#' names.cov.trans = c("Marketing", "Gender", "Channel"),
#' name.date = "Cov.Date")
#'
#'
#' # Fit PNBD with dynamic covariates
#' pnbd(clv.data.dyn.cov)
#'
#' # The same fitting options as for the
#' # static covariate are available
#' pnbd(clv.data.dyn.cov, reg.lambdas = c(trans=10, life=2))
#' }
#' }
#'
NULL
#' @exportMethod pnbd
setGeneric("pnbd", def = function(clv.data, start.params.model=c(), use.cor = FALSE, start.param.cor=c(),
optimx.args=list(), verbose=TRUE, ...)
standardGeneric("pnbd"))
#' @include class_clv_data.R
#' @rdname pnbd
setMethod("pnbd", signature = signature(clv.data="clv.data"), definition = function(clv.data,
start.params.model=c(),
use.cor = FALSE,
start.param.cor=c(),
optimx.args=list(),
verbose=TRUE,...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.pnbd(cl=cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model, use.cor = use.cor,
start.param.cor = start.param.cor, optimx.args = optimx.args, verbose=verbose))
})
#' @include class_clv_data_staticcovariates.R
#' @rdname pnbd
setMethod("pnbd", signature = signature(clv.data="clv.data.static.covariates"), definition = function(clv.data,
start.params.model=c(),
use.cor = FALSE,
start.param.cor=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(),start.params.constr=c(),
reg.lambdas = c(), ...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
obj <- clv.pnbd.static.cov(cl=cl, clv.data=clv.data)
# Do the estimate controlflow / process steps with the static cov object
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model, use.cor = use.cor, start.param.cor = start.param.cor,
optimx.args = optimx.args, verbose=verbose,
names.cov.life=names.cov.life, names.cov.trans=names.cov.trans,
start.params.life=start.params.life, start.params.trans=start.params.trans,
names.cov.constr=names.cov.constr,start.params.constr=start.params.constr,
reg.lambdas = reg.lambdas))
})
#' @include class_clv_data_dynamiccovariates.R
#' @rdname pnbd
setMethod("pnbd", signature = signature(clv.data="clv.data.dynamic.covariates"), definition = function(clv.data,
start.params.model=c(),
use.cor = FALSE,
start.param.cor=c(),
optimx.args=list(),
verbose=TRUE,
names.cov.life=c(), names.cov.trans=c(),
start.params.life=c(), start.params.trans=c(),
names.cov.constr=c(),start.params.constr=c(),
reg.lambdas = c(), ...){
check_err_msg(check_user_data_emptyellipsis(...))
cl <- match.call(call = sys.call(-1), expand.dots = TRUE)
if(is([email protected], "clv.time.datetime")){
stop("This model currently cannot be fitted with data that has a temporal resolution of less than 1d (ie hours).")
}
obj <- clv.pnbd.dynamic.cov(cl = cl, clv.data=clv.data)
return(clv.template.controlflow.estimate(clv.fitted=obj, start.params.model = start.params.model, use.cor = use.cor, start.param.cor = start.param.cor,
optimx.args = optimx.args, verbose=verbose,
names.cov.life=names.cov.life, names.cov.trans=names.cov.trans,
start.params.life=start.params.life, start.params.trans=start.params.trans,
names.cov.constr=names.cov.constr,start.params.constr=start.params.constr,
reg.lambdas = reg.lambdas))
})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_pnbd.R
|
# S3 predict for clv.fitted.spending ------------------------------------------------------------------------------
#' @title Predict customers' future spending
#'
#' @param object A fitted spending model for which prediction is desired.
#' @param newdata A clv data object for which predictions should be made with the fitted model. If none or NULL is given, predictions are made for the data on which the model was fit.
#'
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @description
#' Predict customer's future mean spending per transaction and compare it to the actual mean spending in the holdout period.
#'
#' @details
#' If \code{newdata} is provided, the individual customer statistics underlying the model are calculated
#' the same way as when the model was fit initially. Hence, if \code{remove.first.transaction} was \code{TRUE},
#' this will be applied to \code{newdata} as well.
#'
#' @seealso models to predict spending: \link{gg}.
#' @seealso models to predict transactions: \link{pnbd}, \link{bgnbd}, \link{ggomnbd}.
#' @seealso \code{\link[CLVTools:predict.clv.fitted.transactions]{predict}} for transaction models
#'
#'
#' @return An object of class \code{data.table} with columns:
#' \item{Id}{The respective customer identifier}
#' \item{actual.mean.spending}{Actual mean spending per transaction in the holdout period. Only if there is a holdout period otherwise it is not reported.}
#' \item{predicted.mean.spending}{The mean spending per transaction as predicted by the fitted spending model.}
#'
#'
#' @examples
#' \donttest{
#' data("apparelTrans")
#'
#' # Fit gg model on data
#' apparel.holdout <- clvdata(apparelTrans, time.unit="w",
#' estimation.split=37, date.format="ymd")
#' apparel.gg <- gg(apparel.holdout)
#'
#' # Predict customers' future mean spending per transaction
#' predict(apparel.gg)
#'
#' }
#'
#' @importFrom stats predict
#' @method predict clv.fitted.spending
#' @export
predict.clv.fitted.spending <- function(object, newdata=NULL, verbose=TRUE, ...){
check_err_msg(check_user_data_emptyellipsis(...))
return(clv.template.controlflow.predict(clv.fitted=object, verbose=verbose, user.newdata=newdata))
}
# . S4 definition ----------------------------------------------------------------------------------------
# S4 method to forward to S3 method
#' @include all_generics.R class_clv_fitted_spending.R
#' @exportMethod predict
#' @rdname predict.clv.fitted.spending
setMethod(f = "predict", signature = signature(object="clv.fitted.spending"), predict.clv.fitted.spending)
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_predict_clvfittedspending.R
|
# S3 predict for clv.fitted.transactions ----------------------------------------------------------------------------------
#' @title Predict CLV from a fitted transaction model
#' @param object A fitted clv transaction model for which prediction is desired.
#' @param newdata A clv data object for which predictions should be made with the fitted model. If none or NULL is given, predictions are made for the data on which the model was fit.
#' @param predict.spending Whether and how to predict spending and based on it also CLV, if possible. See details.
#' @param continuous.discount.factor continuous discount factor to use to calculate \code{DERT/DECT}
#' @templateVar prefix {}
#' @templateVar plot_or_predict predict
#' @template template_param_predictionend
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @description
#'
#' Probabilistic customer attrition models predict in general three expected characteristics for every customer:
#' \itemize{
#' \item "conditional expected transactions" (\code{CET}), which is the number of transactions to expect from a customer
#' during the prediction period,
#' \item "probability of a customer being alive" (\code{PAlive}) at the end of the estimation period and
#' \item "discounted expected residual transactions" (\code{DERT}) for every customer, which is the total number of
#' transactions for the residual lifetime of a customer discounted to the end of the estimation period.
#' In the case of time-varying covariates, instead of \code{DERT}, "discounted expected conditional transactions" (\code{DECT})
#' is predicted. \code{DECT} does only cover a finite time horizon in contrast to \code{DERT}.
#' For \code{continuous.discount.factor=0}, \code{DECT} corresponds to \code{CET}.
#'}
#'
#' In order to derive a monetary value such as CLV, customer spending has to be considered.
#' If the \code{clv.data} object contains spending information, customer spending can be predicted using a Gamma/Gamma spending model for
#' parameter \code{predict.spending} and the predicted CLV is be calculated (if the transaction model supports \code{DERT/DECT}).
#' In this case, the prediction additionally contains the following two columns:
#' \itemize{
#' \item "predicted.mean.spending", the mean spending per transactions as predicted by the spending model.
#' \item "CLV", the customer lifetime value. CLV is the product of DERT/DECT and predicted spending.
#'}
#'
#' @details \code{predict.spending} indicates whether to predict customers' spending and if so, the spending model to use.
#' Accepted inputs are either a logical (\code{TRUE/FALSE}), a method to fit a spending model (i.e. \code{\link{gg}}), or
#' an already fitted spending model. If provided \code{TRUE}, a Gamma-Gamma model is fit with default options. If argument
#' \code{newdata} is provided, the spending model is fit on \code{newdata}. Predicting spending is only possible if
#' the transaction data contains spending information. See examples for illustrations of valid inputs.
#'
#' @template template_details_newdata
#'
#' @template template_details_predictionend
#'
#' @details \code{continuous.discount.factor} is the continuous rate used to discount the expected residual
#' transactions (\code{DERT/DECT}). An annual rate of (100 x d)\% equals a continuous rate delta = ln(1+d).
#' To account for time units which are not annual, the continuous rate has to be further adjusted
#' to delta=ln(1+d)/k, where k are the number of time units in a year.
#'
#'
#' @seealso models to predict transactions: \link{pnbd}, \link{bgnbd}, \link{ggomnbd}.
#' @seealso models to predict spending: \link{gg}.
#' @seealso \code{\link[CLVTools:predict.clv.fitted.spending]{predict}} for spending models
#'
#'
#' @return
#' An object of class \code{data.table} with columns:
#' \item{Id}{The respective customer identifier}
#' \item{period.first}{First timepoint of prediction period}
#' \item{period.last}{Last timepoint of prediction period}
#' \item{period.length}{Number of time units covered by the period indicated by \code{period.first} and \code{period.last} (including both ends).}
#' \item{PAlive}{Probability to be alive at the end of the estimation period}
#' \item{CET}{The Conditional Expected Transactions}
#' \item{DERT or DECT}{Discounted Expected Residual Transactions or Discounted Expected Conditional Transactions for dynamic covariates models}
#' \item{actual.x}{Actual number of transactions until prediction.end. Only if there is a holdout period and the prediction ends in it, otherwise it is not reported.}
#' \item{actual.total.spending}{Actual total spending until prediction.end. Only if there is a holdout period and the prediction ends in it, otherwise it is not reported.}
#' \item{predicted.mean.spending}{The mean spending per transactions as predicted by the spending model.}
#' \item{predicted.CLV}{Customer Lifetime Value based on \code{DERT/DECT} and \code{predicted.mean.spending}.}
#'
#' @examples
#'
#' \donttest{
#'
#' data("apparelTrans")
#' # Fit pnbd standard model on data, WITH holdout
#' apparel.holdout <- clvdata(apparelTrans, time.unit="w",
#' estimation.split=37, date.format="ymd")
#' apparel.pnbd <- pnbd(apparel.holdout)
#'
#' # Predict until the end of the holdout period
#' predict(apparel.pnbd)
#'
#' # Predict until 10 periods (weeks in this case) after
#' # the end of the 37 weeks fitting period
#' predict(apparel.pnbd, prediction.end = 10) # ends on 2010-11-28
#'
#' # Predict until 31th Dec 2016 with the timepoint as a character
#' predict(apparel.pnbd, prediction.end = "2016-12-31")
#'
#' # Predict until 31th Dec 2016 with the timepoint as a Date
#' predict(apparel.pnbd, prediction.end = lubridate::ymd("2016-12-31"))
#'
#'
#' # Predict future transactions but not spending and CLV
#' predict(apparel.pnbd, predict.spending = FALSE)
#'
#' # Predict spending by fitting a Gamma-Gamma model
#' predict(apparel.pnbd, predict.spending = gg)
#'
#' # Fit a spending model separately and use it to predict spending
#' apparel.gg <- gg(apparel.holdout, remove.first.transaction = FALSE)
#' predict(apparel.pnbd, predict.spending = apparel.gg)
#'
#'
#' # Fit pnbd standard model WITHOUT holdout
#' pnc <- pnbd(clvdata(apparelTrans, time.unit="w", date.format="ymd"))
#'
#' # This fails, because without holdout, a prediction.end is required
#' \dontrun{
#' predict(pnc)
#' }
#'
#' # But it works if providing a prediction.end
#' predict(pnc, prediction.end = 10) # ends on 2016-12-17
#' }
#'
#' @importFrom stats predict
#' @method predict clv.fitted.transactions
#' @aliases predict
#' @export
predict.clv.fitted.transactions <- function(object, newdata=NULL, prediction.end=NULL, predict.spending=gg,
continuous.discount.factor=0.1, verbose=TRUE, ...){
check_err_msg(check_user_data_emptyellipsis(...))
# If it was not explicitly passed in the call, the spending model should only be applied
# it there is spending data. Otherwise, predict does not work out-of-the-box for
# data object w/o spending
if(missing(predict.spending)){
# Only need to disable if has no spending, default argument is a spending model
# (ie prediction.end = gg already)
if(!clv.data.has.spending([email protected])){
predict.spending <- FALSE
}
}
return(clv.template.controlflow.predict(clv.fitted=object, prediction.end=prediction.end, predict.spending=predict.spending,
continuous.discount.factor=continuous.discount.factor, verbose=verbose, user.newdata=newdata))
}
# . S4 definition ----------------------------------------------------------------------------------------
# S4 method to forward to S3 method
#' @include all_generics.R class_clv_fitted_transactions.R
#' @exportMethod predict
#' @rdname predict.clv.fitted.transactions
setMethod(f = "predict", signature = signature(object="clv.fitted.transactions"), predict.clv.fitted.transactions)
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_predict_clvfittedtransactions.R
|
#' @template template_setdynamiccov
#' @include class_clv_data.R
#' @include class_clv_data_staticcovariates.R
#' @include class_clv_data_dynamiccovariates.R
#' @export
SetDynamicCovariates <- function(clv.data, data.cov.life, data.cov.trans, names.cov.life, names.cov.trans, name.id="Id", name.date="Date"){
Cov.Date <- Id <- NULL
# Do not use S4 generics to catch other classes because it creates confusing documentation entries
# suggesting that there are legitimate methods for these
if(!is(clv.data, "clv.data"))
stop("Covariate data can only be added to objects of class clv.data!")
if(is(clv.data, "clv.data.static.covariates") | is(clv.data, "clv.data.dynamic.covariates"))
stop("Cannot set dynamic covariates because this object has covariates set already!", call. = FALSE)
# Basic inputchecks ---------------------------------------------------------------------
# for parameters name
# Check if data has basic properties, otherwise cannot process column names
if(!is.data.frame(data.cov.life) | !is.data.frame(data.cov.trans))
check_err_msg("Only covariate data of type data.frame or data.table can be processed!")
if(nrow(data.cov.life) == 0 | nrow(data.cov.trans) == 0)
check_err_msg("Covariate data may not be empty!")
err.msg <- c()
err.msg <- c(err.msg, check_userinput_datanocov_namescov(names.cov=names.cov.life, data.cov.df=data.cov.life, name.of.covariate="Lifetime"))
err.msg <- c(err.msg, check_userinput_datanocov_namescov(names.cov=names.cov.trans, data.cov.df=data.cov.trans, name.of.covariate="Transaction"))
# name id in both covariate data
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.id, data=data.cov.life))
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.id, data=data.cov.trans))
# name date in both covariate data
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.date, data=data.cov.life))
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.date, data=data.cov.trans))
check_err_msg(err.msg)
if(any(name.date %in% names.cov.life) | any(name.date %in% names.cov.trans))
check_err_msg("The name for Date cannot also be used as a Covariate.")
# Convert covariate data to data.table to do more sophisticated checks -----------------------------------------
data.cov.life <- copy(data.cov.life)
data.cov.trans <- copy(data.cov.trans)
if(!is.data.table(data.cov.life))
setDT(data.cov.life)
if(!is.data.table(data.cov.trans))
setDT(data.cov.trans)
# Check and convert Id and Date ---------------------------------------------------------------------------------
# Id is correct datatype
err.msg <- c(err.msg, check_userinput_data_id(dt.data = data.cov.life, name.id = name.id, name.var="Lifetime covariate"))
err.msg <- c(err.msg, check_userinput_data_id(dt.data = data.cov.trans, name.id = name.id, name.var="Transaction covariate"))
# Date is correct datatype
err.msg <- c(err.msg, check_userinput_data_date(dt.data = data.cov.life, name.date = name.date, name.var="Lifetime covariate"))
err.msg <- c(err.msg, check_userinput_data_date(dt.data = data.cov.trans, name.date = name.date, name.var="Transaction covariate"))
check_err_msg(err.msg)
# need to subset to only the relevant columns here already in case there is already a columns Id in the data
# otherwise renaming leads to 2 columns with the same name
data.cov.life <- data.cov.life[, .SD, .SDcols = c(name.id, name.date, names.cov.life)]
data.cov.trans <- data.cov.trans[, .SD, .SDcols = c(name.id, name.date, names.cov.trans)]
# Cannot proceed if there are any NAs (conversion + if(), ..)
if(anyNA(data.cov.life))
err.msg <- c(err.msg, paste0("The Lifetime covariate data may not contain any NAs!"))
if(anyNA(data.cov.trans))
err.msg <- c(err.msg, paste0("The Transaction covariate data may not contain any NAs!"))
check_err_msg(err.msg)
setnames(data.cov.life, old = name.id, new = "Id")
setnames(data.cov.trans, old = name.id, new = "Id")
setnames(data.cov.life, old = name.date, new = "Cov.Date")
setnames(data.cov.trans, old = name.date, new = "Cov.Date")
data.cov.life[, Id := .convert_userinput_dataid(id.data = Id)]
data.cov.trans[, Id := .convert_userinput_dataid(id.data = Id)]
data.cov.life[, Cov.Date := clv.time.convert.user.input.to.timepoint([email protected], user.timepoint = Cov.Date)]
data.cov.trans[, Cov.Date := clv.time.convert.user.input.to.timepoint([email protected], user.timepoint = Cov.Date)]
setkeyv(data.cov.life, cols = c("Id", "Cov.Date"))
setkeyv(data.cov.trans, cols = c("Id", "Cov.Date"))
# Required dates for cov datea -------------------------------------------------------------------------
# Cut covariate data to range
# allows for more data than the required range
# speeds up tests
# The maximum cov period is not fixed by holdout or estimation end but rather
# only needs to be at least this long. The user might supply longer cov data.
# It is then verified in the input checks (datadyncov_datadyncovspecific), that
# there are cov dates of the same length up to dt.required.dates[, max(Cov.Date)] for all users
tp.max.cov.date <- max([email protected]@timepoint.holdout.end,
[email protected]@timepoint.estimation.end,
data.cov.life[, max(Cov.Date)],
data.cov.trans[, max(Cov.Date)])
# all required covariate dates in range (from floor_tu to floor_tu and spaced by time.unit)
# estimation.start is always required lower end
dt.required.dates <- clv.time.sequence.of.covariate.timepoints(clv.time = [email protected],
tp.start = [email protected]@timepoint.estimation.start,
tp.end = tp.max.cov.date)
# Cut to range, if needed
# Only timepoints lower than min(Cov.Date) are not needed and can be cut
# The dt.required.dates[, max(Cov.Date)] are the longest possible anyway (see
# definition of tp.max.cov.date), and no cov would be cut
timepoint.cut.lower <- dt.required.dates[, min(Cov.Date)]
if(data.cov.life[, any(Cov.Date < timepoint.cut.lower)]){
# if(verbose)
message("The Lifetime covariate data before ",timepoint.cut.lower," (period of estimation start) is cut off.")
data.cov.life <- data.cov.life[Cov.Date >= timepoint.cut.lower]
}
if(data.cov.trans[, any(Cov.Date < timepoint.cut.lower)]){
# if(verbose)
message("The Transaction covariate data before ",timepoint.cut.lower," (period of estimation start) is cut off.")
data.cov.trans <- data.cov.trans[Cov.Date >= timepoint.cut.lower]
}
# should not be required, but be sure
setkeyv(data.cov.life, c("Id", "Cov.Date"))
setkeyv(data.cov.trans, c("Id", "Cov.Date"))
# Dyncov specific checks ---------------------------------------------------------------------------------------
# Dynamic cov specific checks on covariate data
# only after if is DT because heavily relies on it for efficency
# only after Id is character because needed to compare to data.transaction Id
# only on the range to which it was cut
dt.required.ids <- unique([email protected][, "Id"])
err.msg <- c(err.msg, check_userinput_datadyncov_datadyncovspecific(dt.data.dyn.cov = data.cov.life,
clv.time = [email protected],
names.cov = names.cov.life,
dt.required.dates = dt.required.dates,
dt.required.ids = dt.required.ids,
name.of.covariate = "Lifetime"))
err.msg <- c(err.msg, check_userinput_datadyncov_datadyncovspecific(dt.data.dyn.cov = data.cov.trans,
clv.time = [email protected],
names.cov = names.cov.trans,
dt.required.dates = dt.required.dates,
dt.required.ids = dt.required.ids,
name.of.covariate = "Transaction"))
check_err_msg(err.msg)
# All checks passed
# Convert the covariate data to dummies ---------------------------------------------------------------
# keep numbers, char/factors to dummies
l.covs.life <- convert_userinput_covariatedata(dt.cov.data = data.cov.life, names.cov=names.cov.life)
l.covs.trans <- convert_userinput_covariatedata(dt.cov.data = data.cov.trans, names.cov=names.cov.trans)
# The cov names now are different because of the dummies!
data.cov.life <- l.covs.life$data.cov
data.cov.trans <- l.covs.trans$data.cov
names.cov.life <- l.covs.life$final.names.cov
names.cov.trans <- l.covs.trans$final.names.cov
# Add upper and lower covariate interval bounds --------------------------------------------------------
data.cov.life <- pnbd_dyncov_covariate_add_interval_bounds(dt.cov = data.cov.life, clv.time = [email protected])
data.cov.trans <- pnbd_dyncov_covariate_add_interval_bounds(dt.cov = data.cov.trans, clv.time = [email protected])
# Create and return dyncov data object -----------------------------------------------------------------
setcolorder(data.cov.life, c("Id", "Cov.Date", "tp.cov.lower", "tp.cov.upper", names.cov.life))
setcolorder(data.cov.trans, c("Id", "Cov.Date", "tp.cov.lower", "tp.cov.upper", names.cov.trans))
setkeyv(data.cov.life, cols = c("Id", "Cov.Date", "tp.cov.lower", "tp.cov.upper"))
setkeyv(data.cov.trans, cols = c("Id", "Cov.Date", "tp.cov.lower", "tp.cov.upper"))
return(clv.data.dynamic.covariates(no.cov.obj = clv.data,
data.cov.life = data.cov.life,
data.cov.trans = data.cov.trans,
names.cov.data.life = names.cov.life,
names.cov.data.trans = names.cov.trans))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_setdynamiccovariates.R
|
#' @template template_setstaticcov
#' @export
SetStaticCovariates <- function(clv.data, data.cov.life, data.cov.trans, names.cov.life, names.cov.trans, name.id="Id"){
Id <- NULL
# Do not use S4 generics to catch other classes because it creates confusing documentation entries
# suggesting that there are legitimate methods for these
if(!is(clv.data, "clv.data"))
stop("Covariate data can only be added to objects of class clv.data!")
if(is(clv.data, "clv.data.static.covariates") | is(clv.data, "clv.data.dynamic.covariates"))
stop("Cannot set static covariates because this object has covariates set already!", call. = FALSE)
# Basic inputchecks ---------------------------------------------------------------------
# for parameters
# Check if data has basic properties, otherwise cannot process column names
if(!is.data.frame(data.cov.life) | !is.data.frame(data.cov.trans))
check_err_msg("Only covariate data of type data.frame or data.table can be processed!")
if(nrow(data.cov.life) == 0 | nrow(data.cov.trans) == 0)
check_err_msg("Covariate data may not be empty!")
err.msg <- c()
err.msg <- c(err.msg, check_userinput_datanocov_namescov(names.cov=names.cov.life, data.cov.df=data.cov.life, name.of.covariate="Lifetime"))
err.msg <- c(err.msg, check_userinput_datanocov_namescov(names.cov=names.cov.trans, data.cov.df=data.cov.trans, name.of.covariate="Transaction"))
# name id in both covariate data
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.id, data=data.cov.life))
err.msg <- c(err.msg, check_userinput_datanocov_columnname(name.col=name.id, data=data.cov.trans))
check_err_msg(err.msg)
# Convert covariate data to data.table and check -----------------------------------------
# to better process in the check and convert function *_datacov
# Copy data as it will be manipulated by reference
data.cov.life <- copy(data.cov.life)
data.cov.trans <- copy(data.cov.trans)
if(!is.data.table(data.cov.life))
setDT(data.cov.life)
if(!is.data.table(data.cov.trans))
setDT(data.cov.trans)
setkeyv(data.cov.life, cols = name.id)
setkeyv(data.cov.trans, cols = name.id)
# make Id to char before comparing it to Id in data.transaction
err.msg <- c(err.msg, check_userinput_data_id(dt.data=data.cov.life, name.id=name.id, name.var="Lifetime covariate data"))
err.msg <- c(err.msg, check_userinput_data_id(dt.data=data.cov.trans, name.id=name.id, name.var="Transaction covariate data"))
check_err_msg(err.msg)
# need to subset to relevant columns only in case there is already a columns Id in the data
# otherwise renaming leads to 2 columns with the same name
data.cov.life <- data.cov.life[, .SD, .SDcols = c(name.id, names.cov.life)]
data.cov.trans <- data.cov.trans[, .SD, .SDcols = c(name.id, names.cov.trans)]
setnames(data.cov.life, old = name.id, new = "Id")
setnames(data.cov.trans, old = name.id, new = "Id")
data.cov.life[, Id := .convert_userinput_dataid(Id)]
data.cov.trans[, Id := .convert_userinput_dataid(Id)]
# Make static cov specific checks on covariate data
# only after if is DT because heavily relies on it for efficiency
# only after Id is character because needed to compare to data.transaction Id
check_err_msg(check_userinput_datanocov_datastaticcov(clv.data = clv.data, dt.data.static.cov = data.cov.life, names.cov = names.cov.life, name.of.covariate="Lifetime"))
check_err_msg(check_userinput_datanocov_datastaticcov(clv.data = clv.data, dt.data.static.cov = data.cov.trans, names.cov = names.cov.trans, name.of.covariate="Transaction"))
# Make cov data --------------------------------------------------------------------------
# keep numbers, char/factors to dummies
# input data.cov.X is renamed by ref to legal names
l.covs.life <- convert_userinput_covariatedata(dt.cov.data=data.cov.life, names.cov=names.cov.life)
l.covs.trans <- convert_userinput_covariatedata(dt.cov.data=data.cov.trans, names.cov=names.cov.trans)
data.cov.life <- l.covs.life$data.cov
data.cov.trans <- l.covs.trans$data.cov
names.cov.data.life <- l.covs.life$final.names.cov
names.cov.data.trans <- l.covs.trans$final.names.cov
setkeyv(data.cov.life, cols = "Id")
setkeyv(data.cov.trans, cols = "Id")
# Create object ---------------------------------------------------------------------------
# Create from given clv.data obj
return(clv.data.static.covariates(no.cov.obj = clv.data,
data.cov.life = data.cov.life,
data.cov.trans = data.cov.trans,
names.cov.data.life = names.cov.data.life,
names.cov.data.trans = names.cov.data.trans))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_setstaticcovariates.R
|
#' Formula Interface for Spending Models
#'
#' @description
#' Fit latent Gamma-Gamma model for customer spending with a formula interface
#'
#' @template template_param_formulainterface_formula
#' @template template_param_formulainterface_data
#' @template template_param_optimxargs
#' @template template_param_verbose
#'
#' @seealso Spending models for inputs: \link{gg}.
#' @seealso \link{latentAttrition} to fit latent attrition models with a formula interface
#'
#' @return Returns an object of the respective model which was fit.
#'
#' @examples
#' \donttest{
#'
#' data("cdnow")
#' clv.cdnow <- clvdata(data.transactions = cdnow, date.format="ymd",
#' time.unit = "weeks")
#'
#' # Fit gg
#' spending(~gg(), data=clv.cdnow)
#'
#' # Fit gg with start params
#' spending(~gg(start.params.model=c(p=0.5, q=15, gamma=2)),
#' data=clv.cdnow)
#'
#' # Fit gg, do not remove first transaction
#' spending(~gg(remove.first.transaction=FALSE), data=clv.cdnow)
#' # same, abreviate parameters
#' spending(~gg(remo=F), data=clv.cdnow)
#'
#' # Fit gg on given data.frame transaction data, no split
#' spending(data()~gg(), data=cdnow)
#'
#' # Fit gg on given data.frame, split after 39 periods
#' spending(data(split=39)~gg(), data=cdnow)
#' # same but also give date format and period definition
#' spending(data(split=39, format=ymd, unit=w)~gg(), data=cdnow)
#'
#' ## No covariate may be selected or covariate data.frame may be
#' ## given because currently no spending model uses covariates
#'
#' }
#'
#'
#' @importFrom Formula as.Formula
#' @importFrom stats terms formula
#' @export
spending <- function(formula, data, optimx.args=list(), verbose=TRUE){
cl <- match.call(call = sys.call(), expand.dots = TRUE)
check_err_msg(check_userinput_formula(formula, name.specials.model = "gg"))
check_err_msg(check_userinput_formula_data(data))
check_err_msg(check_userinput_spending_formulavsdata(formula=formula, data=data))
F.formula <- as.Formula(formula)
# Turn data.frame/table into data if needed
if(is.data.frame(data) || is.data.table(data)){
data <- formulainterface_dataframe_toclvdata(F.formula = F.formula, data=data, cl=cl)
}
# No covariates to be transformed
# default args from explicitly passed args
args <- list(clv.data = data, verbose=verbose, optimx.args=optimx.args)
# add model call args
model <- formula_read_model_name(F.formula)
l.model.args <- formula_parse_args_of_special(F.formula = F.formula, name.special = model, from.lhs=0, from.rhs = 1)
args <- modifyList(args, l.model.args, keep.null = TRUE)
# Fit model
obj <- do.call(what = model, args)
# Replace call with call to spending()
obj@call <- cl
return(obj)
}
#' @importFrom Formula as.Formula
check_userinput_spending_formulavsdata <- function(formula, data){
# only verify formula, not data
err.msg <- c()
# formula is verified to be basic correct
F.formula <- as.Formula(formula)
# always only 1 RHS
if(length(F.formula)[2] != 1){
err.msg <- c(err.msg, "The formula may only contain 1 RHS part specifiying the model!")
}
if(is.data.frame(data) || is.data.table(data)){
err.msg <- check_userinput_latentattrition_formulavsdata_LHS1(formula)
}else{
# many not have any LHS if not raw data
if(length(F.formula)[1] != 0){
err.msg <- c(err.msg, "Please do not specify any LHS if a clv.data object is given for parameter data!")
}
}
return(err.msg)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_interface_spending.R
|
#' @examples library(data.table)
#' @templateVar name_data_text Data Table
#' @templateVar name_data_code data.table
#' @templateVar name_res dt.trans
#' @template template_clvdata_asdatax
#' @template template_param_dots
#' @param keep.rownames Ignored
#' @export
as.data.table.clv.data <- function(x,
keep.rownames = FALSE,
Ids = NULL,
sample = c("full", "estimation", "holdout"),
...){
Id <- NULL
check_err_msg(check_user_data_emptyellipsis(...))
dt.trans <- clv.data.select.sample.data(clv.data=x, sample=sample,
choices = c("full", "estimation", "holdout"))
if(is.null(Ids)){
return(dt.trans)
}else{
dt.trans <- dt.trans[Id %in% Ids]
# ***TODO: Should stop instead of warn if not all Ids are there?
if(dt.trans[, uniqueN(Id)] != length(unique(Ids))){
warning("Not for all of the given Ids transaction data could be found")
}
return(dt.trans)
}
}
#' @templateVar name_data_text Data Frame
#' @templateVar name_data_code data.frame
#' @templateVar name_res df.trans
#' @template template_clvdata_asdatax
#' @template template_param_dots
#' @param row.names Ignored
#' @param optional Ignored
#' @export
as.data.frame.clv.data <- function(x,
row.names = NULL,
optional = NULL,
Ids = NULL,
sample = c("full", "estimation", "holdout"),
...){
return(as.data.frame(as.data.table.clv.data(x, Ids=Ids, sample=sample, ...=...)))
}
#' Number of observations
#'
#' The number of observations is defined as the number of unique customers in the transaction data.
#'
#' @template template_param_dots
#' @param object An object of class clv.data.
#'
#' @return The number of customers.
#'
#' @importFrom stats nobs
#' @export
nobs.clv.data <- function(object, ...){
Id <- NULL
# Observations are number of customers
return(as.integer([email protected][, uniqueN(Id)]))
}
#' @export
#' @include class_clv_data.R
print.clv.data <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
Name <- Total <- NULL
nsmall <- 4 # dont leave to user, hardcode
# Print an overview of the data
cat(x@name, "\n")
cat("\nCall:\n", paste(deparse(x@call), sep = "\n", collapse = "\n"), "\n", sep = "")
# Rough data set overview of sample only --------------------------------------------------
.print.list(list("Total # customers" = nobs(x),
"Total # transactions" = nrow([email protected]),
"Spending information" = clv.data.has.spending(clv.data = x)))
cat("\n")
print([email protected], digits = digits, ...)
# clv.time already prints a newline
invisible(x)
}
#' @export
#' @include class_clv_data_staticcovariates.R
print.clv.data.static.covariates <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
# print no cov part
NextMethod()
cat("Covariates")
# Print rough covariates overview if it is a covariates model -----------------------------
.print.list(list( "Trans. Covariates " = paste([email protected], collapse=", "),
" # covs" = length([email protected]),
"Life. Covariates " = paste([email protected], collapse=", "),
" # covs " = length([email protected])))
invisible(x)
}
#' @export
print.clv.data.dynamic.covariates <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
# print static cov part
NextMethod()
Cov.Date <- NULL
# Cannot store in object because of datatype issues.
# Would need to subclass clv.time or hide in a list in object
timepoint.first.cov.life <- [email protected][, min(Cov.Date)]
timepoint.last.cov.life <- [email protected][, max(Cov.Date)]
timepoint.first.cov.trans <- [email protected][, min(Cov.Date)]
timepoint.last.cov.trans <- [email protected][, max(Cov.Date)]
# Print first and last day of cov data
.print.list(list("Cov Date first Life" = clv.time.format.timepoint([email protected], timepoint=timepoint.first.cov.life),
"Cov Date last Life" = clv.time.format.timepoint([email protected], timepoint=timepoint.last.cov.life),
"Cov Date first Trans" = clv.time.format.timepoint([email protected], timepoint=timepoint.first.cov.trans),
"Cov Date last Trans" = clv.time.format.timepoint([email protected], timepoint=timepoint.last.cov.trans)))
invisible(x)
}
#' @template template_summary_data
#' @template template_param_dots
#' @export
summary.clv.data <- function(object, Id=NULL, ...){
res <- structure(list(), class="summary.clv.data")
res$name <- object@name
res$clv.time <- [email protected] # needed for formatting when printing
res$summary.clv.time <- summary([email protected])
res$descriptives.transactions <- clv.data.make.descriptives(clv.data=object, Ids = Id)
res$selected.ids <- unique(Id)
return(res)
}
#' @param x An object of class \code{"summary.clv.data"}, usually, a result of a call to \code{summary.clv.data}.
#' @param digits The number of significant digits to use when printing.
#'
#' @export
#' @rdname summary.clv.data
#' @keywords internal
print.summary.clv.data <- function(x, digits=max(3L, getOption("digits")-3L), ...){
nsmall <- 4
# Dont print title and clv.time summary if interested in summary of specific customers
if(is.null(x$selected.ids)){
cat(x$name, "\n")
print(x$summary.clv.time, digits=digits, ...)
cat("\n")
}
# Print transactions descriptives for each period -------------------------------------------
# Actual descriptives
disp <- array(data = NA_character_, dim = list(nrow(x$descriptives.transactions), 3))
disp[, 1] <- x$descriptives.transactions$Estimation
disp[, 2] <- x$descriptives.transactions$Holdout
disp[, 3] <- x$descriptives.transactions$Total
rownames(disp) <- x$descriptives.transactions$Name
colnames(disp) <- c("Estimation", "Holdout", "Total")
if(is.null(x$selected.ids)){
cat("Transaction Data Summary \n")
}else{
cat("Transaction Data Summary for Given Customers (n=",length(x$selected.ids),")\n", sep = "")
}
print(disp, quote = FALSE, na.print = "", print.gap = 6)
cat("\n")
invisible(x)
}
#' @include class_clv_data.R
#' @importFrom methods show
#' @export
#' @rdname clv.data-class
setMethod(f = "show", signature = signature(object="clv.data"), definition = function(object){
print(x=object)})
#' Subsetting clv.data
#'
#' Returns a subset of the transaction data stored within the given \code{clv.data} object which meet conditions.
#' The given expression are forwarded to the \code{data.table} of transactions.
#' Possible rows to subset and select are \code{Id}, \code{Date}, and \code{Price} (if present).
#'
#' @param x \code{clv.data} to subset
#' @param subset logical expression indicating rows to keep
#' @param select expression indicating columns to keep
#' @param ... further arguments passed to \code{data.table::subset}
#' @template template_param_sample
#'
#' @return A copy of the \code{data.table} of selected transactions. May contain columns \code{Id}, \code{Date}, and \code{Price}.
#'
#' @seealso \code{data.table}'s \code{\link[data.table:subset]{subset}}
#'
#' @aliases subset
#'
#' @examples
#'
#' \donttest{ # dont test because ncpu=2 limit on cran (too fast)
#' library(data.table) # for between()
#' data(cdnow)
#'
#' clv.cdnow <- clvdata(cdnow,
#' date.format="ymd",
#' time.unit = "week",
#' estimation.split = "1997-09-30")
#'
#' # all transactions of customer "1"
#' subset(clv.cdnow, Id=="1")
#' subset(clv.cdnow, subset = Id=="1")
#'
#' # all transactions of customer "111" in the estimation period...
#' subset(clv.cdnow, Id=="111", sample="estimation")
#' # ... and in the holdout period
#' subset(clv.cdnow, Id=="111", sample="holdout")
#'
#' # all transactions of customers "1", "2", and "999"
#' subset(clv.cdnow, Id %in% c("1","2","999"))
#'
#' # all transactions on "1997-02-16"
#' subset(clv.cdnow, Date == "1997-02-16")
#'
#' # all transactions between "1997-02-01" and "1997-02-16"
#' subset(clv.cdnow, Date >= "1997-02-01" & Date <= "1997-02-16")
#' # same using data.table's between
#' subset(clv.cdnow, between(Date, "1997-02-01","1997-02-16"))
#'
#' # all transactions with a value between 50 and 100
#' subset(clv.cdnow, Price >= 50 & Price <= 100)
#' # same using data.table's between
#' subset(clv.cdnow, between(Price, 50, 100))
#'
#' # only keep Id of transactions on "1997-02-16"
#' subset(clv.cdnow, Date == "1997-02-16", "Id")
#' }
#'
#' @export
subset.clv.data <- function(x,
subset,
select,
sample=c("full", "estimation", "holdout"),
...){
mc <- match.call(expand.dots = FALSE)
# replace object and function in call
mc[[1L]] <- quote(base::subset)
mc[["x"]] <- clv.data.select.sample.data(clv.data=x, sample=sample,
choices = c("full", "estimation", "holdout"))
# only keep subset, select to call data.table
mc <- mc[c(1L, match(c("x", "subset", "select", "..."), names(mc), 0L))]
return(eval(mc, parent.frame()))
# NextMethod([email protected]) # object has no S3 class attribute (vector)
# Does not work because subset and select are expressions
# dt.subset <- data.table:::subset.data.table([email protected], subset=subset, select=select, ...=...)
# return(dt.subset)
# if(isTRUE(all.equal(address(dt.subset),address([email protected]))){
# return(copy(dt.subset))
# }else{
# return(dt.subset)
# }
}
#' @include all_generics.R
#' @rdname as.clv.data
#' @export
as.clv.data.data.frame <- function(x,
date.format="ymd", time.unit="weeks",
estimation.split = NULL,
name.id="Id", name.date="Date", name.price="Price",
...){
return(clvdata(data.transactions = x,
date.format = date.format, time.unit = time.unit, estimation.split = estimation.split,
name.id = name.id, name.date = name.date, name.price = name.price))
}
#' @include all_generics.R
#' @rdname as.clv.data
#' @export
as.clv.data.data.table <- function(x,
date.format="ymd", time.unit="weeks",
estimation.split = NULL,
name.id="Id", name.date="Date", name.price="Price",
...){
return(clvdata(data.transactions = x,
date.format = date.format, time.unit = time.unit, estimation.split = estimation.split,
name.id = name.id, name.date = name.date, name.price = name.price))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvdata.R
|
#' @export
#' @rdname summary.clv.data
summary.clv.data.dynamic.covariates <- function(object, ...){
# get part for static cov data
res <- NextMethod()
Cov.Date <- NULL
class(res) <- c("summary.clv.data.dynamic.covariates", class(res))
# res$name.covariates.type <- "Dynamic Covariates" #printing
# Cannot store in object because of datatype issues.
# Would need to subclass clv.time or hide in a list in object
res$timepoint.first.cov.life <- [email protected][, min(Cov.Date)]
res$timepoint.last.cov.life <- [email protected][, max(Cov.Date)]
res$timepoint.first.cov.trans <- [email protected][, min(Cov.Date)]
res$timepoint.last.cov.trans <- [email protected][, max(Cov.Date)]
return(res)
}
#' @export
#' @rdname summary.clv.data
print.summary.clv.data.dynamic.covariates <- function(x, digits=max(3L, getOption("digits")-3L), ...){
# print static cov part
NextMethod()
# Do not print if interested in specific customers
if(is.null(x$selected.ids)){
# Print first and last day of cov data
.print.list(list("Cov Date first Life" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$timepoint.first.cov.life),
"Cov Date last Life" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$timepoint.last.cov.life),
"Cov Date first Trans" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$timepoint.first.cov.trans),
"Cov Date last Trans" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$timepoint.last.cov.trans)))
cat("\n")
}
invisible(x)
}
#' @importFrom methods show
#' @include class_clv_data_dynamiccovariates.R
#' @export
#' @rdname clv.data.dynamic.covariates-class
setMethod(f = "show", signature = signature(object="clv.data.dynamic.covariates"), definition = function(object){
print(x=object)})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvdata_dynamiccov.R
|
#' @title Plot Diagnostics for the Transaction data in a clv.data Object
#'
#' @param x The clv.data object to plot
#' @param which Which plot to produce, either "tracking", "frequency", "spending", "interpurchasetime", or "timings".
#' May be abbreviated but only one may be selected. Defaults to "tracking".
#'
#' @template template_param_verbose
#' @param plot Whether a plot should be created or only the assembled data returned.
#'
#' @param cumulative "tracking": Whether the cumulative actual repeat transactions should be plotted.
#' @templateVar prefix "tracking":
#' @templateVar plot_or_predict plot
#' @template template_param_predictionend
#'
#' @param trans.bins "frequency": Vector of integers indicating the number of transactions (x axis) for which the customers should be counted.
#' @param count.repeat.trans "frequency": Whether repeat transactions (TRUE, default) or all transactions (FALSE) should be counted.
#' @param count.remaining "frequency": Whether the customers which are not captured with \code{trans.bins} should be counted in a separate last bar.
#' @param label.remaining "frequency": Label for the last bar, if \code{count.remaining=TRUE}.
#'
#' @param mean.spending "spending": Whether customer's mean spending per transaction (\code{TRUE}, default) or the
#' value of every transaction in the data (\code{FALSE}) should be plotted.
#'
#' @param Ids "timings": A character vector of customer ids or a single integer specifying the number of customers to sample.
#' Defaults to \code{NULL} for which 50 random customers are selected.
#' @param annotate.ids "timings": Whether timelines should be annotated with customer ids.
#'
#' @param sample Name of the sample for which the plot should be made, either
#' "estimation", "full", or "holdout". Defaults to "estimation". Not for "tracking" and "timing".
#' @param color Color of resulting geom object in the plot. Not for "tracking" and "timing".
#' @param geom "spending" and "interpurchasetime": The geometric object of ggplot2 to display the data. Forwarded to
#' \link[ggplot2:stat_density]{ggplot2::stat_density}.
#' @param ... Forwarded to \link[ggplot2:stat_density]{ggplot2::stat_density} ("spending", "interpurchasetime")
#' or \link[ggplot2:geom_bar]{ggplot2::geom_bar} ("frequency"). Not for "tracking" and "timings".
#'
#'
#'
#' @description
#' Depending on the value of parameter \code{which}, one of the following plots will be produced.
#' Note that the \code{sample} parameter determines the period for which the
#' selected plot is made (either estimation, holdout, or full).
#'
#' \subsection{Tracking Plot}{
#' Plot the aggregated repeat transactions per period over the given time-horizon (\code{prediction.end}).
#' See Details for the definition of plotting periods.
#' }
#'
#' \subsection{Frequency Plot}{
# Plot distribution of the number of customers having the number of transactions.
#' Plot the distribution of transactions or repeat transactions per customer, after aggregating transactions
#' of the same customer on a single time point.
#' Note that if \code{trans.bins} is changed, \code{label.remaining} usually needs to be adapted as well.
#' }
#'
#' \subsection{Spending Plot}{
#' Plot the empirical density of either customer's average spending per transaction or the value
#' of every transaction in the data, after aggregating transactions of the same customer on a single time point.
#' Note that in all cases this includes all transactions and not only repeat-transactions.
#' }
#'
#' \subsection{Interpurchase Time Plot}{
#' Plot the empirical density of customer's mean time (in number of periods) between transactions,
#' after aggregating transactions of the same customer on a single time point.
#' Note that customers without repeat-transactions are removed.
#' }
#'
#' \subsection{Transaction Timing Plot}{
#' Plot the transaction timings of selected or sampled customers on their respective timelines.
#' }
#'
#' @template template_details_predictionend
#'
#' @details If there are no repeat transactions until \code{prediction.end}, only the time for which there is data
#' is plotted. If the data is returned (i.e. with argument \code{plot=FALSE}), the respective rows
#' contain \code{NA} in column \code{Number of Repeat Transactions}.
#'
#'
#' @seealso \link[ggplot2:stat_density]{ggplot2::stat_density} and \link[ggplot2:geom_bar]{ggplot2::geom_bar}
#' for possible arguments to \code{...}
#' @seealso \link[CLVTools:plot.clv.fitted.transactions]{plot} to plot fitted transaction models
#' @seealso \link[CLVTools:plot.clv.fitted.spending]{plot} to plot fitted spending models
#'
#' @return
#' An object of class \code{ggplot} from package \code{ggplot2} is returned by default.
#' If \code{plot=FALSE}, the data that would have been used to create the plot is returned.
#' Depending on which plot was selected, this is a \code{data.table}
#' which contains some of the following columns:
#' \item{Id}{Customer Id}
#' \item{period.until}{The timepoint that marks the end (up until and including) of the period to which the data in this row refers.}
#' \item{Spending}{Spending as defined by parameter \code{mean.spending}.}
#' \item{mean.interpurchase.time}{Mean number of periods between transactions per customer,
#' excluding customers with no repeat-transactions.}
#' \item{num.transactions}{The number of (repeat) transactions, depending on \code{count.repeat.trans}.}
#' \item{num.customers}{The number of customers.}
#' \item{type}{"timings": Which purpose the value in this row is used for.}
#' \item{variable}{"tracking": The number of actual repeat transactions in the period that ends at \code{period.until}.\cr
#' "timings": Coordinate (x or y) for which to use the value in this row for.}
#' \item{value}{"timings": Date or numeric (stored as string) \cr
#' "tracking": numeric}
#'
#'
#' @examples
#'
#' \donttest{
#'
#' data("cdnow")
#' clv.cdnow <- clvdata(cdnow, time.unit="w",estimation.split=37,
#' date.format="ymd")
#'
#' ### TRACKING PLOT
#' # Plot the actual repeat transactions
#' plot(clv.cdnow)
#' # same, explicitly
#' plot(clv.cdnow, which="tracking")
#'
#' # plot cumulative repeat transactions
#' plot(clv.cdnow, cumulative=TRUE)
#'
#' # Dont automatically plot but tweak further
#' library(ggplot2) # for ggtitle()
#' gg.cdnow <- plot(clv.cdnow)
#' # change Title
#' gg.cdnow + ggtitle("CDnow repeat transactions")
#'
#' # Dont return a plot but only the data from
#' # which it would have been created
#' dt.plot.data <- plot(clv.cdnow, plot=FALSE)
#'
#'
#' ### FREQUENCY PLOT
#' plot(clv.cdnow, which="frequency")
#'
#' # Bins from 0 to 15, all remaining in bin labelled "16+"
#' plot(clv.cdnow, which="frequency", trans.bins=0:15,
#' label.remaining="16+")
#'
#' # Count all transactions, not only repeat
#' # Note that the bins have to be adapted to start from 1
#' plot(clv.cdnow, which="frequency", count.repeat.trans = FALSE,
#' trans.bins=1:9)
#'
#'
#' ### SPENDING DENSITY
#' # plot customer's average transaction value
#' plot(clv.cdnow, which="spending", mean.spending = TRUE)
#'
#' # distribution of the values of every transaction
#' plot(clv.cdnow, which="spending", mean.spending = FALSE)
#'
#'
#' ### INTERPURCHASE TIME DENSITY
#' # plot as small points, in blue
#' plot(clv.cdnow, which="interpurchasetime",
#' geom="point", color="blue", size=0.02)
#'
#'
#' ### TIMING PATTERNS
#' # selected customers and annotating them
#' plot(clv.cdnow, which="timings", Ids=c("123", "1041"), annotate.ids=TRUE)
#'
#' # plot 25 random customers
#' plot(clv.cdnow, which="timings", Ids=25)
#'
#' # plot all customers
#' plot(clv.cdnow, which="timings", Ids=nobs(clv.cdnow))
#' }
#'
#' @importFrom graphics plot
#' @include all_generics.R class_clv_data.R
#' @method plot clv.data
#' @export
plot.clv.data <- function(x, which=c("tracking", "frequency", "spending", "interpurchasetime", "timings"),
# tracking plot
prediction.end=NULL, cumulative=FALSE,
# frequency
trans.bins=0:9, count.repeat.trans=TRUE, count.remaining=TRUE,
label.remaining="10+",
# spending density
mean.spending=TRUE,
# timings
annotate.ids=FALSE,
Ids=c(),
# all density
sample=c("estimation", "full", "holdout"),
geom="line", color="black",
# all plots
plot=TRUE, verbose=TRUE, ...){
# do not check ggplot inputs (geom, color)
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=plot, var.name="plot"))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose"))
err.msg <- c(err.msg, .check_userinput_matcharg(char=which, choices=c("tracking", "frequency", "spending", "interpurchasetime", "timings"),
var.name="which"))
check_err_msg(err.msg)
return(
switch(EXPR = match.arg(arg=tolower(which), choices = c("tracking", "frequency", "spending", "interpurchasetime", "timings"),
several.ok = FALSE),
"tracking" =
clv.data.plot.tracking(x=x, prediction.end = prediction.end, cumulative = cumulative,
plot = plot, verbose = verbose, ...=...),
"spending" =
clv.data.plot.density.spending(x = x, sample=sample, mean.spending = mean.spending,
plot = plot, verbose=verbose,
color = color, geom=geom, ...),
"interpurchasetime" =
clv.data.plot.density.interpurchase.time(clv.data = x, sample=sample,
plot=plot, verbose=verbose,
color=color, geom=geom, ...),
"frequency" =
clv.data.plot.barplot.frequency(clv.data = x, sample=sample,
trans.bins=trans.bins,
count.repeat.trans=count.repeat.trans,
label.remaining=label.remaining,
count.remaining=count.remaining,
plot=plot, verbose=verbose,
color=color, ...),
"timings" =
clv.data.plot.transaction.timings(clv.data = x, Ids = Ids,
annotate.ids = annotate.ids,
plot = plot, verbose = verbose,
...)
))
}
#' @importFrom ggplot2 theme rel element_text element_blank element_rect element_line
#' @importFrom utils modifyList
clv.data.plot.add.default.theme <- function(p, custom=list()){
l.default.args <- list(
plot.title = element_text(face = "bold", size = rel(1.5)),
text = element_text(),
panel.background = element_blank(),
panel.border = element_blank(),
plot.background = element_rect(colour = NA),
axis.title = element_text(face = "bold",size = rel(1)),
axis.title.y = element_text(angle=90,vjust =2),
axis.title.x = element_text(vjust = -0.2),
axis.text = element_text(),
axis.line = element_line(colour="black"),
axis.ticks = element_line(),
panel.grid.major = element_line(colour="#d2d2d2"),
panel.grid.minor = element_blank(),
legend.key = element_blank(),
legend.position = "bottom",
legend.direction = "horizontal",
legend.title = element_text(face="italic"),
strip.background=element_rect(colour="#d2d2d2",fill="#d2d2d2"),
strip.text = element_text(face="bold", size = rel(0.8)))
# Overwrite with custom args
l.default.args <- modifyList(l.default.args, custom)
return(p + do.call(what=theme, args = l.default.args))
}
clv.data.plot.tracking <- function(x, prediction.end, cumulative, plot, verbose, ...){
period.until <- period.num <- value <- NULL
# This is nearly the same as plot.clv
# However, creating a single plotting controlflow leads to all kinds of side effects and special cases.
# Because there are only 2 functions that would profit, it was decided to leave it in their own separate
# functions. (It is only the Rule of three ("Three strikes and you refactor"), not the Rule of two)
# Check inputs ------------------------------------------------------------------------------------------------------
err.msg <- c()
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=cumulative, var.name="cumulative"))
err.msg <- c(err.msg, check_user_data_predictionend(clv.fitted=x, prediction.end=prediction.end))
check_err_msg(err.msg)
# Define time period to plot -----------------------------------------------------------------------------------------
# Use table with exactly defined periods as reference to save the repeat transactions
# End date further than transactions:
# If there are not enough transactions for all dates, they are set to NA (= not plotted)
dt.dates.expectation <- clv.time.expectation.periods(clv.time = [email protected], user.tp.end = prediction.end)
tp.data.start <- dt.dates.expectation[, min(period.until)]
tp.data.end <- dt.dates.expectation[, max(period.until)]
if(verbose)
message("Plotting from ", tp.data.start, " until ", tp.data.end, ".")
if(clv.data.has.holdout(x)){
if(tp.data.end < [email protected]@timepoint.holdout.end){
warning("Not plotting full holdout period.", call. = FALSE, immediate. = TRUE)
}
}else{
if(tp.data.end < [email protected]@timepoint.estimation.end){
warning("Not plotting full estimation period.", call. = FALSE, immediate. = TRUE)
}
}
# Get repeat transactions ----------------------------------------------------------------------------------------
label.transactions <- "Number of Repeat Transactions"
dt.repeat.trans <- clv.data.add.repeat.transactions.to.periods(clv.data=x, dt.date.seq=dt.dates.expectation,
cumulative=cumulative)
setnames(dt.repeat.trans, old = "num.repeat.trans", new = label.transactions)
# Plot data, if needed --------------------------------------------------------------------------------------------
# Merge data for plotting
# To be sure to have all dates, merge data on original dates
dt.dates.expectation[, period.num := NULL]
dt.dates.expectation[dt.repeat.trans, (label.transactions) := get(label.transactions), on="period.until"]
dt.plot <- melt(dt.dates.expectation, id.vars="period.until")
# last period often has NA as it marks the full span of the period
dt.plot <- dt.plot[!is.na(value)]
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.plot[]
# Only if needed
if(!plot){
return(dt.plot)
}
# Plot table with formatting, label etc
p <- clv.controlflow.plot.tracking.base(dt.plot = dt.plot, clv.data = x,
color.mapping = setNames(object = "black", nm = label.transactions))
p <- p + theme(legend.position = "none")
return(p)
}
clv.data.make.density.plot <- function(dt.data, mapping, labs_x, title, geom, ...){
p <- ggplot(data = dt.data) + stat_density(mapping = mapping, geom = geom, ...)
# Axis and title
p <- p + labs(x = labs_x, y="Density", title=title)
return(clv.data.plot.add.default.theme(p))
}
#' @importFrom ggplot2 aes
clv.data.plot.density.spending <- function(x, sample, mean.spending, plot, verbose, color, geom, ...){
Id <- Price <- Spending <- NULL
# only check non-ggplot inputs
# sample is checked in select.sample.data
check_err_msg(.check_user_data_single_boolean(mean.spending, var.name="mean.spending"))
# get transaction data data
dt.trans <- clv.data.select.sample.data(clv.data = x, sample = sample, choices=c("estimation", "full", "holdout"))
# Calculate spending
if(mean.spending){
dt.spending <- dt.trans[, list(Spending = mean(Price)), by="Id"]
title <- "Density of Average Transaction Value"
labs_x <- "Average Value per Transaction"
}else{
dt.spending <- dt.trans[, list(Spending = Price, Id)]
title <- "Density of Transaction Value"
labs_x <- "Value per Transaction"
}
if(plot){
return(clv.data.make.density.plot(dt.data = dt.spending,
mapping = aes(x = Spending),
labs_x = labs_x, title = title,
# pass to stat_density
geom = geom, color=color, ...))
}else{
return(dt.spending)
}
}
clv.data.plot.density.interpurchase.time <- function(clv.data, sample,
plot, verbose, color, geom, ...){
interp.time <- mean.interpurchase.time <- NULL
dt.trans <- clv.data.select.sample.data(clv.data=clv.data, sample=sample, choices=c("estimation", "full", "holdout"))
# interpurchase time in given period
dt.mean.interp <- clv.data.mean.interpurchase.times(clv.data=clv.data, dt.transactions=dt.trans)
# only such with repeat-transaction
dt.mean.interp <- dt.mean.interp[!is.na(interp.time)]
setcolorder(dt.mean.interp, c("Id", "interp.time"))
setnames(dt.mean.interp, old="interp.time", new="mean.interpurchase.time")
labs_x <- paste0("Mean Interpurchase Time (",[email protected]@name.time.unit,")")
if(plot){
return(clv.data.make.density.plot(dt.data = dt.mean.interp,
mapping = aes(x = mean.interpurchase.time),
labs_x = labs_x,
title = "Density of Customer's Mean Time between Transactions",
geom = geom, color = color, ...))
}else{
return(dt.mean.interp)
}
}
#' @importFrom ggplot2 ggplot geom_col labs geom_text position_dodge rel
clv.data.plot.barplot.frequency <- function(clv.data, count.repeat.trans, count.remaining, label.remaining, trans.bins,
sample, plot, verbose, color, ...){
x <- num.customers <- num.transactions <- NULL
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=count.repeat.trans, var.name="count.repeat.trans"))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=count.remaining, var.name="count.remaining"))
err.msg <- c(err.msg, .check_userinput_charactervec(char=label.remaining, var.name="label.remaining", n=1))
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
check_err_msg(err.msg) # count.repeat.trans has to be checked first
check_err_msg(check_userinput_datanocov_transbins(trans.bins=trans.bins, count.repeat.trans=count.repeat.trans))
# Number of customers which have the given number of transactions
trans.bins <- unique(trans.bins)
dt.bins <- data.table(x = trans.bins)
dt.trans <- clv.data.select.sample.data(clv.data=clv.data, sample=sample, choices=c("estimation", "full", "holdout"))
dt.num.trans <- dt.trans[, list(x = .N), by="Id"]
if(count.repeat.trans){
dt.num.trans[, x := x-1]
x.lab <- "Number of Repeat Transactions"
}else{
x.lab <- "Number of Transactions"
}
# count how many customers had how many num trans
dt.num.cust.by.trans <- dt.num.trans[, list(num.customers = .N), by="x"]
# add how many customers made x num trans
# NA where does not match, set 0 to keep
dt.bins <- dt.bins[dt.num.cust.by.trans, num.customers := num.customers, on="x"]
dt.bins[is.na(num.customers), num.customers := 0]
setnames(dt.bins, "x", "num.transactions")
# Make char to bind together with "remaining"
# get levels order before turning into character
levels.bins <- dt.bins[, sort(num.transactions)]
dt.bins[, num.transactions := as.character(num.transactions)]
if(count.remaining){
# find all num.trans which are not already in bins
dt.remaining <- dt.num.cust.by.trans[!(x %in% dt.bins[, as.numeric(num.transactions)])]
dt.remaining <- dt.remaining[, list(num.transactions=label.remaining, num.customers = sum(num.customers))]
dt.bins <- rbindlist(list(dt.bins, dt.remaining))
# add remaining as last/highest level
levels.bins <- c(levels.bins, label.remaining)
}
# turn into ordered category for plotting
dt.bins[, num.transactions := factor(num.transactions, levels = levels.bins, ordered = TRUE)]
if(!plot){
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.bins[]
return(dt.bins)
}else{
# use geom_col because geom_bar does the counting itself
p <- ggplot(data = dt.bins) + geom_col(mapping = aes(x=num.transactions, y=num.customers),
fill=color,
width = 0.5,
show.legend = FALSE)
# Axis and title
p <- p + labs(x = x.lab, y="Number of Customers",
# Number of Customers per Number of Transactions
title="Distribution of Transaction Count")
# add count annotation
p <- p + geom_text(aes(label = num.customers, x = num.transactions, y = num.customers),
position = position_dodge(width = 0.8),
vjust = -0.6,
size = rel(3))
# Standard theme, but make x ticks for the bins bold (num repeat trans)
return(clv.data.plot.add.default.theme(p, custom = list(axis.text.x = element_text(face="bold"))))
}
}
#' @importFrom ggplot2 ggplot geom_segment geom_point geom_text geom_vline theme xlab ylim ggtitle element_blank scale_x_datetime scale_x_date
clv.data.plot.transaction.timings <- function(clv.data, Ids, annotate.ids, plot, verbose, ...){
# cran silence
Id <- x <- y <- i.y <- date.first.actual.trans <- xstart <- xend <- ystart <- yend <- type <- Date <- NULL
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=annotate.ids, var.name="annotate.ids"))
err.msg <- c(err.msg, check_userinput_datanocov_ids(Ids=Ids))
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
check_err_msg(err.msg)
# Draw lines with segments
# For each customer: xstart, ystart, xend, yend
# Add calibration points
# For each customer x,y of varying number
# Add holdout points
# For each customer x,y of varying number
x.max <- [email protected]@timepoint.holdout.end
# Select first transaction of all ids, sample if ids not given
dt.customer.y <- pnbd_cbs(clv.data)
Ids <- unique(Ids)
if(is.null(Ids) | (length(Ids) == 1 & is.numeric(Ids))){
# sample given number of random customers (50 if none given)
if(is.null(Ids)){
Ids <- 50
}
if(Ids > nobs(clv.data)){
Ids <- nobs(clv.data)
warning(paste0("Id may not be larger than the number of customers and is set to ", nobs(clv.data), "."))
}
Ids <- dt.customer.y[, sample(x = Id, size = Ids, replace = FALSE)]
}
if(!all(Ids %in% dt.customer.y[, unique(Id)])){
warning("Not all given Ids were found in the transaction data.", call. = FALSE)
}
dt.customer.y <- dt.customer.y[Id %in% Ids, c("Id", "date.first.actual.trans")]
# Determine y position based on date of first transaction
# shortest on top, ordered by Id if same timepoint
setorderv(dt.customer.y, c("date.first.actual.trans", "Id"), order = c(1, -1))
dt.customer.y[, y := seq(from=10, length.out=.N, by=10)]
# Line segments
# x: from first transaction (start) to holdout end (end)
# y: start and end same per customer
dt.segments <- dt.customer.y[, list(Id, xstart=date.first.actual.trans, xend=x.max, ystart=y, yend=y)]
# Points in calibration period
# x: transaction
# y: per customer y
dt.calibration <- clv.data.get.transactions.in.estimation.period(clv.data)
dt.calibration <- dt.calibration[Id %in% Ids]
dt.calibration[, x := Date]
dt.calibration[dt.customer.y, y := i.y, on="Id"]
# Points in holdout period
if(clv.data.has.holdout(clv.data)){
dt.holdout <- clv.data.get.transactions.in.holdout.period(clv.data)
dt.holdout <- dt.holdout[Id %in% Ids]
dt.holdout[, x := Date]
dt.holdout[dt.customer.y, y := i.y, on="Id"]
}
if(!plot){
# put data in single data.table to return if needed
# columns: Id, type, x, y
# types: point_calibration, point_holdout, segment_start, segment_end
# x: Date
# y: number
dt.segments.start <- dt.segments[, list(Id, x=xstart, y=ystart, type="segment_start")]
dt.segments.end <- dt.segments[, list(Id, x=xend, y=yend, type="segment_end")]
dt.calibration[, type := "point_calibration"]
if(clv.data.has.holdout(clv.data)){
dt.holdout[, type := "point_holdout"]
l.plot <- list(dt.segments.start, dt.segments.end, dt.calibration, dt.holdout)
}else{
l.plot <- list(dt.segments.start, dt.segments.end, dt.calibration)
}
# melt all tables to bind them to common long-format
dt.plot <- rbindlist(lapply(l.plot, function(dt){
dt[, x := as.character(x)] # return x and y as chars to mix different types
dt[, y := as.character(y)]
dt <- melt(dt, id.vars = c('Id', 'type'), measure.vars = c('x', 'y'), variable.factor=FALSE)
dt
}))
return(dt.plot)
}
# Use single data.tables for plotting each part because much simpler than subsetting and cast()ing dt.plot
# Customer lines
g <- ggplot() + geom_segment(aes(x=xstart, xend=xend, y=ystart, yend=yend), data=dt.segments, color="#efefef")
# transaction points
g <- g + geom_point(aes(x=x, y=y), data=dt.calibration, color="#454545")
# holdout points & split line
if(clv.data.has.holdout(clv.data)){
g <- g + geom_point(aes(x=x, y=y), data=dt.holdout, color="#454545", fill="#999999", pch=21)
g <- g + geom_vline(aes(xintercept=x), linetype="dashed", show.legend = FALSE,
data=data.frame([email protected]@timepoint.estimation.end))
}
# mark ids
if(annotate.ids){
g <- g + geom_text(aes(x=x, y=y, label=Id),
data = dt.customer.y[, list(Id, y, x=min(date.first.actual.trans))],
nudge_x = -50, size=2.5, fontface="bold")
}
# y limits start at 0 to ensure a gap between first line and x axis
g <- g + ylim(c(0, dt.customer.y[, max(y)] + 10))
# x limits from first transaction to holdout/estimation end
# exactly 4 breaks from first plotted transaction to end
# dont set limits as id annotations will fall outside and trigger a waring
x.breaks <- seq(from=dt.customer.y[, min(date.first.actual.trans)], to=x.max, length.out=4)
if(is([email protected], "clv.time.date")){
g <- g + scale_x_date(breaks = x.breaks)
}else{
g <- g + scale_x_datetime(breaks = x.breaks)
}
# cosmetics
g <- clv.data.plot.add.default.theme(g)
g <- g + theme(axis.title.y = element_blank(), axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), panel.grid.major = element_blank())
g <- g + xlab("Date")
g <- g + ggtitle('Transaction Timings', subtitle = paste0("Estimation end: ", clv.time.format.timepoint([email protected], [email protected]@timepoint.estimation.end)))
return(g)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvdata_plot.R
|
#' @export
#' @rdname summary.clv.data
#' @keywords internal
summary.clv.data.static.covariates <- function(object, ...){
# get part for no cov data
res <- NextMethod()
class(res) <- c("summary.clv.data.static.covariates", class(res))
# res$name.covariates.type <- "Static Covariates" #printing
res$names.cov.data.trans <- [email protected]
res$names.cov.data.life <- [email protected]
return(res)
}
#' @export
#' @rdname summary.clv.data
print.summary.clv.data.static.covariates <- function(x, digits=max(3L, getOption("digits")-3L), ...){
NextMethod()
# Do not print if interested in specific Ids
if(is.null(x$selected.ids)){
cat("Covariates")
# cat(x$name.covariates.type)
.print.list(list( "Trans. Covariates " = paste(x$names.cov.data.trans, collapse=", "),
" # covs" = length(x$names.cov.data.trans),
"Life. Covariates " = paste(x$names.cov.data.life, collapse=", "),
" # covs " = length(x$names.cov.data.life)))
cat("\n")
}
invisible(x)
}
#' @importFrom methods show
#' @include class_clv_data_staticcovariates.R
#' @export
#' @rdname clv.data.static.covariates-class
setMethod(f = "show", signature = signature(object="clv.data.static.covariates"), definition = function(object){
print(x=object)})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvdata_staticcov.R
|
#' @include class_clv_fitted.R
#' @importFrom stats logLik nobs coef
#' @importFrom utils tail
#' @importFrom optimx coef<-
#' @export
logLik.clv.fitted <- function(object, ...){
last.row.optimx <- tail([email protected], n = 1)
return(structure( (-1)*(last.row.optimx[["value"]]),
nall = nobs(object),
nobs = nobs(object),
df = length(coef(last.row.optimx)),
class ="logLik"))
}
#' Number of observations
#'
#'
#' The number of observations is defined as the number of unique customers for which the model was fit.
#'
#' @param object An object of class clv.fitted.
#' @template template_param_dots
#'
#' @return The number of customers.
#'
#' @importFrom stats nobs
#' @export
#' @include class_clv_fitted.R
nobs.clv.fitted <- function(object, ...){
# Observations are number of customers
return(nrow(object@cbs))
}
#' @include class_clv_fitted.R
#' @importFrom stats coef
#' @importFrom optimx coef<-
#' @importFrom utils tail
#' @export
coef.clv.fitted <- function(object, ...){
last.row.optimx.coef <- tail(coef([email protected]),n=1)
# model params from clv.model (backtransform) --------------------------------------------------------
# Backtransform estimated model params from opimizer to original scale
prefixed.params.model <- last.row.optimx.coef[1, [email protected]@names.prefixed.params.model,drop=TRUE]
original.scale.model.params <- clv.model.backtransform.estimated.params.model(clv.model = [email protected],
prefixed.params.model = prefixed.params.model)
# Set original scale names and ensure order
original.scale.model.params <- setNames(original.scale.model.params[[email protected]@names.prefixed.params.model],
[email protected]@names.original.params.model)
original.scale.params <- original.scale.model.params
# Correlation param ---------------------------------------------------------------------------------------
original.scale.params <- clv.model.coef.add.correlation(clv.model = [email protected],
last.row.optimx.coef = last.row.optimx.coef,
original.scale.params = original.scale.params)
return(original.scale.params)
}
#' @title Calculate Variance-Covariance Matrix for CLV Models fitted with Maximum Likelihood Estimation
#'
#' @param object a fitted clv model object
#' @template template_param_dots
#'
#'
#' @description
#' Returns the variance-covariance matrix of the parameters of the fitted model object.
#' The variance-covariance matrix is derived from the Hessian that results from the optimization procedure.
#' First, the Moore-Penrose generalized inverse of the Hessian is used to obtain an estimate of the
#' variance-covariance matrix.
#' Next, because some parameters may be transformed for the purpose of restricting their value during
#' the log-likelihood estimation, the variance estimates are adapted to
#' be comparable to the reported coefficient estimates.
#' If the result is not positive definite, \link[Matrix:nearPD]{Matrix::nearPD} is used
#' with standard settings to find the nearest positive definite matrix.
#'
#' If multiple estimation methods were used, the Hessian of the last method is used.
#'
#' @return
#' A matrix of the estimated covariances between the parameters of the model.
#' The row and column names correspond to the parameter names given by the \code{coef} method.
#'
# @references Jeff's "Note on p-values"
#'
#' @seealso \link[MASS:ginv]{MASS::ginv}, \link[Matrix:nearPD]{Matrix::nearPD}
#'
#'
#' @importFrom stats vcov
#' @importFrom utils tail
#' @importFrom Matrix nearPD
#' @importFrom MASS ginv
#'
#' @export
vcov.clv.fitted <- function(object, ...){
if(any(!is.finite([email protected])))
stop("The vcov matrix cannot be calulated because the hessian contains non-finite values!", call. = FALSE)
# Get the vcov as the inverse of hessian
# log(thetahat) ~ N(theta,Hinv)!
#
# Jeff:
# negative hessian or hessian?!
# -> Depends on optimization! If we have the loglikelihood we need the negative Hessian.
# However we have the negative (!) Log likelihood, so we need to take the Hessian directly
# Moore-Penrose inverse of Hessian
# Results in the regular inverse if invertible
m.hessian.inv <- ginv([email protected])
# Apply Jeff's delta method to account for the transformations of the parameters
# See Jeff's Note on how to derive p-values
# The variances are for the transformed parameters (ie log-scale)
# Get the numbers to put in diag() for back transformation from the model
# Jeff: Apply the transformation on optimizer-scale parameters
prefixed.params <- tail(coef([email protected]), n=1)[1, , drop = TRUE]
m.delta.diag <- clv.model.vcov.jacobi.diag([email protected], clv.fitted=object,
prefixed.params=prefixed.params)
stopifnot(all(colnames(m.hessian.inv) == colnames(m.delta.diag)))
stopifnot(all(rownames(m.hessian.inv) == rownames(m.delta.diag)))
m.vcov <- m.delta.diag %*% m.hessian.inv %*% m.delta.diag
# Make positive definite if it is not already
# Returns unchanged if the matrix is PD already
m.vcov <- as.matrix(nearPD(m.vcov)$mat)
# Naming and sorting
# Sorting: Correct because directly from optimx hessian and for delta.diag from coef(optimx)
# **TODO: This might not hold if covs are transformed as well, ie need to replace their names as well (but currently covs are not transformed in any model)
# Naming: Has to match coef(). model + cor: original
# any cov: leave prefixed
# Change the names of model+cor to display name because
# the reported vcov is in original scale as well
# Set all names of vcov to these of hessian (prefixed)
rownames(m.vcov) <- colnames(m.vcov) <- colnames([email protected])
# prefixed names to replace with original names
names.prefixed.all <- [email protected]@names.prefixed.params.model
names.original.all <- [email protected]@names.original.params.model
if(clv.model.estimation.used.correlation([email protected])){
names.prefixed.all <- c(names.prefixed.all, [email protected]@name.prefixed.cor.param.m)
names.original.all <- c(names.original.all, [email protected]@name.correlation.cor)
}
# position of these prefixed names
pos.prefixed.names <- match(x = names.prefixed.all, table=rownames(m.vcov))
# replace with original names
rownames(m.vcov)[pos.prefixed.names] <- names.original.all
colnames(m.vcov)[pos.prefixed.names] <- names.original.all
# Of utmost importance: Ensure same sorting as coef()
names.coef <- names(coef(object = object))
m.vcov <- m.vcov[names.coef, names.coef]
return(m.vcov)
}
#' @importFrom stats qnorm vcov coef
#' @export
confint.clv.fitted <- function(object, parm, level = 0.95, ...){
# This largely follows stats:::confint.lm to exhibit the same behavior
# Get SE
# SE <- sqrt(diag(vcov(object)))
#
# CI.low <- params - qnorm(1-alpha/2) * SE
# CI.high <- params + qnorm(1-alpha/2) * SE
estim.coefs <- coef(object)
# Param selection --------------------------------------------------------------------------------
if(missing(parm))
# Use all by default
parm <- names(estim.coefs)
else
if(is.numeric(parm))
# Make numbers to respective names
parm <- names(estim.coefs)[parm]
# CI calc ----------------------------------------------------------------------------------------
req.a <- (1-level) / 2
req.a <- c(req.a, 1 - req.a)
zs <- qnorm(p = req.a, mean = 0, sd = 1)
ci <- estim.coefs[parm] + sqrt(diag(vcov(object)))[parm] %o% zs
# Return ----------------------------------------------------------------------------------------
# from stats:::format.perc - cannot call with ::: because gives CRAN note
names.perc <- paste(format(100 * req.a, trim = TRUE, scientific = FALSE, digits = 3), "%")
res <- array(data = NA, dim = c(length(parm), 2L), dimnames = list(parm, names.perc))
res[] <- ci
return(res)
}
#' @export
#' @importFrom utils tail
#' @importFrom stats coef
#' @include class_clv_fitted.R
print.clv.fitted <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
# Short print similar to lm
cat([email protected]@name.model, "Model\n")
cat("\nCall:\n", paste(deparse(x@call), sep = "\n", collapse = "\n"), "\n", sep = "")
cat("\nCoefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2L,
quote = FALSE)
last.row.optimx <- tail([email protected], n = 1)
cat("KKT1:", last.row.optimx$kkt1, "\n")
cat("KKT2:", last.row.optimx$kkt2, "\n")
if(clv.model.supports.correlation([email protected])){
cat("\n")
cat("Used Options:\n")
cat("Correlation: ", [email protected]@estimation.used.correlation, "\n")
}
invisible(x)
}
#' @include all_generics.R class_clv_fitted.R
#' @importFrom methods show
#' @export
#' @rdname clv.fitted-class
setMethod(f = "show", signature = signature(object="clv.fitted"), definition = function(object){
print(x=object)})
# helper to convert list to printable array
.list2array <- function(l, col.n="", row.n=names(l), nsmall=4){
disp <- array(data=NA_character_, dim=list(length(l), 1))
disp[, 1] <- unlist(format(l, na.encode = FALSE, digits=nsmall, nsmall=nsmall, scientific=FALSE))
rownames(disp) <- row.n
colnames(disp) <- col.n
return(disp)
}
.print.list <- function(l, col.n = "", row.n = names(l), nsmall=4){
disp.arr <- .list2array(l, col.n=col.n, row.n=row.n, nsmall=nsmall)
print(disp.arr, na.print = "", quote = FALSE)
}
#' @rdname summary.clv.fitted
#' @order 3
#' @importFrom stats printCoefmat
#' @export
print.summary.clv.fitted <- function(x, digits=max(3L, getOption("digits")-3L),
signif.stars = getOption("show.signif.stars"), ...){
Total <- Name <- Estimation <- Holdout <- Total <- NULL
nsmall <- 4
cat(x$name.model, " Model \n")
cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
# Print fitting period information ----------------------------------------
cat("Fitting period:")
.print.list(nsmall=nsmall,
l=list("Estimation start" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$tp.estimation.start),
"Estimation end" = clv.time.format.timepoint(clv.time=x$clv.time, timepoint=x$tp.estimation.end),
"Estimation length" = paste0(format(x$estimation.period.in.tu, digits=digits,nsmall=nsmall), " ", x$time.unit)))
cat("\n")
# Print estimated model parameters ---------------------------------------
cat("Coefficients:\n")
printCoefmat(x$coefficients, digits = digits, na.print = "NA",
has.Pvalue = TRUE, signif.stars = signif.stars,...)
# General Optimization infos ---------------------------------------------
cat("\nOptimization info:")
.print.list(nsmall=nsmall,
l = list("LL" = x$estimated.LL,
"AIC" = x$AIC,
"BIC" = x$BIC,
"KKT 1" = x$kkt1,
"KKT 2" = x$kkt2,
"fevals" = x$fevals,
"Method" = x$method))
# Correlation ------------------------------------------------------------
if(length(x$additional.options)>0){
cat("\nUsed Options:")
.print.list(nsmall=nsmall, l = x$additional.options)
}
return(invisible(x))
}
#' @template template_summary_clvfitted
#' @order 1
#' @importFrom stats coef vcov AIC BIC logLik pnorm
#' @importFrom utils tail
#' @importFrom methods is
#' @export
summary.clv.fitted <- function(object, ...){
## The basis structure
res <- structure(list(), class = "summary.clv.fitted")
# Model stuff ---------------------------------------------------------------------
res$name.model <- [email protected]@name.model
res$call <- object@call
# Estimation & Transaction --------------------------------------------------------
# Fitting period
res$clv.time <- [email protected]@clv.time # needed for formating when printing
res$tp.estimation.start <- [email protected]
res$tp.estimation.end <- [email protected]
res$estimation.period.in.tu <- [email protected]
res$time.unit <- [email protected]
# Coefficient table --------------------------------------------------------------
# Return the full coefficient table. The subset is to relevant rows is done in the
# printing
all.est.params <- coef(object)
# return NA_ placeholder if cannot calculate vcov
res$vcov <- tryCatch(vcov(object),
error = function(e){
h <- [email protected]
h[,] <- NA_real_
return(h)})
se <- tryCatch(suppressWarnings(sqrt(diag(res$vcov))),
error = function(e)return(e))
if(is(se, "error")){
warning("The standard errors could not be calculated because the vcov contains non-numeric elements.", call. = FALSE)
}else{
# only check if not error
if(anyNA(se))
warning("For some parameters the standard error could not be calculated.", call. = FALSE)
}
# Jeff: z.val - norm
z.val <- (all.est.params-0)/se
p.val <- 2*(1-pnorm(abs(z.val)))
res$coefficients <- cbind(all.est.params,
se,
z.val,
p.val)
rownames(res$coefficients) <- names(all.est.params)
colnames(res$coefficients) <- c("Estimate","Std. Error", "z-val", "Pr(>|z|)")
# Optimization -------------------------------------------------------------------
res$estimated.LL <- as.vector(logLik(object))
res$AIC <- AIC(object)
res$BIC <- BIC(object)
last.row.optimx <- tail([email protected], n = 1)
res$kkt1 <- last.row.optimx$kkt1
res$kkt2 <- last.row.optimx$kkt2
res$fevals <- last.row.optimx$fevals
res$method <- rownames(last.row.optimx)
# Additional options: Correlation ------------------------------------------------
if(clv.model.supports.correlation(clv.model = [email protected])){
res$additional.options <- list("Correlation"[email protected]@estimation.used.correlation)
}else{
res$additional.options <- list()
}
return(res)
}
#' @export
coef.summary.clv.fitted <- function(object, ...){
return(object$coefficients)
}
#' @export
vcov.summary.clv.fitted <- function(object, ...){
return(object$vcov)
}
#' @title Extract Unconditional Expectation
#' @param object A fitted clv model for which the unconditional expectation is desired.
#' @templateVar prefix {}
#' @templateVar plot_or_predict predict
#' @template template_param_predictionend
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @description
#' Extract the unconditional expectation (future transactions unconditional on being "alive") from a fitted clv model.
#' This is the unconditional expectation data that is used when plotting the fitted model.
#'
#' @template template_details_predictionend
#'
#' @seealso \code{\link[CLVTools:plot.clv.fitted.transactions]{plot}} to plot the unconditional expectation
#'
#' @return
#' A \code{data.table} which contains the following columns:
#' \item{period.until}{The timepoint that marks the end (up until and including) of the period to which the data in this row refers.}
#' \item{period.num}{The number of this period. }
#' \item{expectation}{The value of the unconditional expectation for the period that ends on \code{period.until}.}
#'
#'
#' @include class_clv_fitted.R
#' @importFrom stats fitted
#' @export
fitted.clv.fitted <- function(object, prediction.end=NULL, verbose=FALSE, ...){
dt.expectation.seq <- clv.time.expectation.periods(clv.time = [email protected]@clv.time,
user.tp.end = prediction.end)
dt.model.expectation <- clv.model.expectation([email protected], clv.fitted=object,
dt.expectation.seq=dt.expectation.seq, verbose=verbose)
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.model.expectation[]
return(dt.model.expectation)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvfitted.R
|
#' @title Plot expected and actual mean spending per transaction
#' @param x The fitted spending model to plot
#' @param n Number of points at which the empirical and model density are calculated. Should be a power of two.
#' @template template_param_verbose
#' @template template_param_dots
#'
#' @description
#' Compares the density of the observed average spending per transaction (empirical distribution) to the
#' model's distribution of mean transaction spending (weighted by the actual number of transactions).
#' See \code{\link[CLVTools:plot.clv.data]{plot.clv.data}} to plot more nuanced diagnostics for the transaction data only.
#'
#' @seealso \code{\link[CLVTools:plot.clv.fitted.transactions]{plot}} for transaction models
#' @seealso \code{\link[CLVTools:plot.clv.data]{plot}} for transaction diagnostics of \code{clv.data} objects
#'
#' @return
#' An object of class \code{ggplot} from package \code{ggplot2} is returned by default.
#'
#' @examples
#' \donttest{
#' data("cdnow")
#'
#' clv.cdnow <- clvdata(cdnow,
#' date.format="ymd",
#' time.unit = "week",
#' estimation.split = "1997-09-30")
#'
#' est.gg <- gg(clv.data = clv.cdnow)
#'
#' # Compare empirical to theoretical distribution
#' plot(est.gg)
#'
#' \dontrun{
#' # Modify the created plot further
#' library(ggplot2)
#' gg.cdnow <- plot(est.gg)
#' gg.cdnow + ggtitle("CDnow Spending Distribution")
#' }
#' }
#'
#' @template template_references_gg
#'
#' @importFrom graphics plot
#' @importFrom ggplot2 ggplot aes stat_density geom_line labs theme scale_colour_manual guide_legend element_text element_rect element_blank element_line rel
#' @method plot clv.fitted.spending
#' @export
plot.clv.fitted.spending <- function (x, n = 256, verbose=TRUE, ...) {
Spending <- NULL
# Check inputs -----------------------------------------------------------------------------------------------------
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose"))
err.msg <- c(err.msg, .check_user_data_single_numeric(n=n, var.name="n"))
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
check_err_msg(err.msg = err.msg)
# readability
clv.fitted <- x
# Plot customer's mean spending as density -------------------------------------------------------------------------
dt.customer.mean.spending <- clv.fitted@cbs[x>0, "Spending"]
p <- clv.data.make.density.plot(dt.data = dt.customer.mean.spending,
mapping = aes(x = Spending, colour = "Actual"),
labs_x = "Average Value per Transaction",
title = "Density of Average Transaction Value",
color="black", geom = "line",
n = n)
# Overlay with model density ---------------------------------------------------------------------------------------
p <- p + geom_line(stat = "function",
mapping = aes(x = Spending, colour = [email protected]@name.model),
fun = clv.model.probability.density,
args = list(clv.model = [email protected], clv.fitted = clv.fitted),
n = n,
na.rm = FALSE)
# Add legend
columns <- setNames(c("black", "red"), c("Actual", [email protected]@name.model))
p <- p + scale_colour_manual(name = "Legend", values = columns)
return(p)
}
#' @exportMethod plot
#' @include class_clv_fitted_spending.R
#' @rdname plot.clv.fitted.spending
setMethod("plot", signature(x="clv.fitted.spending"), definition = plot.clv.fitted.spending)
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvfittedspending_plot.R
|
#' @title Plot Diagnostics for a Fitted Transaction Model
#' @param x The fitted transaction model for which to produce diagnostic plots
#' @param which Which plot to produce, either "tracking" or "pmf". May be abbreviated but only one may be selected. Defaults to "tracking".
#' @param other.models List of fitted transaction models to plot. List names are used as colors, standard colors are chosen if unnamed (see examples).
#' The \code{clv.data} object stored in each model is used if no \code{newdata} is given.
#'
#' @param cumulative "tracking": Whether the cumulative expected (and actual) transactions should be plotted.
#' @templateVar prefix "tracking":
#' @templateVar plot_or_predict plot
#' @template template_param_predictionend
#'
#' @param trans.bins "pmf": Vector of positive integer numbers (>=0) indicating the number of repeat transactions (x axis) to plot. Should contain 0 in nearly all cases as it refers to repeat-transactions.
#' @param calculate.remaining "pmf": Whether the probability for the remaining number of transactions not in \code{trans.bins} should be calculated.
#' @param label.remaining "pmf": Label for the last bar, if \code{calculate.remaining=TRUE}.
#'
#' @param newdata An object of class clv.data for which the plotting should be made with the fitted model.
#' If none or NULL is given, the plot is made for the data on which the model was fit.
#' If \code{other.models} was specified, the data in each model is replaced with \code{newdata}.
#' @param transactions Whether the actual observed repeat transactions should be plotted.
#' @param label Character vector to label each model. If NULL, the model(s) internal name is used (see examples).
#' @param plot Whether a plot is created or only the assembled data is returned.
#' @template template_param_verbose
#' @template template_param_dots
#'
#'
#' @description
#' Depending on the value of parameter \code{which}, one of the following plots will be produced.
#' See \code{\link[CLVTools:plot.clv.data]{plot.clv.data}} to plot more nuanced diagnostics for the transaction data only.
#' For comparison, other models can be drawn into the same plot by specifying them in \code{other.models} (see examples).
#'
#'
#' \subsection{Tracking Plot}{
#' Plot the actual repeat transactions and overlay it with the repeat transaction as predicted
#' by the fitted model. Currently, following previous literature, the in-sample unconditional
#' expectation is plotted in the holdout period. In the future, we might add the option to also
#' plot the summed CET for the holdout period as an alternative evaluation metric.
#' Note that only whole periods can be plotted and that the prediction end might not exactly match \code{prediction.end}.
#' See the Note section for more details.
#' }
#'
#' \subsection{PMF Plot}{
# Plot the actual number of customers which made a given number of repeat transactions in the estimation period
# and compare it to the expected number, as by the fitted model.
#
#' Plot the actual and expected number of customers which made a given number of repeat
#' transaction in the estimation period. The expected number is based on the PMF of the fitted model,
#' the probability to make exactly a given number of repeat transactions in the estimation period.
#' For each bin, the expected number is the sum of all customers' individual PMF value.
#' Note that if \code{trans.bins} is changed, \code{label.remaining} needs to be adapted as well.
#'
#' }
#'
#' @template template_details_predictionend
#' @template template_details_newdata
#'
#'
#' @note Because the unconditional expectation for a period is derived as the difference of
#' the cumulative expectations calculated at the beginning and at end of the period,
#' all timepoints for which the expectation is calculated are required to be spaced exactly 1 time unit apart.
#'
#' If \code{prediction.end} does not coincide with the start of a time unit, the last timepoint
#' for which the expectation is calculated and plotted therefore is not \code{prediction.end}
#' but the start of the first time unit after \code{prediction.end}.
#'
#' @seealso \code{\link[CLVTools:plot.clv.fitted.spending]{plot.clv.fitted.spending}} for diagnostics of spending models
#' @seealso \code{\link[CLVTools:plot.clv.data]{plot.clv.data}} for transaction diagnostics of \code{clv.data} objects
#' @seealso \code{\link[CLVTools:pmf]{pmf}} for the values on which the PMF plot is based
#'
#'
#' @return
#' An object of class \code{ggplot} from package \code{ggplot2} is returned by default.
#' If \code{plot=FALSE}, the data that would have been used to create the plot is returned.
#' Depending on which plot was selected, this is a data.table which contains the
#' following columns:
#'
#' For the Tracking plot:
#' \item{period.until}{The timepoint that marks the end (up until and including) of the period to which the data in this row refers.}
#' \item{variable}{Type of variable that 'value' refers to. Either "model name" or "Actual" (if \code{transactions=TRUE}).}
#' \item{value}{Depending on variable either (Actual) the actual number of repeat transactions in the period that ends at \code{period.until},
#' or the unconditional expectation for the period that ends on \code{period.until} ("model name").}
#'
#' For the PMF plot:
#' \item{num.transactions}{The number of repeat transactions in the estimation period (as ordered factor).}
#' \item{variable}{Type of variable that 'value' refers to. Either "model name" or "Actual" (if \code{transactions=TRUE}).}
#' \item{value}{Depending on variable either (Actual) the actual number of customers which have the respective number of repeat transactions,
#' or the number of customers which are expected to have the respective number of repeat transactions, as by the fitted model ("model name").}
#'
#'
#'
#' @examples
#' \donttest{
#'
#' data("cdnow")
#'
#' # Fit ParetoNBD model on the CDnow data
#' clv.cdnow <- clvdata(cdnow, time.unit="w",
#' estimation.split=37,
#' date.format="ymd")
#' pnbd.cdnow <- pnbd(clv.cdnow)
#'
#' ## TRACKING PLOT
#' # Plot actual repeat transaction, overlayed with the
#' # expected repeat transactions as by the fitted model
#' plot(pnbd.cdnow)
#'
#' # Plot cumulative expected transactions of only the model
#' plot(pnbd.cdnow, cumulative=TRUE, transactions=FALSE)
#'
#' # Plot until 2001-10-21
#' plot(pnbd.cdnow, prediction.end = "2001-10-21")
#'
#' # Plot until 2001-10-21, as date
#' plot(pnbd.cdnow,
#' prediction.end = lubridate::dym("21-2001-10"))
#'
#' # Plot 15 time units after end of estimation period
#' plot(pnbd.cdnow, prediction.end = 15)
#'
#' # Save the data generated for plotting
#' # (period, actual transactions, expected transactions)
#' plot.out <- plot(pnbd.cdnow, prediction.end = 15)
#'
#' # A ggplot object is returned that can be further tweaked
#' library("ggplot2")
#' gg.pnbd.cdnow <- plot(pnbd.cdnow)
#' gg.pnbd.cdnow + ggtitle("PNBD on CDnow")
#'
#'
#' ## PMF PLOT
#' plot(pnbd.cdnow, which="pmf")
#'
#' # For transactions 0 to 15, also have
#' # to change label for remaining
#' plot(pnbd.cdnow, which="pmf", trans.bins=0:15,
#' label.remaining="16+")
#'
#' # For transactions 0 to 15 bins, no remaining
#' plot(pnbd.cdnow, which="pmf", trans.bins=0:15,
#' calculate.remaining=FALSE)
#'
#' ## MODEL COMPARISON
#' # compare vs bgnbd
#' bgnbd.cdnow <- bgnbd(clv.cdnow)
#' ggomnbd.cdnow <- ggomnbd(clv.cdnow)
#'
#' # specify colors as names of other.models
#' # note that ggomnbd collapses into the pnbd on this dataset
#' plot(pnbd.cdnow, cumulative=TRUE,
#' other.models=list(blue=bgnbd.cdnow, "#00ff00"=ggomnbd.cdnow))
#'
#' # specify names as label, using standard colors
#' plot(pnbd.cdnow, which="pmf",
#' other.models=list(bgnbd.cdnow),
#' label=c("Pareto/NBD", "BG/NBD"))
#' }
#'
#' @importFrom graphics plot
#' @include class_clv_fitted.R
#' @method plot clv.fitted.transactions
#' @aliases plot
#' @export
plot.clv.fitted.transactions <- function (x,
which=c("tracking", "pmf"),
other.models=list(),
# tracking
prediction.end=NULL,
cumulative=FALSE,
# pmf
trans.bins = 0:9,
calculate.remaining = TRUE,
label.remaining="10+",
# general
newdata=NULL,
transactions=TRUE,
label=NULL,
plot=TRUE,
verbose=TRUE,
...) {
# Check inputs ------------------------------------------------------------------------------------------------------
# Do before replacing newdata as it may be costly
# Cannot plot if there are any NAs in any of the prediction.params
clv.controlflow.check.prediction.params(clv.fitted = x)
err.msg <- c()
err.msg <- c(err.msg, .check_userinput_matcharg(char=which, choices=c("tracking", "pmf"), var.name="which"))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=transactions, var.name="transactions"))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=plot, var.name="plot"))
err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose"))
err.msg <- c(err.msg, check_user_data_othermodels(other.models=other.models))
err.msg <- c(err.msg, check_user_data_emptyellipsis(...))
check_err_msg(err.msg)
check_err_msg(check_user_data_label(label=label, other.models=other.models))
# Newdata ------------------------------------------------------------------------------------------------
# Because many of the following steps refer to the data stored in the fitted model,
# it first is replaced with newdata before any other steps are done
#
# Skip replacing newdata if there are other models, as each model will be called again separately with newdata.
# This saves replacing the clv.data in the main model (x) two times at initial call with other.models and separte call to plot for x only.
# (costly mem copy and some models require re-doing LL)
if(!is.null(newdata) & length(other.models)==0){
# check newdata
clv.controlflow.check.newdata(clv.fitted = x, user.newdata = newdata, prediction.end=prediction.end)
# Replace data in model with newdata
# Deep copy to not change user input
[email protected] <- copy(newdata)
# Do model dependent steps of adding newdata
x <- clv.model.process.newdata(clv.model = [email protected], clv.fitted=x, verbose=verbose)
}
return(switch(match.arg(arg = tolower(which), choices = c("tracking","pmf")),
"tracking" = clv.fitted.transactions.plot.tracking(x=x, other.models=other.models, newdata=newdata, prediction.end=prediction.end,
cumulative=cumulative, transactions=transactions,
label=label, plot=plot, verbose=verbose),
"pmf" = clv.fitted.transactions.plot.barplot.pmf(x=x, newdata=newdata, other.models=other.models, trans.bins=trans.bins, transactions=transactions,
calculate.remaining=calculate.remaining, label.remaining=label.remaining,
label=label, plot=plot, verbose=verbose)))
}
#' @exportMethod plot
#' @include class_clv_fitted.R
#' @rdname plot.clv.fitted.transactions
setMethod("plot", signature(x="clv.fitted.transactions"), definition = plot.clv.fitted.transactions)
#' @importFrom ggplot2 ggplot aes geom_line geom_vline labs scale_fill_manual guide_legend
clv.controlflow.plot.tracking.base <- function(dt.plot, clv.data, color.mapping){
# cran silence
period.until <- value <- variable <- NULL
# Plotting order
dt.plot[, variable := factor(variable, levels=names(color.mapping), ordered = TRUE)]
p <- ggplot(data = dt.plot, aes(x=period.until, y=value, colour=variable)) + geom_line()
# Add holdout line if there is a holdout period
if(clv.data.has.holdout(clv.data)){
p <- p + geom_vline(xintercept = as.numeric([email protected]@timepoint.holdout.start),
linetype="dashed", show.legend = FALSE)
}
# Variable color and name
p <- p + scale_fill_manual(values = color.mapping,
aesthetics = c("color", "fill"),
guide = guide_legend(title="Legend"))
# Axis and title
p <- p + labs(x = "Date", y= "Number of Repeat Transactions", title= paste0(clv.time.tu.to.ly([email protected]), " tracking plot"),
subtitle = paste0("Estimation end: ", clv.time.format.timepoint([email protected], [email protected]@timepoint.estimation.end)))
return(clv.data.plot.add.default.theme(p))
}
# Tracking plot --------------------------------------------------------------------------------------------
clv.fitted.transactions.plot.tracking <- function(x, other.models, newdata, prediction.end, cumulative, transactions,
label, plot, verbose, ...){
variable <- period.until <- period.num <- NULL
err.msg <- c()
err.msg <- c(err.msg, .check_user_data_single_boolean(b=cumulative, var.name="cumulative"))
err.msg <- c(err.msg, check_user_data_predictionend(clv.fitted=x, prediction.end=prediction.end))
check_err_msg(err.msg)
# do fitted object specific checks (ie dyncov checks cov data length)
clv.controlflow.plot.check.inputs(obj=x, prediction.end=prediction.end, cumulative=cumulative,
plot=plot, label.line=label, verbose=verbose)
if(length(other.models) == 0){
if(length(label) == 0){
label <- [email protected]@name.model
}
dt.plot <- clv.fitted.transactions.plot.tracking.get.data(
x=x, prediction.end = prediction.end, cumulative=cumulative, label=label, transactions=transactions, verbose=verbose)
dt.plot[variable == "expectation", variable := label]
dt.plot[variable == "num.repeat.trans", variable := "Actual"]
colors <- 'red'
}else{
label <- clv.fitted.transactions.plot.multiple.models.prepare.label(label=label, main.model=x, other.models=other.models)
other.models <- clv.fitted.transactions.plot.multiple.models.prepare.othermodels(other.models=other.models)
if(verbose){
message("Collecting data for other models...")
}
dt.plot <- clv.fitted.transactions.plot.multiple.models.get.data(main.model=x, other.models=other.models, label=label,
l.plot.args = list(which='tracking',
prediction.end=prediction.end,
newdata=newdata,
cumulative=cumulative, transactions=transactions, verbose=verbose))
# main model always in red
colors <- c('red', names(other.models))
}
if(!plot){
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.plot[]
return(dt.plot)
}else{
# add color and label for actuals
if(transactions){
label <- c('Actual', label) # Add 'Actual' as first! Required for correct ordering
colors <-c('black', colors)
}
# Plotting order as in label
dt.plot[, variable := factor(variable, levels=label, ordered = TRUE)]
# Plot table with formatting, label etc
return(clv.controlflow.plot.tracking.base(dt.plot = dt.plot, clv.data = [email protected], color.mapping = setNames(colors, label)))
}
}
clv.fitted.transactions.plot.tracking.get.data <- function(x, prediction.end, cumulative, transactions, label, verbose){
i.expectation <- expectation <- value <- num.repeat.trans <- i.num.repeat.trans <- period.num <- period.until <- NULL
# Define time period to plot
# Use table with exactly defined periods as reference and to save all generated data
# End date:
# Use same prediction.end date for clv.data (actual transactions) and clv.fitted (unconditional expectation)
# If there are not enough transactions for all dates, they are set to NA (= not plotted)
dt.dates.expectation <- clv.time.expectation.periods(clv.time = [email protected]@clv.time, user.tp.end = prediction.end)
tp.data.start <- dt.dates.expectation[, min(period.until)]
tp.data.end <- dt.dates.expectation[, max(period.until)]
if(verbose){
message("Plotting from ", tp.data.start, " until ", tp.data.end, ".")
}
if(clv.data.has.holdout([email protected])){
if(tp.data.end < [email protected]@[email protected]){
warning("Not plotting full holdout period.", call. = FALSE, immediate. = TRUE)
}
}else{
if(tp.data.end < [email protected]@[email protected]){
warning("Not plotting full estimation period.", call. = FALSE, immediate. = TRUE)
}
}
# Merge data for plotting
# To be sure to have all dates, merge data on original date
# Get expectation values
dt.expectation <- clv.fitted.transactions.add.expectation.data(clv.fitted.transactions=x, dt.expectation.seq=dt.dates.expectation,
cumulative=cumulative, verbose=verbose)
dt.dates.expectation[dt.expectation, expectation := i.expectation, on="period.until"]
# Get repeat transactions
if(transactions){
dt.repeat.trans <- clv.data.add.repeat.transactions.to.periods([email protected], dt.date.seq=dt.dates.expectation,
cumulative=cumulative)
dt.dates.expectation[dt.repeat.trans, num.repeat.trans := i.num.repeat.trans, on="period.until"]
}
dt.dates.expectation[, period.num := NULL]
dt.plot <- melt(dt.dates.expectation, id.vars='period.until')
# last period often has NA as it marks the full span of the period
dt.plot <- dt.plot[!is.na(value)]
return(dt.plot)
}
# PMF plot -----------------------------------------------------------------------------------------------
#' @importFrom ggplot2 ggplot geom_col position_dodge2 guide_legend scale_x_discrete
clv.fitted.transactions.plot.barplot.pmf <- function(x, newdata, other.models, trans.bins, transactions, label,
calculate.remaining, label.remaining, plot, verbose){
pmf.x <- pmf.value <- actual.num.customers <- expected.customers <- i.expected.customers <- NULL
num.customers <- num.transactions <- variable <- value <- NULL
check_err_msg(check_user_data_integer_vector_greater0(vec=trans.bins, var.name="trans.bins"))
check_err_msg(.check_userinput_charactervec(char=label.remaining, var.name="label.remaining", n=1))
check_err_msg(.check_user_data_single_boolean(b=calculate.remaining, var.name="calculate.remaining"))
if(length(other.models) == 0){
if(length(label) == 0){
label <- [email protected]@name.model
}
dt.plot <- clv.fitted.transactions.plot.barplot.pmf.get.data(
x=x, trans.bins = trans.bins, calculate.remaining=calculate.remaining, label.remaining = label.remaining, transactions = transactions)
dt.plot[variable=="expected.customers", variable := label]
dt.plot[variable=="actual.num.customers", variable := "Actual"]
colors <- 'red'
}else{
label <- clv.fitted.transactions.plot.multiple.models.prepare.label(label=label, main.model = x, other.models = other.models)
other.models <- clv.fitted.transactions.plot.multiple.models.prepare.othermodels(other.models = other.models)
if(verbose){
message("Collecting data for other models...")
}
dt.plot <- clv.fitted.transactions.plot.multiple.models.get.data(main.model = x, other.models = other.models, label = label,
l.plot.args = list(which="pmf",
trans.bins=trans.bins,
newdata=newdata,
label.remaining=label.remaining,
calculate.remaining=calculate.remaining, verbose=verbose))
colors <- c('red', names(other.models))
}
if(!plot){
# data.table does not print when returned because it is returned directly after last [:=]
# " if a := is used inside a function with no DT[] before the end of the function, then the next
# time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT)
# will print. To avoid this: include a DT[] after the last := in your function."
dt.plot[]
return(dt.plot)
}else{
# add color and label for actuals
if(transactions){
label <- c('Actual', label) # Add 'Actual' as first! Required for correct ordering
colors <-c('black', colors)
}
# Plotting order
dt.plot[, variable := factor(variable, levels=label, ordered = TRUE)]
p <- ggplot(dt.plot)+geom_col(aes(x=num.transactions, fill=variable, y=value),
width = 0.5, position=position_dodge2(width = 0.9))
# add count annotation
p <- p + geom_text(aes(group=variable, label = round(value, digits=1),
x = num.transactions, y = value),
position = position_dodge2(width = 0.5),
vjust = -0.6,
size = rel(3))
# Variable color and name
p <- p + scale_fill_manual(values = setNames(colors, label),
aesthetics = c("color", "fill"),
guide = guide_legend(title="Legend"))
# # show missing values as 0 (if there are)
p <- p + scale_x_discrete(na.translate=TRUE, na.value=0)
# Axis and title
p <- p + labs(x = "Number of Repeat Transactions", y="Number of Customers",
title="Frequency of Repeat Transactions in the Estimation Period")
return(clv.data.plot.add.default.theme(p, custom = list(axis.text.x = element_text(face="bold"))))
}
}
clv.fitted.transactions.plot.barplot.pmf.get.data <- function(x, trans.bins, calculate.remaining, label.remaining, transactions){
actual.num.customers <- num.customers <- expected.customers <- i.expected.customers <- char.num.transactions <- num.transactions <- pmf.x <- pmf.value <- NULL
# also done in plot.clv.data and pmf() but do explicitly
trans.bins <- sort(unique(trans.bins))
# Always work with the actuals from plot() as basis to have ordered factors
# Collect actual transactions
dt.actuals <- plot([email protected], which="frequency", plot=FALSE, verbose=FALSE,
sample="estimation",
trans.bins=trans.bins, count.repeat.trans=TRUE,
count.remaining=calculate.remaining, label.remaining = label.remaining)
# Collect pmf values
# are per customer, aggregate per x
dt.pmf <- pmf(x, x=trans.bins)
# Calculate pmf of remaining (not explicitly calculated x)
# P(remaining) is leftover probability (1-all others)
if(calculate.remaining){
dt.pmf[, (label.remaining) := 1 - rowSums(.SD), .SDcols = !"Id"]
}
dt.pmf <- melt(dt.pmf, id.vars = "Id", variable.factor = FALSE,
variable.name="pmf.x", value.name="pmf.value")
dt.pmf <- dt.pmf[, list(expected.customers = sum(pmf.value)), by="pmf.x"]
# Add num expected trans for each num.transactions
# match on separate char representation of num.transactions to keep it as ordered factor
dt.pmf[, char.num.transactions := gsub(x=pmf.x, pattern="pmf.x.", replacement="")]
dt.actuals[, char.num.transactions := as.character(num.transactions)]
dt.actuals[dt.pmf, expected.customers := i.expected.customers, on = "char.num.transactions"]
dt.actuals[, char.num.transactions := NULL]
dt.actuals[, num.customers := as.numeric(num.customers)] # integer leads to melt warning
setnames(dt.actuals, "num.customers", "actual.num.customers")
if(!transactions){
# Drop actuals if not needed
dt.actuals[, actual.num.customers := NULL]
}
return(melt(dt.actuals, id.vars="num.transactions", variable.factor=FALSE))
}
# other.models -----------------------------------------------------------------------------------------------
clv.fitted.transactions.plot.multiple.models.prepare.label <- function(label, main.model, other.models){
# create labels from model's name if missing
if(length(label)==0){
label <- c([email protected]@name.model,
sapply(other.models, function(m){
[email protected]@name.model
}))
# postfix duplicate names because it breaks data stored in long-format
label <- make.unique(label, sep = "_")
}
return(label)
}
clv.fitted.transactions.plot.multiple.models.prepare.othermodels <- function(other.models){
if(is.null(names(other.models))){
names(other.models) <- rep_len("", length.out = length(other.models))
}
# replace missing names with colors
other.models.not.named <- nchar(names(other.models)) == 0
if(sum(other.models.not.named) > 0){
# cbbPalette without black and red
palette <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#CC79A7")
names(other.models)[other.models.not.named] <- palette[seq(sum(other.models.not.named))]
}
return(other.models)
}
#' @importFrom utils modifyList
clv.fitted.transactions.plot.multiple.models.get.data <- function(main.model, other.models, label, l.plot.args){
# Collect plot data for main model separately because includes actuals if desired
dt.plot <- do.call(plot, args = modifyList(x = l.plot.args,
val=list(x=main.model, plot=FALSE, label=label[1]),
keep.null = TRUE))
# Collect plot data for all other models (always without actuals)
# use for loop instead of lapply because requires access to label (and mapply is cumbersome)
l.plot.others <- list()
for(i in seq(other.models)){
# Have to call plot() generic and not relevant function because there could be newdata which has to be updated in each model
l.plot.others[[i]] <- do.call(plot, args = modifyList(x=l.plot.args,
val=list(x=other.models[[i]], plot=FALSE, transactions=FALSE, label= label[i+1]),
keep.null = TRUE))
}
return(rbindlist(c(list(dt.plot), l.plot.others), use.names = T))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvfittedtransactions_plot.R
|
#' @export
#' @include class_clv_fitted_transactions_staticcov.R
print.clv.fitted.transactions.static.cov <- function(x, digits = max(3L, getOption("digits") - 3L), ...){
# print standard parts
NextMethod()
# options used
cat("Constraints: ", [email protected], "\n")
cat("Regularization: ", [email protected], "\n")
invisible(x)
}
#' @rdname summary.clv.fitted
#' @order 2
#' @include class_clv_data_staticcovariates.R
#' @export
summary.clv.fitted.transactions.static.cov <- function(object, ...){
# Get basic structure from nocov
res <- NextMethod()
class(res) <- c("summary.clv.fitted.transactions.static.cov", class(res))
# Add further optimization options -----------------------------------------------
# Regularization
# lambdas
# Constraint covs
# which
res$additional.options <- c(res$additional.options,
"Regularization"[email protected])
if([email protected]){
res$additional.options <- c(res$additional.options,
" lambda.life" = [email protected],
" lambda.trans" = [email protected])
}
res$additional.options <- c(res$additional.options,
"Constraint covs" = [email protected])
if([email protected]){
res$additional.options <- c(res$additional.options,
" Constraint params" = paste([email protected], collapse = ", "))
}
return(res)
}
#' @importFrom stats coef na.omit setNames
#' @importFrom optimx coef<-
#' @importFrom utils tail
#' @include class_clv_fitted_transactions_staticcov.R
#' @export
coef.clv.fitted.transactions.static.cov <- function(object, ...){
# Covariates params -----------------------------------------------------------------------------------
# Is estimated check and backtransformed coefs from model only
original.scale.coef.model <- NextMethod()
last.row.optimx.coef <- tail(coef([email protected]),n=1)
# Covariate params
# Do NOT duplicate constrained params because output of coef() has to match vcov!
if([email protected]){
names.prefixed.covs <- union([email protected],
union([email protected],
[email protected]))
}else{
names.prefixed.covs <- union([email protected],
[email protected])
}
# if for whatever reason there is still a NA leftover from previous design of constrained param names
names.prefixed.covs <- na.omit(names.prefixed.covs)
# let model backtransform from optimizer to original scale
prefixed.params.cov <- last.row.optimx.coef[1, names.prefixed.covs, drop=TRUE]
prefixed.params.cov <- setNames(prefixed.params.cov, names.prefixed.covs) # Names are lost if only 1 cov (single constraint)
original.scale.params.cov <- clv.model.backtransform.estimated.params.cov(clv.model = [email protected],
prefixed.params.cov = prefixed.params.cov)
# There are no display/original scale names to set for covariates. They need the prefix to stay
# distinguishable between processes
original.scale.params.cov <- setNames(original.scale.params.cov[names.prefixed.covs],
names.prefixed.covs)
# Put together in correct order ------------------------------------------------------------------------------------------
# relevant order is as in optimx so that coef output is in the same order as vcov() / hessian
# it should also be possible through input structure to optimx (ie c(model, cov)) but guarantee
# by explicitely setting the same order as in optimx. This is greatly complicated by differing/prefixed names
#
# covariates params keep prefix to stay distinguishable
# mapping for original to prefixed
# content: original names for model and correlation, prefixed names for cov params
# names: prefixed names
# Content + transformed names for model and cor
# append correlation param, if exists and should be returned. If not included here, it is removed from nocov param vec
names.original.named.prefixed.all <- names(original.scale.coef.model)
if(clv.model.estimation.used.correlation(clv.model = [email protected])){
names(names.original.named.prefixed.all) <- c([email protected]@names.prefixed.params.model,
[email protected]@name.prefixed.cor.param.m)
}else{
names(names.original.named.prefixed.all) <- [email protected]@names.prefixed.params.model
}
# Content + prefixed names for covs
names.original.named.prefixed.all <- c(names.original.named.prefixed.all,
setNames(names(original.scale.params.cov),
names(original.scale.params.cov)))
# bring into same order as in optimx
# read definitive order from optimx through prefixed names
names.optimx.coefs <- colnames(last.row.optimx.coef)
# bring original scale names into order of optimx (prefixed) names
names.original.named.prefixed.all <- names.original.named.prefixed.all[names.optimx.coefs]
# put together return values in original scale
params.all <- c(original.scale.coef.model, original.scale.params.cov)
# return in correct order
return(params.all[names.original.named.prefixed.all])
}
#' @include all_generics.R class_clv_fitted_transactions_staticcov.R
#' @importFrom methods show
#' @export
#' @rdname clv.fitted.transactions.static.cov-class
setMethod(f = "show", signature = signature(object="clv.fitted.transactions.static.cov"), definition = function(object){
print(x=object)})
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvfittedtransactions_staticcov.R
|
#' @include class_clv_time.R
#' @importFrom methods show
#' @export
#' @rdname clv.time-class
setMethod(f = "show", signature = signature(object="clv.time"), definition = function(object){
print(x=object)})
#' @rdname summary.clv.time
#' @include class_clv_time.R
#' @keywords internal
#' @export
print.clv.time <- function(x, digits=max(3L, getOption("digits")-3L), ...){
nsmall <- 4 # dont leave to user, hardcode
has.holdout <- clv.time.has.holdout(clv.time=x)
.print.list(list("Time unit" = [email protected],
" " ="",
"Estimation start" = clv.time.format.timepoint(clv.time=x, [email protected]),
"Estimation end" = clv.time.format.timepoint(clv.time=x, [email protected]),
"Estimation length" = paste0(format([email protected], digits=digits,nsmall=nsmall), " ", [email protected]),
" " ="",
"Holdout start" = ifelse(has.holdout, clv.time.format.timepoint(clv.time=x, [email protected]), "-"),
"Holdout end" = ifelse(has.holdout, clv.time.format.timepoint(clv.time=x, [email protected]), "-"),
"Holdout length" = ifelse(has.holdout, paste0(format([email protected], nsmall=nsmall), " ", [email protected]), "-")),
nsmall=nsmall)
cat("\n")
invisible(x)
}
#' @template template_summary_clvtime
#' @include class_clv_time.R
#' @export
summary.clv.time <- function(object, ...){
res <- structure(list(), class="summary.clv.time")
res$name.time.unit <- [email protected]
res$estimation.period.in.tu <- [email protected]
res$has.holdout <- clv.time.has.holdout(clv.time=object)
if(res$has.holdout)
res$holdout.period.in.tu <- [email protected]
return(res)
}
#' @keywords internal
#' @export
print.summary.clv.time <-function(x, digits=max(3L, getOption("digits")-3L), ...){
nsmall <- 4
.print.list(list("Time unit" = x$name.time.unit,
"Estimation length" = paste0(format(x$estimation.period.in.tu, digits=digits,nsmall=nsmall), " ", x$name.time.unit),
"Holdout length" = ifelse(x$has.holdout, paste0(format(x$holdout.period.in.tu, nsmall=nsmall), " ", x$name.time.unit), "-"))
, nsmall=nsmall)
return(invisible(x))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/f_s3generics_clvtime.R
|
# There is no next.interlayer
#' @importFrom utils modifyList
interlayer_callLL <- function(LL.function.sum, LL.params, LL.params.names.ordered, ...){
all.other.args <- list(...)
# Order LL params --------------------------------------------------------------
# As the order of the LL params may differ by function (ie trans vs life),
# bring them in the needed order
# This will also remove any param which was not specified in
# LL.params.names.ordered what could be desirable
LL.params <- LL.params[LL.params.names.ordered]
# Call LL ----------------------------------------------------------------------
# Call the specified LL function with the new params
allowed.LL.function.arg.names <- formalArgs(def = LL.function.sum)
# Create the args to call the LL function
# the params need to be in first position
LL.function.args <- list(LL.params)
LL.function.args <- modifyList(LL.function.args,
# Only pass the params allowed by the LL
all.other.args[intersect(allowed.LL.function.arg.names,
names(all.other.args))])
LL.res <- do.call(LL.function.sum, LL.function.args)
return(LL.res)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_callLL.R
|
# Call the single next layer in next.interlayers and pass all parameters
interlayer_callnextinterlayer <- function(next.interlayers, LL.params, LL.function.sum, ...){
all.other.args <- list(...)
# Put together call ----------------------------------------------------------
# remove the current interlayer
# Call layer on top
interlayer.call.args <- list(next.interlayers = next.interlayers[-1],
LL.params = LL.params,
LL.function.sum = LL.function.sum)
interlayer.call.args <- modifyList(interlayer.call.args, all.other.args)
return(do.call(what = next.interlayers[[1]], args = interlayer.call.args))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_callnextinterlayer.R
|
# LL.params are the unfixed parameters containing the unfixed params only once
#' @importFrom utils modifyList
interlayer_constraints <- function(next.interlayers, LL.params, LL.function.sum, names.original.params.constr, names.prefixed.params.constr, ...){
# Catch elipsis params immediately
all.other.args <- list(...)
# Construct new param set --------------------------------------------------------------
# Only a single param is given for the fixed params
#
# The vec LL.params contains all model params, all correctly named non-fixed params, and also
# the to-be-fixed, incorrectly named (missing prefix) params with a single param only per covariate
#
# Construct param vec:
# - Non fixed params
# - Fixed params
# - Add to-be-fixed parameters twice, once for life and once for trans
# - Add "life." and "trans." prefixes to names
# Add prefix to the names
fixed.params.names.life <- paste("life", names.original.params.constr, sep=".")
fixed.params.names.trans <- paste("trans", names.original.params.constr, sep=".")
# check if names exist
if(!(all(names.prefixed.params.constr %in% names(LL.params))))
stop("The named constrained params are not among the parameters")
# All params but the fixed ones
new.LL.params <- LL.params[setdiff(names(LL.params), names.prefixed.params.constr)]
# Add the fixed params twice (passed in the orignal param vec as well)
new.LL.params[fixed.params.names.life] <- LL.params[names.prefixed.params.constr]
new.LL.params[fixed.params.names.trans] <- LL.params[names.prefixed.params.constr]
# Call next interlayer ------------------------------------------------------
# Use do.call to integrate ... args
next.interlayer.call.args <- list(next.interlayers = next.interlayers,
LL.params = new.LL.params,
LL.function.sum = LL.function.sum)
next.interlayer.call.args <- modifyList(next.interlayer.call.args,
all.other.args)
return(do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_constraints.R
|
#' @importFrom utils modifyList
interlayer_correlation <- function(next.interlayers, LL.params, LL.function.sum, LL.function.ind, name.prefixed.cor.param.m, check.param.m.bounds, ...){
# Catch all other args in elipsis
all.other.args <- list(...)
# Read out pnbd model params
alpha_0 <- exp(LL.params[["log.alpha"]])
r <- exp(LL.params[["log.r"]])
beta_0 <- exp(LL.params[["log.beta"]])
s <- exp(LL.params[["log.s"]])
param.m <- LL.params[[name.prefixed.cor.param.m]]
# Laplace transformations
LA <- (alpha_0 / (1 + alpha_0))^r
LB <- (beta_0 / (1 + beta_0 ))^s
if(check.param.m.bounds){
# Restrain m to be in the interval [lowerbound, upperbound]
upperbound <- 1 / max( LA*(1- LB), (1-LA)*LB )
lowerbound <- -1 / max( LA*LB , (1-LA)*(1-LB))
if( param.m > upperbound || param.m < lowerbound){
return(NA_real_)
}
}
# Each model param + 1 while keeping the others unchanged
params.00 <- LL.params
params.10 <- LL.params
params.01 <- LL.params
params.11 <- LL.params
optimx.names.model <- all.other.args[["obj"]]@[email protected]
params.00[optimx.names.model] <- log(c(r, alpha_0, s, beta_0))
params.10[optimx.names.model] <- log(c(r, alpha_0+1, s, beta_0))
params.01[optimx.names.model] <- log(c(r, alpha_0, s, beta_0+1))
params.11[optimx.names.model] <- log(c(r, alpha_0+1, s, beta_0+1))
# Call individual LL for each of these parameter combinations --------------------------------------
next.interlayer.call.args <- list(next.interlayers = next.interlayers,
LL.function.sum = LL.function.ind) # use the individual LL function
next.interlayer.call.args <- modifyList(next.interlayer.call.args,
all.other.args)
next.interlayer.call.args.00 <- modifyList(next.interlayer.call.args, list(LL.params = params.00))
next.interlayer.call.args.10 <- modifyList(next.interlayer.call.args, list(LL.params = params.10))
next.interlayer.call.args.01 <- modifyList(next.interlayer.call.args, list(LL.params = params.01))
next.interlayer.call.args.11 <- modifyList(next.interlayer.call.args, list(LL.params = params.11))
LL.00 <- do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args.00)
LL.01 <- do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args.01)
LL.10 <- do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args.10)
LL.11 <- do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args.11)
# Catch errors before they crash the addition below due to unqual extent
if(any(!is.finite(LL.00), !is.finite(LL.01), !is.finite(LL.10), !is.finite(LL.11))){
return(NA_real_)
}
# Return summed cor LL values
vLL <- exp(LL.00) + param.m*LA*LB * (exp(LL.00) + exp(LL.11) - exp(LL.10) - exp(LL.01))
vLL <- log(vLL)
return(-sum(vLL))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_correlation.R
|
# Entry point called by optimx.
# Puts together all interlayers needed depending on the specified parameters
#
#
# Interlayers are put together depending on the parameters given.
# No additional input checks are performed on any given parameter
#
# @param ... All other arguments to be given to the LL function
#
# LL.params needs to be the first argument as it will receive the parameters from the optimizer
#' @importFrom utils modifyList
interlayer_manager <- function(LL.params, LL.param.names.to.optimx, LL.function.sum,
use.interlayer.constr,
use.interlayer.reg, reg.lambda.trans, reg.lambda.life,
use.cor,
...){
all.other.args <- list(...)
# Parameter names are removed by some optimization methods
# Add back because crucial for further interlayers
names(LL.params) <- LL.param.names.to.optimx
# Put together the interlayers -----------------------------------------------
# Depends on the parameters given
# Content: use interlayer
# NULL: dont use interlayer
#
# Interlayers will be called recursively, using the
# one on top (first position) as next.
#
# Last interlayer to call therefore always is _callLL()
#
# If some parameters are constraint, they need to be the very first,
# as this interlayer only generates the parameters which will then be
# used by the other interlayers
# if covs were constraint, the names for all params are needed per
# process in _callLL and regularization interlayer. These are generated
# here from the original cov data names
# Add callLL as first and append all other interlayers before that
# (callLL will be called as last)
interlayers.to.use <- list("callLL"=interlayer_callLL)
# Add correlation interlayer if needed
if(use.cor == T & !anyNA(use.cor))
interlayers.to.use <- c("correlation"=interlayer_correlation, interlayers.to.use)
# Add regularization interlayer if needed
if(use.interlayer.reg == T &
!is.null(reg.lambda.trans) & !anyNA(reg.lambda.trans) &
!is.null(reg.lambda.life) & !anyNA(reg.lambda.life)){
interlayers.to.use <- c("regularization"=interlayer_regularization, interlayers.to.use)
}
# Add constraint infront of all other interlayers, if needed
if(use.interlayer.constr == TRUE){
interlayers.to.use <- c("constraints"=interlayer_constraints, interlayers.to.use)
}
# Start calling the interlayers ----------------------------------------------
# Use do call to integrate ... args
interlayer.call.args <- list(next.interlayers = interlayers.to.use,
LL.function.sum = LL.function.sum,
LL.params = LL.params,
reg.lambda.life = reg.lambda.life,
reg.lambda.trans = reg.lambda.trans)
interlayer.call.args <- modifyList(interlayer.call.args,
all.other.args)
return(do.call(what = interlayer_callnextinterlayer, args = interlayer.call.args))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_manager.R
|
#' @importFrom utils modifyList
interlayer_regularization <- function(next.interlayers, LL.params, LL.function.sum,
names.prefixed.params.after.constr.life, names.prefixed.params.after.constr.trans,
reg.lambda.life, reg.lambda.trans, num.observations, ...){
all.other.args <- list(...)
# Calculate LL value --------------------------------------------------------
# The LL value is calculate by the next interlayer and may pass through
# additional layers before actually being calculated
# Use do.call to integrate ... args
next.interlayer.call.args <- list(next.interlayers = next.interlayers,
LL.params = LL.params,
LL.function.sum = LL.function.sum)
next.interlayer.call.args <- modifyList(next.interlayer.call.args,
all.other.args)
LL.value <- do.call(what = interlayer_callnextinterlayer, args = next.interlayer.call.args)
if(!is.finite(LL.value))
return(LL.value)
# Regularization --------------------------------------------------------------
# LL value + regularization term
#
# regularization term := lambda.trans * t(cov.trans) * params.trans +
# lambda.life * t(cov.life) * params.life
params.cov.life <- LL.params[names.prefixed.params.after.constr.life]
params.cov.trans <- LL.params[names.prefixed.params.after.constr.trans]
reg.term <- reg.lambda.trans*t(params.cov.trans)%*%params.cov.trans + reg.lambda.life*t(params.cov.life)%*%params.cov.life
reg.term <- as.vector(reg.term)
avg.LL.value <- LL.value / num.observations
# Return sum of LL and regterm
# Add reg term to pull negative avg LL value towards 0
return(avg.LL.value + reg.term)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/interlayer_regularization.R
|
# Covariate data of
# No covariate after date.upper.cov is considered. Do floor_timeunit() as required before calling
# - Calculate exp.gX.P/L
# - Cut to alive periods per customer
# - Cut to maximum date
# For life and trans together because it is much easier to pass in single clv.fitted and not all parts alone
pnbd_dyncov_alivecovariates <- function(clv.fitted, date.upper.cov){
# cran silence
Cov.Date <- exp.gX.L <- exp.gX.P <- date.cov.period.coming.alive <- date.first.actual.trans <- i.date.cov.period.coming.alive <- is.alive.in.period <- NULL
# For more readable code
clv.time <- [email protected]@clv.time
names.cov.life <- [email protected]@names.cov.data.life
names.cov.trans <- [email protected]@names.cov.data.trans
# Initial cutting:
# Values are calculated for all available data since start of estimation
# and only cut to required shorter length later as required
# -> min lower: floor_tu(estimation.start)
# No covariate after date.upper.cov is considered
date.first.cov <- clv.time.floor.date(clv.time=clv.time,[email protected])
# Only keep cov data between first and last allowable date
dt.life <- [email protected]@data.cov.life[Cov.Date >= date.first.cov & Cov.Date <= date.upper.cov, .SD, .SDcols = c("Id", "Cov.Date", names.cov.life)]
dt.trans <- [email protected]@data.cov.trans[Cov.Date >= date.first.cov & Cov.Date <= date.upper.cov, .SD, .SDcols = c("Id", "Cov.Date", names.cov.trans)]
# matrix multiply per date and customer ---------------------------------------------------------------------
# matrix multiplication by=c("date", "Id") is extremely slow, but can do cov1*g1+cov2*g2+cov3*g3+...
# However, row-wise vec*DT is not possible unless also a data.frame/table of same dimension.
# Therefore, add gammas as separate columns to have them as data.table as well
# Gammas need to have separate names from cov data
# Also, this step ensures same order of names and gammas when using as .SDcols when multiplying
names.gamma.life <- paste0("gamma.", names.cov.life)
names.gamma.trans <- paste0("gamma.", names.cov.trans)
# Write gamma values in gamma columns (one whole column per gamma value)
# Subset with names.cov.* to ensure the same order as names.gamma.*
dt.life[, (names.gamma.life) := data.table(t([email protected][names.cov.life]))]
dt.trans[, (names.gamma.trans) := data.table(t([email protected][names.cov.trans]))]
# Multiply data * gammas element-wise and sum row-wise
# actually multiplies data.table*data.table element-wise and then rowSums is like sum per c("Id","Cov.Date")
dt.life[, exp.gX.L := exp(rowSums(dt.life[, .SD, .SDcols=names.gamma.life] * dt.life[, .SD, .SDcols=names.cov.life]))]
dt.trans[, exp.gX.P := exp(rowSums(dt.trans[, .SD, .SDcols=names.gamma.trans] * dt.trans[, .SD, .SDcols=names.cov.trans]))]
# Cut to when alive ---------------------------------------------------------------------------------
# Calculate the period when customer became alive.
# Do this outside dt.life once for every customer in a separate table to avoid calling
# clv.time.floor.date (S4 function) for every row separately
dt.customer.alive <- clv.fitted@cbs[, c("Id", "date.first.actual.trans")]
dt.customer.alive[, date.cov.period.coming.alive := clv.time.floor.date(clv.time=clv.time,
timepoint=date.first.actual.trans)]
# Add when customers became alive to every cov data
dt.life[ dt.customer.alive, date.cov.period.coming.alive := i.date.cov.period.coming.alive, on="Id"]
dt.trans[dt.customer.alive, date.cov.period.coming.alive := i.date.cov.period.coming.alive, on="Id"]
# Only the covariates at which the customer is alive
# Including the one active when customer became alive (by doing floor_date before)
dt.life[, is.alive.in.period := Cov.Date >= date.cov.period.coming.alive]
dt.trans[, is.alive.in.period := Cov.Date >= date.cov.period.coming.alive]
dt.life <- dt.life[is.alive.in.period == TRUE]
dt.trans <- dt.trans[is.alive.in.period == TRUE]
return(list(dt.trans = dt.trans, dt.life = dt.life))
}
pnbd_dyncov_ABCD <- function(clv.fitted, prediction.end.date){
Cov.Date <- i <- exp.gX.P <- i.exp.gX.P <- Ai <- Ci <- exp.gX.L <- Bbar_i <- T.cal <- i.T.cal <- Dbar_i <- NULL
d_omega <- i.d_omega <- is.customers.first.cov <- num.period.alive <- NULL
# For more understandable, clean code
clv.time <- [email protected]@clv.time
# Covariate Values ---------------------------------------------------------------------------------------------------
# Calculate values from covariates and gammas, ie exp(gammas*cov) and cuts to only these when customer is alive
#
# The Ai, Bi, Ci, Di parts have to be built, so that the last (=the ith)
# covariate is active when prediction.end.date is
# If prediction.end.date falls directly onto the start of a covariate,
# the covariate is active then and included as well.
# => max cov: floor_tu(prediction.end.date)
#
# The first covariate in the prediction (i=1) is the one active when estimation.end is
# The covariate start date hence can be before the holdout.start and is also already
# used in the fitting
# => i=1: floor_tu(estimation.end)
date.last.cov <- clv.time.floor.date(clv.time=clv.time, timepoint=prediction.end.date)
l.covs <- pnbd_dyncov_alivecovariates(clv.fitted = clv.fitted, date.upper.cov = date.last.cov)
dt.trans <- l.covs[["dt.trans"]]
dt.life <- l.covs[["dt.life"]]
# i ---------------------------------------------------------------------------------------------------
# Define prediction period number i per customer
# As per definition, the first prediction period is the period where estimation.end lies in.
# Even if it was possible to properly separate estimation and prediction periods
# (ie they estimation.end and holdout.start are in separate periods) this is enforced because the
# notation relies on it and corrects for it (ie i is period num k0T+i-1, minus 1 to avoid double counting this overlap of periods)
# First period is the cov period in which the estimation end lies! (not the holdout.start)
date.first.prediction.period.start <- clv.time.floor.date(clv.time = clv.time,
timepoint = [email protected])
# Order by covariate date!
# 1 = Smallest date up
setorderv(dt.life, cols = "Cov.Date", order = 1)
setorderv(dt.trans, cols = "Cov.Date", order = 1)
# Write all i to data, by Id!
# Leave all i before prediction start intenionally as NA
# .N is nrow() - after cut to prediction period
dt.life[Cov.Date >= date.first.prediction.period.start, i := seq.int(from = 1, to = .N), by="Id"]
dt.trans[Cov.Date >= date.first.prediction.period.start, i := seq.int(from = 1, to = .N), by="Id"]
# Table with results data ----------------------------------------------------------------------------------
# Values for each Id/Cov combination in the prediction period
# in the prediction period = has value for i
dt.ABCD <- dt.life[!is.na(i), c("Id", "Cov.Date", "exp.gX.L", "i")]
setkeyv(dt.ABCD, cols = c("Id", "Cov.Date", "i"))
# Add transaction g*cov data
setkeyv(dt.trans, cols = c("Id", "Cov.Date"))
dt.ABCD[dt.trans, exp.gX.P := i.exp.gX.P, on=c("Id", "Cov.Date")]
# Ai & Ci ---------------------------------------------------------------------------------------------------
# They are both simply the gamma*cov values in the prediction period, for all Ids and dates
dt.ABCD[, Ai := exp.gX.P]
dt.ABCD[, Ci := exp.gX.L]
# Bbar_i ------------------------------------------------------------------------------------------------------
# Only the prediction part, from i=1
# k0T=0, only use i
# nothing that is before prediction start
# role of domega: d1 = partial period from Tcal to ceiling_tu(Tcal)
# d1 is same value for all customers and periods
d1 <- clv.time.interval.in.number.tu(interv = interval(start = [email protected],
end = clv.time.ceiling.date(clv.time,
timepoint = [email protected])),
clv.time = clv.time)
dt.ABCD[, d1 := d1]
dt.ABCD[, Bbar_i := exp.gX.P]
dt.ABCD[i==1, Bbar_i := exp.gX.P * d1]
# Bbar is all cov data of lower i's (previous periods) summed up - per customer!
# Cannot do cumsum(exp.gX.P) because also need to include *d1 in cumsum
dt.ABCD[, Bbar_i := cumsum(Bbar_i), by="Id"]
# Add T.cal from cbs
dt.ABCD[clv.fitted@cbs, T.cal := i.T.cal, on="Id"]
# Every last cov data needs to be calculated differently
# All i's mark the last period of 1..i and therefore need to be adapted
# Subtract cov value at i because already included in cumsum
# These adaptions are done for every i>1, unspecific to customer (ie can be done row-wise)
dt.ABCD[i > 1, Bbar_i := (Bbar_i - exp.gX.P) + exp.gX.P*(-T.cal - d1 - (i-2))]
# First also needs to be adapted
# i=1: exp.gX.P * -Tcal
dt.ABCD[i == 1, Bbar_i := exp.gX.P*(-T.cal)]
# Dbar_i ----------------------------------------------------------------------------------------------------
# Based on all cov data since the customer came alive / the cov that awoke the customer / the covariate that was active when became customer
# = also before prediction period -> Use dt.life and not just dt.ABCD
#
# A note on the notation:
# With k0T+i-1 the notation refers to the current period of Dbar_i because the last estimation period and
# first prediction period are forced to always overlap and otherwise would be counted double when
# summing k0T and i.
# For the same reason it is -3 and not -2 when adapting the last i-th cov
# k0T+i-3 hence counts the summed middle-elements
# Counting k0T is however somewhat error-prone because of the involved period definitions and
# edge-cases. Therefore, the number of middle cov periods are calculated instead by counting
# all periods since becoming alive until i and substracting 2. (ie number periods since alive - 2)
dt.Dbar <- dt.life
# Dbar is summed up lifetime cov data
dt.Dbar[, Dbar_i := exp.gX.L]
# First period when coming alive is *d_omega
# Needs to be added because not in dt.life, only in dt.ABCD
dt.Dbar[clv.fitted@cbs, d_omega := i.d_omega, on="Id"]
# min(cov.date) per Id!
dt.Dbar[, is.customers.first.cov := Cov.Date == min(Cov.Date), by="Id"]
dt.Dbar[is.customers.first.cov == TRUE, Dbar_i := exp.gX.L*d_omega]
# At every period: Sum of all previous lifetime cov data
setorderv(x = dt.Dbar, cols = "Cov.Date", order = 1)
dt.Dbar[, Dbar_i := cumsum(Dbar_i) , by="Id"]
# Every i is a "last" that needs to be adapted
# Instead of calculating the number of periods to subtract (k0T+i-3), they are counted from becoming alive
# Current covdata at i is already wrongly in Dbar_i through cumsum() therefore subtract it from Dbar_i
#
# k0T+i > 2 : * (-d.omega - (k0T+i-3))
# k0T+i <= 2: * (-d.omega)
# k0T+i <= 2: "coming alive only just in the period of estimation.end = first prediction period"
# k0T+i-3 = num.periods.alive-2 => k0T+i = num.periods.alive+1
# Count of periods alive at every point
# Still ordered by cov.date
dt.Dbar[, num.period.alive := seq.int(from = 1, to = .N), by="Id"]
# Only keep prediction period
dt.Dbar <- dt.Dbar[!is.na(i)]
# Last period adaption
dt.Dbar[, Dbar_i := (Dbar_i- exp.gX.L) + exp.gX.L*(-d_omega - (num.period.alive-2))]
# Special case: k0T+i <= 2 <=> num.periods.alive+1 <= 2 <=> "only alive 1 period": *(-d_omega) only
dt.Dbar[num.period.alive+1 <= 2, Dbar_i := (Dbar_i- exp.gX.L) + exp.gX.L*(-d_omega)]
# Write results to final results table
dt.ABCD[dt.Dbar, Dbar_i:= Dbar_i, on=c("Id", "i")]
# Return ------------------------------------------------------------------------------------
setkeyv(dt.ABCD, c("Id", "Cov.Date", "i"))
return(dt.ABCD)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_ABCD.R
|
.pnbd_dyncov_LL_BkSum <- function(data.work.trans, BkT=T){
AuxTrans <- Num.Walk <- adj.Walk1 <- d <- adj.Max.Walk <- tjk <- delta <- Id <- V1 <- NULL
#Check for BkT. If FALSE, auxilary transaction need to be removed,
# if TRUE we use all transactions inlcuding auxilary one.
if(BkT == FALSE)
data.work <- data.work.trans[AuxTrans==F]
else
data.work <- data.work.trans
# num.walk same for data.working.1 and .2
max.walk <- data.work[, max(Num.Walk)]
if( max.walk == 1 || max.walk == 2)
{
#Sum B1, Bn
Bsum <- data.work[, sum(adj.Walk1 * d, #B1
adj.Max.Walk * (tjk-d-delta*(Num.Walk-2)), #Bkn/Bjn
na.rm=T), by=Id]
}else{
# create strings of structure: "c(adj.Walk2, adj.Walk3, ..., adj.Walk(max.walk-1))"
middle.walks <- paste0("c(", paste0("adj.Walk", 2:(max.walk-1), collapse=", "), ")")
#Sum B1, B2, .., Bn
Bsum <- data.work[, sum( adj.Walk1 * d, #B1
eval(parse(text=middle.walks)), #B2,B3,..B(n-1)
adj.Max.Walk * (tjk-d-delta*(Num.Walk-2)), #Bkn/Bjn
na.rm=T), by=Id]
}
#If Bjsum is calculated not all customers might be used!
# -> merge with all customers and fill the missing ones with 0
if(BkT == F )
{
unique.customers <- unique(data.work.trans[, "Id", with=F])
if( nrow(unique.customers) != nrow(Bsum))
{
Bsum<-merge(x = unique.customers, y=Bsum, by="Id", all.x=T)
Bsum[is.na(V1), V1:=0]
}
}
#rename accordingly
if(BkT == T)
setnames(Bsum, "V1", "Bksum")
else
setnames(Bsum, "V1", "Bjsum")
return(Bsum)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_BkSum.R
|
pnbd_dyncov_CET <- function(clv.fitted, predict.number.of.periods, prediction.end.date, only.return.input.to.CET=FALSE){
i <- S <- Ai <- T.cal <- Ci <- Dbar_i <- Bbar_i <- bT_i <- DkT <- i.DkT <- Bksum <- i.Bksum <- palive <- i.palive <- NULL
i.S <- F1 <- x <- Id <- F2 <- i.F2.noS <- CET <- NULL
t <- predict.number.of.periods
r <- [email protected][["r"]]
alpha_0 <- [email protected][["alpha"]]
s <- [email protected][["s"]]
beta_0 <- [email protected][["beta"]]
clv.time <- [email protected]@clv.time
# This is d_1 in the formulas
d <- clv.time.interval.in.number.tu(clv.time=clv.time,
interv = interval(start = [email protected],
end = clv.time.ceiling.date(clv.time=clv.time,
[email protected])))
# table with A,Bbar,C,Dbar
dt.ABCD <- pnbd_dyncov_ABCD(clv.fitted = clv.fitted, prediction.end.date = prediction.end.date)
# S ------------------------------------------------------------------------------------------
# Distinguish cases depending on the number of covariates that are active during the prediction
# kTTt==1: Single expression, also save in S as it is added at the same place
# kTTt>=2: Sum of S
# kTTt is the number of active covariates from holdout.start until
# i here is the covariate number for covariates in the prediction period (seq(N) by=Id from Cov.Date>=floor(estimation.end))
# because all customers' Cov.Dates start at floor(estimation.end), their i is also the same (and at least 1)
kTTt <- dt.ABCD[, max(i)]
if(kTTt >= 2){
dt.ABCD[i == 1,
S := ((Ai*(T.cal*s + 1 / Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / ((Dbar_i+beta_0+Ci*T.cal)^s)) -
((Ai*((T.cal+d)*s + 1 / Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / (Dbar_i+beta_0+Ci*(T.cal+d))^s)]
# ** What if i == 2? Is then overwritten?
dt.ABCD[i > 1, bT_i := T.cal+d+(i-2)]
dt.ABCD[i > 1, # also do for i==max(i), subsetting to !max(i) is presumably slower
S:= ((Ai*( bT_i *s + 1/Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / (Dbar_i+beta_0+Ci* bT_i )^s) -
((Ai*((bT_i+1)*s + 1/Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / (Dbar_i+beta_0+Ci*(bT_i+1))^s)]
dt.ABCD[i == max(i),
S:= ((Ai*( bT_i *s + 1/Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / ((Dbar_i+beta_0+Ci* bT_i )^s)) -
((Ai*((T.cal+t)*s + 1/Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / ((Dbar_i+beta_0+Ci*(T.cal+t))^s))]
}else{
dt.ABCD[i == 1,
S := ((Ai*(T.cal *s + 1 / Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / ((Dbar_i+beta_0+Ci* T.cal )^s)) -
((Ai*((T.cal+t)*s + 1 / Ci*(Dbar_i+beta_0)) + Bbar_i*(s-1)) / ( Dbar_i+beta_0+Ci*(T.cal+t))^s)]
}
# To test correctness of intermediate results
if(only.return.input.to.CET){
return(dt.ABCD)
}
dt.S <- dt.ABCD[, list(S = sum(S)), keyby="Id"]
# PAlive ------------------------------------------------------------------------------------------
dt.palive <- pnbd_dyncov_palive(clv.fitted=clv.fitted)
# CET ---------------------------------------------------------------------------------------------
# Merge data in single table by Id
dt.result <- clv.fitted@cbs[, c("Id","x", "t.x", "T.cal")]
dt.result[[email protected], DkT := i.DkT, on="Id"]
dt.result[[email protected], Bksum := i.Bksum, on="Id"]
dt.result[dt.palive, palive := i.palive, on="Id"]
dt.result[dt.S, S := i.S, on="Id"]
# F1
# Bksum has BkT correctly included
dt.result[, F1 := ((r+x) * (beta_0+DkT)^s) / ((Bksum + alpha_0) * (s-1))]
# F2
dt.F2.noS <- dt.ABCD[i == max(i), list(Id, F2.noS = ((Bbar_i + Ai*(T.cal+t) )*(s-1)) / (Dbar_i + Ci*(T.cal+t) + beta_0)^s)]
# S is different for kTTt==1 and kTTt>=2
dt.result[dt.F2.noS, F2 := i.F2.noS + S, on = "Id"]
dt.result[, CET := palive * F1 * F2]
return(dt.result)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_CET.R
|
# Note that for a constant prediction period, the difference between DECT and DERT increases as the discount factor decreases.
pnbd_dyncov_DECT <- function(clv.fitted, predict.number.of.periods, prediction.end.date, continuous.discount.factor){
# cran silence
i.S <- bT_i <- T.cal <- d1 <- i <- param.s <- d1 <- delta <- Ci <- Dbar_i <- palive <- i.palive <- F1 <- S <- DECT <- NULL
Ai <- Dbar_i <- i.DkT <- BkSum <- i.BkSum <- x <- DkT <- Bksum <- i.Bksum <- NULL
clv.time <- [email protected]@clv.time
# delta is the discount rate \Delta in derivations.
delta <- continuous.discount.factor
t <- predict.number.of.periods
r <- [email protected]["r"]
alpha_0 <- [email protected]["alpha"]
s <- [email protected]["s"]
beta_0 <- [email protected]["beta"]
# This is d_1 in the formulas
d <- clv.time.interval.in.number.tu(clv.time=clv.time,
interv = interval(start = [email protected],
end = clv.time.ceiling.date(clv.time = clv.time,
timepoint = [email protected])))
# S ---------------------------------------------------------------------------------------------------------
dt.ABCD <- pnbd_dyncov_ABCD(clv.fitted = clv.fitted, prediction.end.date = prediction.end.date)
dt.ABCD[, param.s := s] # add s as vector to pass to vec_hyper2f0 function that relies on vectors
dt.ABCD[, bT_i := T.cal + d1 + (i-2)]
dt.ABCD[i==1,
S := ( .f_confhypergeo_secondkind(param.s, param.s, (delta*(Ci*T.cal + Dbar_i + beta_0))/Ci)) -
(exp(-delta*d1) * .f_confhypergeo_secondkind(param.s, param.s, (delta*(Ci*(T.cal+d1) + Dbar_i + beta_0))/Ci))]
dt.ABCD[i>1 & i!= max(i),
S := ( exp(-delta*(d1+i-2)) * .f_confhypergeo_secondkind(param.s,param.s, (delta*(Ci* bT_i +Dbar_i+beta_0)) / Ci)) -
(exp(-delta*(d1+i-1)) * .f_confhypergeo_secondkind(param.s,param.s, (delta*(Ci*(bT_i+1)+Dbar_i+beta_0)) / Ci))]
# T = T.cal
# T2 = T.cal + t
# T2-T = t
# ***TODO: Is t == max(i) really the same. It can often then result in negative expressions ***
dt.ABCD[i== max(i),
S := (exp(-delta*(d1+i-2)) * .f_confhypergeo_secondkind(param.s, param.s, (delta * (Ci*bT_i + Dbar_i + beta_0)) / Ci)) -
(exp(-delta*(t)) * .f_confhypergeo_secondkind(param.s, param.s, (delta * (Ci*(T.cal+t) + Dbar_i + beta_0)) / Ci))]
dt.ABCD[, S := S * (Ai / (Ci^s))]
dt.S <- dt.ABCD[, list(S = sum(S)), keyby="Id"]
# Aggregate results ------------------------------------------------------------------------------------------------
dt.result <- clv.fitted@cbs[, c("Id", "x")]
dt.result[[email protected], DkT := i.DkT, on="Id"]
dt.result[[email protected], Bksum := i.Bksum, on="Id"]
dt.palive <- pnbd_dyncov_palive(clv.fitted = clv.fitted)
dt.result[dt.palive, palive := i.palive, on = "Id"]
dt.result[, F1 := delta^(s-1) * ((r+x)* (beta_0+DkT)^s) / (Bksum + alpha_0)]
dt.result[dt.S, S := i.S, on = "Id"]
dt.result[, DECT := palive * F1 * S]
setkeyv(dt.result, "Id")
return(dt.result)
}
# The confluent hypergeometric function of the second kind as defined on:
# http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheSecondKind.html
.f_confhypergeo_secondkind <- function (a, b, z)
{
# Verified for a number of parameters to yield the same results as Wolfram's HypergeometricU[] and Matlab's kummerU().
return(Re(z^(-a)* vec_gsl_hyp2f0_e(vA = a, vB = 1 + a - b, vZ = -z^(-1))$value))
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_DECT.R
|
pnbd_dyncov_assert_walk_assumptions <- function(clv.fitted){
abs_pos <- walk_id <- walk_from <- walk_to <- num_walks <- Id <- tp.cov.lower <- tp.this.trans <- NULL
first_cov_real <- i.first_cov_real <- first_cov_aux <- first_cov_real <- NULL
i.date.first.actual.trans <- x <- tjk <- d_omega <- d1 <- first_trans <- NULL
assert_ret <- tryCatch(expr = {
# All walks:
# keys: Id, walk_id, tp.this.trans, tp.cov.lower (and therefore also sorted)
# sorted, increasing:
# strictly monotonic: abs_pos
# monotonic: walk_id, walk_from, walk_to
assert_allwalks <- function(dt.walks){
# coreelements
stopifnot(setequal(key(dt.walks), c("Id", "walk_id", "tp.this.trans", "tp.cov.lower")))
stopifnot(dt.walks[, !is.unsorted(abs_pos, strictly = TRUE)])
stopifnot(dt.walks[, !is.unsorted(walk_id, strictly = FALSE)])
stopifnot(dt.walks[, !is.unsorted(walk_from, strictly = FALSE)])
stopifnot(dt.walks[, !is.unsorted(walk_to, strictly = FALSE)])
stopifnot(!anyNA(dt.walks))
# backwards looking from second transaction
stopifnot(dt.walks[tp.this.trans < tp.cov.lower, .N] == 0)
}
assert_allwalks([email protected])
assert_allwalks([email protected])
assert_allwalks([email protected])
assert_allwalks([email protected])
# all aux walks:
# every Id only once
# every Id in walks
# same length per customer
stopifnot([email protected][, list(num_walks = uniqueN(walk_id)), by="Id"][, all(num_walks==1)])
stopifnot([email protected][, uniqueN(Id)] == nobs(clv.fitted))
stopifnot(setequal([email protected][, unique(Id)], clv.fitted@cbs$Id))
stopifnot([email protected][, list(num_walks = uniqueN(walk_id)), by="Id"][, all(num_walks==1)])
stopifnot([email protected][, uniqueN(Id)] == nobs(clv.fitted))
stopifnot(setequal([email protected][, unique(Id)], clv.fitted@cbs$Id))
stopifnot(identical([email protected][, .N, keyby="Id"],
[email protected][, .N, keyby="Id"]))
# lifetime aux walk:
# no date overlap with real lifetime walks
dt.tmp <- [email protected][, list(first_cov_aux = min(tp.cov.lower)), keyby="Id"]
dt.tmp[[email protected][, list(first_cov_real = min(tp.cov.lower)) , keyby="Id"], first_cov_real := i.first_cov_real, on="Id"]
# some first_cov_real are NA because have no real walk
stopifnot(dt.tmp[first_cov_aux < first_cov_real, .N] == 0)
# lifetime real walk:
# exactly 1 walk per customer
# all ids except where aux walk reaches to the first transactions (coming alive)
# (number of customers = num customers in trans real walks where .N>1)
# n real walk + n aux walk >= ceiling(Tcal)
stopifnot([email protected][, list(num_walks=uniqueN(walk_id)), keyby="Id"][, all(num_walks == 1)])
# dt.tmp[[email protected]@data.transactions[, list(last_trans = max(Date)), by="Id"], last_trans := i.last_trans, on="Id"]
dt.tmp[clv.fitted@cbs, first_trans := i.date.first.actual.trans, on="Id"]
stopifnot(setequal([email protected][, unique(Id)],
dt.tmp[first_cov_aux > first_trans, Id]))
# trans real walks:
# every Id with x>0 is in ...
# ... with x-1 walks
stopifnot(setequal([email protected][, unique(Id)], clv.fitted@cbs[x>0, Id]))
stopifnot(identical([email protected][, list(num_walks=as.double(uniqueN(walk_id))), keyby="Id"],
clv.fitted@cbs[x>0, list(num_walks=as.double(x)), keyby="Id"]))
# trans walks
# tjk >= 0 (== 0 when t.x=T)
stopifnot([email protected][tjk < 0, .N] == 0)
stopifnot([email protected][tjk < 0, .N] == 0)
# d1 and d_omega measures are in (0,1]
stopifnot(clv.fitted@cbs[, all(d_omega > 0 & d_omega <= 1)])
stopifnot([email protected][, all(d1 > 0 & d1 <= 1)])
stopifnot([email protected][, all(d1 > 0 & d1 <= 1)])
},
error = function(e){return(e)})
if(is(assert_ret, "error")){
message("Caught the following error, please report issue on Github: \n", assert_ret)
stop("Abort")
}
}
pnbd_dyncov_getLLcallargs <-function(clv.fitted){
i.walk_from <- i.walk_to <- i.d <- i.tjk <- NULL
walkinfo_trans_real_from <- walkinfo_trans_real_to <- i.id_from <- i.id_to <- NULL
pnbd_dyncov_assert_walk_assumptions(clv.fitted)
pnbd_dyncov_addwalkinfo_single <- function(dt.cbs, dt.walk, name, cols.walkinfo){
dt.walkinfo <- unique(dt.walk[, .SD, .SDcols=cols.walkinfo])
for(wi in setdiff(cols.walkinfo, "Id")){
col.name <- paste0("walk_",name,"_", gsub("_", "", gsub("walk", "", wi)))
dt.cbs[dt.walkinfo, (col.name) := get(paste0("i.", wi)), on="Id"]
}
return(dt.cbs)
}
# Add where to find customer's walk info
cols.wi.life <- c("Id", "walk_from", "walk_to")
cols.wi.trans <- c(cols.wi.life, "tjk", "d1")
dt.cbs <- copy(clv.fitted@cbs)
dt.cbs <- pnbd_dyncov_addwalkinfo_single(dt.cbs, [email protected], name="aux_life", cols.walkinfo = cols.wi.life)
dt.cbs <- pnbd_dyncov_addwalkinfo_single(dt.cbs, [email protected], name="real_life", cols.walkinfo = cols.wi.life)
dt.cbs <- pnbd_dyncov_addwalkinfo_single(dt.cbs, [email protected], name="aux_trans", cols.walkinfo = cols.wi.trans)
# Add to cbs
# zero-repeaters have no real trans walks and will have NA in walkinfo_trans_real_from/to
# which are skipped in the cpp implementation
# dt.customerinfo: where in walkinfo matrix to find customer's walk info
dt.walkinfo.real.trans <- pnbd_dyncov_getrealtranswalks_walkinfo([email protected])
dt.customerinfo.real.trans <- unique(dt.walkinfo.real.trans[, c("Id", "id_from", "id_to")])
dt.cbs[dt.customerinfo.real.trans, walkinfo_trans_real_from := i.id_from, on="Id"]
dt.cbs[dt.customerinfo.real.trans, walkinfo_trans_real_to := i.id_to, on="Id"]
# IN SAME ORDER AS READ OUT IN WALK constructor
cols.walk.ordered.life <- c("from", "to")
cols.walk.ordered.trans <- c(cols.walk.ordered.life, "d1", "tjk")
m.walkinfo.aux.life <- data.matrix(dt.cbs[, .SD, .SDcols=paste0("walk_aux_life_", cols.walk.ordered.life, sep="")])
m.walkinfo.real.life <- data.matrix(dt.cbs[, .SD, .SDcols=paste0("walk_real_life_", cols.walk.ordered.life, sep="")])
m.walkinfo.aux.trans <- data.matrix(dt.cbs[, .SD, .SDcols=paste0("walk_aux_trans_", cols.walk.ordered.trans, sep="")])
m.walkinfo.real.trans <- data.matrix(dt.walkinfo.real.trans[, c("walk_from", "walk_to", "d1", "tjk")])
# check col sorting is same as parameters!
stopifnot(names([email protected]) == [email protected]@names.cov.data.life)
stopifnot(names([email protected]) == [email protected]@names.cov.data.trans)
m.cov.data.aux.life <- data.matrix([email protected][, .SD, [email protected]@names.cov.data.life])
m.cov.data.real.life <- data.matrix([email protected][, .SD, [email protected]@names.cov.data.life])
m.cov.data.aux.trans <- data.matrix([email protected][, .SD, [email protected]@names.cov.data.trans])
m.cov.data.real.trans <- data.matrix([email protected][, .SD, [email protected]@names.cov.data.trans])
return(list(X = dt.cbs$x,
t_x = dt.cbs$t.x,
T_cal = dt.cbs$T.cal,
d_omega = dt.cbs$d_omega,
walkinfo_aux_life = m.walkinfo.aux.life,
walkinfo_real_life = m.walkinfo.real.life,
walkinfo_aux_trans = m.walkinfo.aux.trans,
walkinfo_trans_real_from = dt.cbs$walkinfo_trans_real_from,
walkinfo_trans_real_to = dt.cbs$walkinfo_trans_real_to,
walkinfo_real_trans = m.walkinfo.real.trans,
covdata_aux_life = m.cov.data.aux.life,
covdata_real_life = m.cov.data.real.life,
covdata_aux_trans = m.cov.data.aux.trans,
covdata_real_trans = m.cov.data.real.trans))
}
pnbd_dyncov_getLLdata <- function(clv.fitted, params){
# get LL with all values, not just ind LL or summed LL
l.LL.args <- pnbd_dyncov_getLLcallargs(clv.fitted)
l.LL.args[["params"]] <- params
l.LL.args[["return_intermediate_results"]] <- TRUE
# DATA HAS TO BE SAME ORDER AS PARAMS
stopifnot(all(names(params) ==
c([email protected]@names.prefixed.params.model,
[email protected],
[email protected])))
dt.LLdata <- data.table(Id = clv.fitted@cbs$Id,
do.call(what = pnbd_dyncov_LL_ind, args = l.LL.args),
key = "Id")
setnames(dt.LLdata, "F2", "Z")
return(dt.LLdata)
}
pnbd_dyncov_creatwalks_add_tjk <- function(dt.walk, clv.time){
tjk <- tp.previous.trans <- tp.this.trans <- NULL
# time between Trans and the previous Trans / from date.lagged to date
dt.walk[, tjk := clv.time.interval.in.number.tu(clv.time = clv.time,
interv = interval( start = tp.previous.trans,
end = tp.this.trans))]
return(dt.walk)
}
pnbd_dyncov_createwalks_add_corelements <- function(dt.walks){
walk_id <- abs_pos <- walk_from <- walk_to <- NULL
# Add elements shared by all walks: walk_id, abs_pos, walk_from, walk_to
# Do at single point to ensure sorting guarantees
# Add walk ids:
# Does not require sorting, only marks what belongs together
dt.walks[, walk_id := .GRP, by=c("Id", "tp.this.trans")]
# Sort walks:
# For each customer, walks in chronological order, actual data in walk in chronological order:
# Id, tp transaction, tp.cov.lower
# For completeness also add walk_id as key
setkeyv(dt.walks, c("Id", "tp.this.trans", "tp.cov.lower", "walk_id"))
# absolute position in data
dt.walks[, abs_pos := seq(.N)]
# walk_from/to: Start and end position in data of each walk
# min() and max() give warning if table is empty (if there is not a single real lifetime walk)
if(nrow(dt.walks) > 0){
# Add from to of walk
dt.walks[, walk_from := min(abs_pos), by="walk_id"]
dt.walks[, walk_to := max(abs_pos), by="walk_id"]
}else{
dt.walks[, walk_from := numeric(0)]
dt.walks[, walk_to := numeric(0)]
}
return(dt.walks)
}
pnbd_dyncov_walk_d <- function(clv.time, tp.relevant.transaction){
# . d ---------------------------------------------------------------------
# d shall be 1 if it is exactly on the time unit lower boundary
# see comments on d_ in #205
# lubridate::ceiling_date() has the argument change_on_boundary since Version 1.5.6 (2016-04-06)
# this makes +1 of previous implementations obsolete
return(clv.time.interval.in.number.tu(clv.time=clv.time,
interv = interval(start = tp.relevant.transaction,
end = clv.time.ceiling.date(clv.time=clv.time,
timepoint=tp.relevant.transaction))))
}
pnbd_dyncov_creatwalks_add_d1 <- function(dt.walk, clv.time){
d1 <- tp.previous.trans <- NULL
# d1
# "For any two successive transactions (j − 1), j, this is the time of the
# transaction (j-1) to the end of the first interval"
#
# Number of periods between walk's first transaction and the end of the cov interval it is in
dt.walk[, d1 := pnbd_dyncov_walk_d(clv.time=clv.time, tp.relevant.transaction=tp.previous.trans)]
return(dt.walk)
}
pnbd_dyncov_creatwalks_matchcovstocuts <- function(dt.cov, dt.cuts, names.cov){
# Match the cov data to the points given in dt.cuts
by.covs <- c("Id", "tp.cov.lower", "tp.cov.upper")
by.cuts <- c("Id", "tp.cut.lower", "tp.cut.upper")
setkeyv(dt.cov, by.covs)
setkeyv(dt.cuts, by.cuts)
dt.matched <- foverlaps(x = dt.cuts, y = dt.cov, by.x = by.cuts, by.y = by.covs,
type="any", mult="all", nomatch = NULL)
return(dt.matched)
}
pnbd_dyncov_createwalks_singletrans <- function(dt.cov, dt.tp.first.last,
name.lower, name.upper,
names.cov, clv.time){
# Create the walks for a given single transaction of customers
# walk includes: id, abs_pos, from, to
tp.cut.lower <- tp.cut.upper <- tp.this.trans <- tp.previous.trans <- NULL
dt.cuts <- copy(dt.tp.first.last)
dt.cuts[, tp.cut.lower := get(name.lower)]
# dt.cuts[, tp.cut.lower := get(name.lower) + clv.time.epsilon(clv.time)]
dt.cuts[, tp.cut.upper := get(name.upper)]
dt.cuts[get(name.lower) == get(name.upper), tp.cut.lower := get(name.lower)]
dt.walks <- pnbd_dyncov_creatwalks_matchcovstocuts(dt.cov = dt.cov, dt.cuts = dt.cuts,
names.cov = names.cov)
dt.walks[, tp.this.trans := get(name.upper)]
dt.walks[, tp.previous.trans := get(name.lower)]
dt.walks <- pnbd_dyncov_createwalks_add_corelements(dt.walks)
return(dt.walks)
}
pnbd_dyncov_covariate_add_interval_bounds <- function(dt.cov, clv.time){
tp.cov.lower <- tp.cov.upper <- Cov.Date <- NULL
# Covariate intervals are closed intervals + Cov.Date marks beginning (Covs are "forward-looking")
# => [Cov.Date, Next Cov.Date - eps] <=> [Cov.Date, Cov.Date + 1 Period - eps]
dt.cov[, tp.cov.lower := Cov.Date]
# Do not use shift() because leaves NA which will then have to be fixed
# has a test which verifies that same result as if shifting
single.timeperiod <- clv.time.number.timeunits.to.timeperiod(clv.time, user.number.periods=1L)
dt.cov[, tp.cov.upper := tp.cov.lower + single.timeperiod - clv.time.epsilon(clv.time)]
return(dt.cov)
}
pnbd_dyncov_createwalks_real_trans <- function(clv.data, dt.trans, dt.tp.first.last){
num.trans <- tp.this.trans <- tp.previous.trans <- tp.cut.lower <- tp.cut.upper <- is.first <- Date <- NULL
clv.time <- [email protected]
dt.cov <- [email protected]
# Covariates affecting repeat-transactions
# Zero-repeaters have no real walks
# No walk for the first transaction
# A transaction is influenced some time between the last and actual trans
# -> Interval [last trans + eps, this trans]
# remove zero-repeaters
dt.cuts.real <- dt.trans[dt.tp.first.last[num.trans > 1, "Id"], on="Id", nomatch=NULL]
dt.tp.first.last[, num.trans := NULL]
# If 2 transactions are on the same date, shift+1 will lead to Date.Start > Date.End
# Cannot/Should have no 2 transactions on same tp because are aggregated
# No aux trans, only real trans present and therefore there is no aux trans on T (no distance between transactions) in this data
# min dist between transactions is 1 eps, hence tp.cut.lower and tp.cut.upper can fall together when shifting. Although the length of this interval is 0,
# foverlaps() matches these to covariates and produces walks of length 1
setkeyv(dt.cuts.real, cols=c("Id", "Date"))
dt.cuts.real[, tp.this.trans := Date]
dt.cuts.real[, tp.previous.trans := shift(tp.this.trans, n=1), by="Id"]
# walk is [t_j, t_k] and not [t_j+eps, t_k]
# dt.cuts.real[, tp.cut.lower := tp.previous.trans + clv.time.epsilon(clv.time)] # if we add + eps, lower > upper if they are only 1 eps apart (because we also shift)
dt.cuts.real[, tp.cut.lower := tp.previous.trans]
dt.cuts.real[, tp.cut.upper := tp.this.trans]
# remove cut for first transaction
# - which has NA in tp.previous.trans because of shift()ing (and then cannot match to cov anyway)
# - for which no walk shall be created
# dt.cuts.real <- dt.cuts.real[!is.na(tp.previous.trans)]
# May be empty if there are no real trans walks (all zero-repeaters)
if(nrow(dt.cuts.real) > 0){
dt.cuts.real[, is.first := tp.this.trans == min(tp.this.trans), by="Id"]
}else{
dt.cuts.real[, is.first := logical(0), by="Id"]
}
dt.cuts.real <- dt.cuts.real[is.first == FALSE]
dt.cuts.real[, is.first := NULL]
dt.walks.real <- pnbd_dyncov_creatwalks_matchcovstocuts(dt.cov = dt.cov,
dt.cuts = dt.cuts.real,
names.cov = clv.data.get.names.cov.trans(clv.data))
dt.walks.real <- pnbd_dyncov_createwalks_add_corelements(dt.walks.real)
dt.walks.real <- pnbd_dyncov_creatwalks_add_tjk(dt.walks.real, clv.time)
dt.walks.real <- pnbd_dyncov_creatwalks_add_d1(dt.walks.real, clv.time)
return(dt.walks.real)
}
pnbd_dyncov_createwalks_real_life <- function(clv.data, dt.tp.first.last, dt.walks.aux.life){
tp.first.aux.cov.lower <- i.tp.first.aux.cov.lower <- tp.cov.lower <- Cov.Date <- NULL
# Real walks for the lifetime process are all covs before the one covariate where the last transaction happens in
# Given the aux walk, they are the residual covs since coming alive
# May have no overlap with the aux walk
# Only ever needed in Di() where they are summed additionally to the aux walk
# For some customers, there might be no real walk, if the aux walk starts in the customer's first period
# Still, every customer may have 1 real walk at maximum
# Create from residuals given the aux walks
# Eligible covs:
# Per customer: Only transactions before the ones in aux walks (strict <)
# using non-equi join requires minimum data.table version 1.9.8!
dt.tp.first.aux <- dt.walks.aux.life[, list(tp.first.aux.cov.lower = min(tp.cov.lower)), keyby="Id"]
dt.cov <- [email protected][dt.tp.first.aux, nomatch=NULL,
on=c("Id==Id", "tp.cov.lower < tp.first.aux.cov.lower")]
# Subset with join adds/sets tp.cov.lower=tp.first.aux.cov.lower: Overwrite with correct Cov.Date
dt.cov[, tp.cov.lower := Cov.Date]
# Alternative:
# dt.cov <- copy([email protected])
# dt.cov[dt.tp.first.aux, tp.first.aux.cov.lower := i.tp.first.aux.cov.lower, on="Id"]
# dt.cov[, is.before.first.aux := tp.cov.lower < tp.first.aux.cov.lower]
# dt.cov <- dt.cov[is.before.first.aux == TRUE]
# dt.cov[, is.before.first.aux := NULL]
# dt.cov[, tp.first.aux.cov.lower := NULL]
# Create walk table only with eligible covariates
dt.walks.real <- pnbd_dyncov_createwalks_singletrans(dt.cov=dt.cov,
dt.tp.first.last=dt.tp.first.last,
name.lower="tp.first.trans",
name.upper="tp.last.trans",
names.cov=clv.data.get.names.cov.life(clv.data),
[email protected])
return(dt.walks.real)
}
pnbd_dyncov_createwalks_auxwalk <- function(dt.cov, dt.tp.first.last, names.cov, clv.time){
tp.estimation.end <- NULL
dt.tp.first.last[, tp.estimation.end := [email protected]]
dt.walks.aux <- pnbd_dyncov_createwalks_singletrans(dt.cov=dt.cov,
dt.tp.first.last=dt.tp.first.last,
name.lower="tp.last.trans",
name.upper="tp.estimation.end",
names.cov = names.cov,
clv.time=clv.time)
dt.walks.aux[, tp.estimation.end := NULL]
return(dt.walks.aux)
}
pnbd_dyncov_createwalks <- function(clv.data){
walk_id <- walk_from <- walk_to <- .N <- abs_pos <- Date <- tp.cov.lower <- NULL
# Walk info, per walk
# - from, to: where to find walk data
# Transaction:
# - tjk
# - d1
# d_omega is per customer
# Extract transactions and first/last for all walk types & processes because
# may be memory and computation intensive
dt.trans <- clv.data.get.transactions.in.estimation.period(clv.data)
dt.tp.first.last <- dt.trans[, list(tp.first.trans = min(Date),
tp.last.trans = max(Date),
num.trans = .N),
by="Id"]
names.cov.trans <- clv.data.get.names.cov.trans(clv.data)
names.cov.life <- clv.data.get.names.cov.life(clv.data)
dt.walks.aux.life <- pnbd_dyncov_createwalks_auxwalk(dt.cov = [email protected],
dt.tp.first.last=dt.tp.first.last,
names.cov=names.cov.life,
[email protected])
dt.walks.real.life <- pnbd_dyncov_createwalks_real_life(clv.data=clv.data,
dt.tp.first.last=dt.tp.first.last,
dt.walks.aux.life=dt.walks.aux.life)
dt.walks.real.trans <- pnbd_dyncov_createwalks_real_trans(clv.data,
dt.trans=dt.trans,
dt.tp.first.last=dt.tp.first.last)
dt.walks.aux.trans <- pnbd_dyncov_createwalks_auxwalk([email protected],
dt.tp.first.last=dt.tp.first.last,
names.cov=names.cov.trans,
[email protected])
dt.walks.aux.trans <- pnbd_dyncov_creatwalks_add_tjk(dt.walks.aux.trans, clv.time = [email protected])
dt.walks.aux.trans <- pnbd_dyncov_creatwalks_add_d1(dt.walks.aux.trans, clv.time = [email protected])
# Create actual walk tables ------------------------------------------------------------
cols.common <- c("abs_pos", "Id", "tp.this.trans", "walk_id", "tp.cov.lower", "tp.cov.upper", "walk_from", "walk_to")
cols.life <- c(cols.common, names.cov.life)
cols.trans <- c(cols.common, names.cov.trans, "tjk", "d1")
return(list("data.walks.life.aux" = dt.walks.aux.life[, .SD, .SDcols=cols.life],
"data.walks.life.real" = dt.walks.real.life[, .SD, .SDcols=cols.life],
"data.walks.trans.aux" = dt.walks.aux.trans[, .SD, .SDcols=cols.trans],
"data.walks.trans.real" = dt.walks.real.trans[, .SD, .SDcols=cols.trans]))
}
pnbd_dyncov_getrealtranswalks_walkinfo <- function(dt.walk){
abs_pos <- Id <- id_from <- id_to <- NULL
# minimum info, per walk. Keep Id to create customerinfo (match with cbs)
dt.walkinfo <- unique(dt.walk[, c("Id", "walk_from", "walk_to", "tjk", "d1")])
setkeyv(dt.walkinfo, "Id")
# Add abs_pos + id from and to here to ensure correct
# abs_pos requires sorting by id to ensure all walkinfo of same id is together
dt.walkinfo[order(Id), abs_pos := seq(.N)]
dt.walkinfo[, id_from := min(abs_pos), by="Id"]
dt.walkinfo[, id_to := max(abs_pos), by="Id"]
return(dt.walkinfo)
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_createwalks.R
|
#' @importFrom utils txtProgressBar setTxtProgressBar
pnbd_dyncov_expectation <- function(clv.fitted, dt.expectation.seq, verbose, only.return.input.to.expectation=FALSE){
# cran silence
expectation <- exp.gX.P <- i.exp.gX.P <- exp.gX.L <- d_omega <- i.d_omega <- NULL
i <- Ai <- Bi <- Ci <- Di <- Dbar_i <- Bbar_i <- period.num <- d1 <- NULL
tp.last.period.end <- dt.expectation.seq[, max(period.until)]
max.period.no <- dt.expectation.seq[, max(period.num)]
if(max.period.no <=2)
stop("Have to plot at least 3 periods!", call. = FALSE)
# For more readable code
clv.time <- [email protected]@clv.time
# Create ABCD ---------------------------------------------------------------------------------------------
# Calculate Ai, Bbar_i, Ci, Dbar_i
# i is per customer, since when coming alive
# i=1 in period when customer turns alive
# Upper max cov period is where the last expectation date lies in
# If max(dates.periods) falls directly onto the start of a covariate,
# the covariate is active then and is included as well.
# => max cov: floor_tu(max(dates.periods))
date.last.cov <- clv.time.floor.date(clv.time=clv.time, timepoint=tp.last.period.end)
l.covs <- pnbd_dyncov_alivecovariates(clv.fitted = clv.fitted, date.upper.cov = date.last.cov)
dt.trans <- l.covs[["dt.trans"]]
dt.life <- l.covs[["dt.life"]]
# Merge into single table
dt.ABCD <- dt.life[, c("Id", "Cov.Date", "exp.gX.L")]
setkeyv(dt.ABCD, cols = c("Id", "Cov.Date"))
dt.ABCD[dt.trans, exp.gX.P := i.exp.gX.P, on = c("Id", "Cov.Date")]
# . i --------------------------------------------------------------------------------------------------------
# Number of active covariates since customer came alive
# = relative to when alive
# First is the one which was active when the customer had its first transaction
# The data is already cut to only these dates when a customer was alive
# Order with smallest Cov.Date up
# Needed here and in all following parts
setorderv(dt.ABCD, cols = "Cov.Date", order=1L)
# Add i per customer
dt.ABCD[, i := seq.int(from = 1, to = .N), by="Id"]
# Add data needed in Dbar_i and Bbar_i
dt.ABCD[clv.fitted@cbs, d_omega := i.d_omega, on="Id"]
# . Ai & Ci ---------------------------------------------------------------------------------------------------
# They are both simply the gamma*cov values in the prediction period, for all Ids and dates
dt.ABCD[, Ai := exp.gX.P]
dt.ABCD[, Ci := exp.gX.L]
# . Bbar_i ----------------------------------------------------------------------------------------------------
# d1: For this case here d1 = d_omega
dt.ABCD[, d1 := d_omega]
dt.ABCD[, Bbar_i := exp.gX.P]
dt.ABCD[i == 1, Bbar_i := exp.gX.P * d1]
# Already ordered when creating dt.ABCD
dt.ABCD[, Bbar_i := cumsum(Bbar_i), by="Id"]
# At i, exp.gX.P_i is already contained through cumsum.
# Therefore subtract again
# i=1: Bbar_i = 0 because (Bbar_i - exp.gX.P) + exp.gX.P * (-d1)
dt.ABCD[, Bbar_i := (Bbar_i - exp.gX.P) + exp.gX.P * (-d1 - (i-2))]
dt.ABCD[i == 1, Bbar_i := 0]
# . Dbar_i ----------------------------------------------------------------------------------------------------
dt.ABCD[, Dbar_i := exp.gX.L]
dt.ABCD[i == 1, Dbar_i := exp.gX.L*d_omega]
dt.ABCD[, Dbar_i := cumsum(Dbar_i), by="Id"]
# i=1: Dbar_i = 0 because (Dbar_i - exp.gX.L) + exp.gX.L * (-d_omega)]
dt.ABCD[ , Dbar_i := (Dbar_i - exp.gX.L) + exp.gX.L * (-d_omega - (i-2))]
dt.ABCD[i == 1, Dbar_i := 0]
if(only.return.input.to.expectation){
return(dt.ABCD)
}
# Do expectation -----------------------------------------------------------------------------------------------
# For every date in the expectation table, calculate the expectation separately
if(verbose){
progress.bar <- txtProgressBar(max = max.period.no, style = 3)
update.pb <- function(n){setTxtProgressBar(pb=progress.bar, value = n)}
}
# For every period, do unconditional expectation (sumF)
# Do for loop because more expressive than doing by="period.num" in table
for(p.no in dt.expectation.seq$period.num){
period.until <- dt.expectation.seq[period.num == p.no, period.until]
expectation_i <- .pnbd_dyncov_unconditionalexpectation(clv.fitted = clv.fitted,
dt.ABCD = dt.ABCD,
period.until = period.until)
dt.expectation.seq[period.num == p.no, expectation := expectation_i]
if(verbose)
update.pb(p.no)
}
# Cumulative to incremental --------------------------------------------------------------------------
# First entry is already correct, because cumulative = incremental there, and cannot be
# infered using "diff". Therefore let first entry as is, rest is diff
dt.expectation.seq[order(period.num, decreasing = FALSE), expectation := c(0, diff(expectation))]
return(dt.expectation.seq)
}
# **** JEFF: t = TUs from alive until date.expectation.period.start oder date.expectation.period.end?
# **** JEFF: cut: At date.expectation.period.start oder date.expectation.period.end?
.pnbd_dyncov_unconditionalexpectation <- function(clv.fitted, dt.ABCD, period.until){
# cran silence
i <- Ai <- Bbar_i <- Ci <- Dbar_i <- d1 <-S <- i.S <- f <- A_k0t <- Bbar_k0t <- C_k0t <- Dbar_k0t <- Id <- NULL
num.periods.alive.expectation.date <- i.num.periods.alive.expectation.date <- date.first.actual.trans <- Cov.Date <- only.alive.in.1.period <- NULL
# Read out needed params
r <- [email protected][["r"]]
alpha_0 <- [email protected][["alpha"]]
s <- [email protected][["s"]]
beta_0 <- [email protected][["beta"]]
# More readable code
clv.time <- [email protected]@clv.time
# Prepare dt.ABCD -------------------------------------------------------------------------------------
# Only alive customers
# consider only customers alive already at expectation date
# According to Jeff's email: (0, t_i], ie <=
dt.alive.customers <- clv.fitted@cbs[date.first.actual.trans <= period.until,
c("Id", "date.first.actual.trans")]
# Keep only who is alive already at period.until
dt.ABCD.alive <- dt.ABCD[dt.alive.customers, on="Id", nomatch = NULL]
# Exact time from coming alive until end of expectation period
dt.alive.customers[, num.periods.alive.expectation.date :=
clv.time.interval.in.number.tu(clv.time=clv.time,
interv=interval(start = date.first.actual.trans,
end = period.until))]
# Add to every cov period
dt.ABCD.alive[dt.alive.customers, num.periods.alive.expectation.date := i.num.periods.alive.expectation.date,
on = "Id"]
# Cut data to maximal range
# Consider all covariates which are active before and during the period for which the expectation is
# calculated (incl / <= because period.until is the beginning of the covariate period)
dt.ABCD.alive <- dt.ABCD.alive[Cov.Date <= period.until]
# S --------------------------------------------------------------------------------------------------------
# S_i is relative to when alive, ie by i
# d1 is first.purchase until ceiling_tu(first.purchase) = d_omega
# Already added for Bbar_i
# helper to calculate S value by:
# s.fct.expectation(term.1) - s.fct.expectation(term.2)
# A = Ai, B = Bbar_i, C = Ci, D = Dbar_i
s.fct.expectation <- function(term, A, B, C, D, beta_0, s){
return( (A * (term * s + 1/C * (beta_0+D)) + B*(s-1)) / (beta_0 + D + C * term)^s )
}
# term 1 = 0 (yes!), term 2 = d
dt.ABCD.alive[i==1,
S:= s.fct.expectation(term = 0, A=Ai, B=Bbar_i,C=Ci,D=Dbar_i,beta_0=beta_0,s=s) -
s.fct.expectation(term = d1, A=Ai, B=Bbar_i,C=Ci,D=Dbar_i,beta_0=beta_0,s=s)]
dt.ABCD.alive[i>1,
S:= s.fct.expectation(term = (d1 + i - 2), A=Ai, B=Bbar_i, C=Ci, D=Dbar_i, beta_0=beta_0, s=s) -
s.fct.expectation(term = (d1 + i - 1), A=Ai, B=Bbar_i, C=Ci, D=Dbar_i, beta_0=beta_0, s=s)]
# Last = max(i) is per customer, but only after cutting to expectation date!
# After cutting to expectation date, all have the same max date!
# **JEFF: Wird davon ausgegangen, dass num.periods.alive.expectation.date > i ist?
# **JEFF: For first period d1+i-2 is negative..? or exactly -d1 and num.periods.alive.expectation.date = d1, hence = 0?
dt.ABCD.alive[Cov.Date == max(Cov.Date),
S := s.fct.expectation(term = (d1 + i - 2), A=Ai, B=Bbar_i, C=Ci, D=Dbar_i, beta_0=beta_0, s=s) -
s.fct.expectation(term = num.periods.alive.expectation.date, A=Ai, B=Bbar_i, C=Ci, D=Dbar_i, beta_0=beta_0, s=s)]
# S may be NA for customers alive only for <=1 period.
# Their f value is calculated without S then
dt.S <- dt.ABCD.alive[, list(S = sum(S)), keyby="Id"]
# F --------------------------------------------------------------------------------------------------------
# Add everything else needed
# For all customers Ak0t/Bk0t/Ck0t/Dk0t is the last ABCD value (with max(i) where max(Cov.Date))
dt.ABCD_k0t <- dt.ABCD.alive[Cov.Date == max(Cov.Date),
list(Id, A_k0t=Ai, Bbar_k0t=Bbar_i, C_k0t=Ci, Dbar_k0t=Dbar_i, i)]
dt.alive.customers <- dt.alive.customers[dt.ABCD_k0t, on = "Id"]
dt.alive.customers[dt.S, S := i.S, on = "Id"]
# Only alive for 1 period is a special case
# Mark who is alive for only one period
# dt.alive.customers is at max(Cov.Date) for every customer and hence i == max(i) and only one entry per customer
dt.alive.customers[, only.alive.in.1.period := i == 1]
# dt.alive.customers[, only.alive.in.1.period := num.periods.alive.expectation.date <= 1]
# F value
# t is exact (partial) time from alive until expectation end
# (Bk0tbar + t.customer*Ak0t) == (Bbar_i + t.customer*Ai) == Bi, which is needed, and not Bbar_i
# analogously for Di
dt.alive.customers[, f := ((beta_0)^s * r )/ ((s-1) * alpha_0)]
dt.alive.customers[only.alive.in.1.period == TRUE,
f := f * ((A_k0t*num.periods.alive.expectation.date*(s-1)) / (beta_0+C_k0t*num.periods.alive.expectation.date)^s + (A_k0t/C_k0t)/beta_0^(s-1) -
(A_k0t*(num.periods.alive.expectation.date*s + 1/C_k0t*beta_0))/(beta_0+C_k0t*num.periods.alive.expectation.date)^s)]
dt.alive.customers[only.alive.in.1.period == FALSE,
# f * (. +S)
f := f * ( (((A_k0t*num.periods.alive.expectation.date+Bbar_k0t) *(s-1)) /
(beta_0 + (C_k0t*num.periods.alive.expectation.date + Dbar_k0t))^s) + S)]
return(dt.alive.customers[, sum(f)])
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_expectation.R
|
pnbd_dyncov_palive <- function (clv.fitted){
cbs.x <- rsx <- i.x <- Bksum <- DkT <- Z <- palive <- NULL
# Params, not logparams
r <- [email protected][["r"]]
alpha_0 <- [email protected][["alpha"]]
s <- [email protected][["s"]]
beta_0 <- [email protected][["beta"]]
LLdata <- copy([email protected])
cbs <- copy(clv.fitted@cbs)
# write to LLdata for nicer calculation
# Z in the notes: F.2 in LL function
LLdata[cbs, cbs.x := i.x, on="Id"]
LLdata[, rsx := s/(r+s+cbs.x)]
LLdata[, palive := 1/((Bksum+alpha_0)^(cbs.x+r) * (DkT+beta_0)^s * rsx * Z + 1)]
# return as data.table
return(LLdata[, c("Id", "palive")])
}
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/R/pnbd_dyncov_palive.R
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
#fig.path = "figures/WALKTHROUGH-",
out.width = "100%"
)
# On CRAN, code may not run with more than 2 threads
# Otherwise results in failed check with "Re-building vignettes had CPU time xxx times elapsed time"
data.table::setDTthreads(threads = 2)
## ----install-package-CRAN, eval = FALSE---------------------------------------
# install.packages("CLVTools")
## ----install-package-GITHUB, eval = FALSE-------------------------------------
# install.packages("devtools")
# devtools::install_github("bachmannpatrick/CLVTools", ref = "development")
## ----load-library-------------------------------------------------------------
library("CLVTools")
## ----load-data----------------------------------------------------------------
data("apparelTrans")
apparelTrans
## ----load-CreateObj-----------------------------------------------------------
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
## ----print-CLVObject----------------------------------------------------------
clv.apparel
## ----summary-CLVObject--------------------------------------------------------
summary(clv.apparel)
## ----estimate-model-formula---------------------------------------------------
est.pnbd <- latentAttrition(~pnbd(),
data=clv.apparel)
est.pnbd
## ----estimate-model-formula2, eval=FALSE--------------------------------------
# est.pnbd <- latentAttrition(~pnbd(start.params.model=c(r=1, alpha=10, s=2, beta=8)),
# optimx.args = list(control=list(trace=5),
# method="Nelder-Mead"),
# data=clv.apparel)
## ----estimate-model-formula3, eval=FALSE--------------------------------------
# est.pnbd <- latentAttrition(data(split=40, format=ymd, unit=w)~pnbd(), data=apparelTrans)
## ----estimate-model, eval=FALSE-----------------------------------------------
# est.pnbd <- pnbd(clv.data = clv.apparel)
# est.pnbd
## ----estimate-model2, eval=FALSE----------------------------------------------
# est.pnbd <- pnbd(clv.data = clv.apparel,
# start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
# optimx.args = list(control=list(trace=5),
# method="Nelder-Mead"
# ))
## ----param-summary------------------------------------------------------------
#Full detailed summary of the parameter estimates
summary(est.pnbd)
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
## ----coef-model---------------------------------------------------------------
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
#Extract the confidence intervals
confint(est.pnbd)
## ----ll-model-----------------------------------------------------------------
# LogLikelihood at maximum
logLik(est.pnbd)
# Variance-Covariance Matrix at maximum
vcov(est.pnbd)
## ----estimate-ggomnbd-formula, eval=FALSE-------------------------------------
# est.ggomnbd <- latentAttrition(~ggomnbd(start.params.model=
# c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001)),
# optimx.args = list(method="Nelder-Mead"),
# data=clv.apparel)
## ----estimate-ggomnbd, eval=FALSE---------------------------------------------
# est.ggomnbd <- ggomnbd(clv.data = clv.apparel,
# start.params.model = c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001),
# optimx.args = list(method="Nelder-Mead"))
## ----predict-model------------------------------------------------------------
results <- predict(est.pnbd)
print(results)
## ----predict-model2, eval = FALSE---------------------------------------------
# predict(est.pnbd, prediction.end = 30)
## ----plot-model3, eval = FALSE------------------------------------------------
# predict(est.pnbd, prediction.end = "2006-05-08")
## ----plot-actual, fig.height=4.40, fig.width=9--------------------------------
plot(clv.apparel)
## ----plot-interpurchase, fig.height=4.40, fig.width=9-------------------------
plot(clv.apparel, which="interpurchasetime")
## ----plot-model, fig.height=4.40, fig.width=9---------------------------------
plot(est.pnbd)
## ----plot-model2, eval = FALSE------------------------------------------------
# plot(est.pnbd, prediction.end = 30, cumulative = TRUE)
## ----predict-model3, eval = FALSE---------------------------------------------
# plot(est.pnbd, prediction.end = "2006-05-08", cumulative = TRUE)
## ----predict-model4, eval = FALSE---------------------------------------------
# plot(est.pnbd, which="pmf", trans.bins=0:5, label.remaining="6+")
## ----Cov-staticData-----------------------------------------------------------
data("apparelStaticCov")
apparelStaticCov
## ----Cov-dynData--------------------------------------------------------------
data("apparelDynCov")
apparelDynCov
## ----Cov-setStatic------------------------------------------------------------
clv.static<- SetStaticCovariates(clv.data = clv.apparel,
data.cov.life = apparelStaticCov,
data.cov.trans = apparelStaticCov,
names.cov.life = c("Gender", "Channel"),
names.cov.trans =c("Gender", "Channel"),
name.id = "Id")
## ----Cov-setDynamic, eval=FALSE, message=FALSE, warning=TRUE------------------
# clv.dyn <- SetDynamicCovariates(clv.data = clv.apparel,
# data.cov.life = apparelDynCov,
# data.cov.trans = apparelDynCov,
# names.cov.life = c("Marketing", "Gender", "Channel"),
# names.cov.trans = c("Marketing", "Gender", "Channel"),
# name.id = "Id",
# name.date = "Cov.Date")
## ----static-cov-estimate-formula1, message=TRUE, warning=FALSE, eval=FALSE----
# est.pnbd.static <- latentAttrition(~pnbd()|.|., clv.static)
## ----static-cov-estimate-formula2, warning=FALSE, eval=FALSE------------------
# est.pnbd.static <- latentAttrition(~pnbd()|Gender|Channel+Gender, clv.static)
#
## ---- static-covariates-formula3, warning=FALSE, eval=FALSE-------------------
# est.pnbd.static <- latentAttrition(~pnbd()|Channel+Gender|I(log(Channel+2)), clv.static)
## ----static-covariates-formula4, warning=FALSE, eval=FALSE--------------------
# est.pnbd.static <- latentAttrition(data()~pnbd()|.|.,
# data=apparelTrans, cov=apparelStaticCov)
## ----dyn-cov-formula1, eval=FALSE---------------------------------------------
# est.pnbd.dyn <- latentAttrition(~pnbd()|.|., optimx.args = list(control=list(trace=5)),
# clv.dyn)
## ----static-cov-estimate, message=TRUE, warning=FALSE-------------------------
est.pnbd.static <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.life = c(Gender=0.6, Channel=0.4),
start.params.trans = c(Gender=0.6, Channel=0.4))
## ----dyn-cov-estimate, eval=FALSE---------------------------------------------
# est.pnbd.dyn <- pnbd(clv.dyn,
# start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
# start.params.life = c(Marketing=0.5, Gender=0.6, Channel=0.4),
# start.params.trans = c(Marketing=0.5, Gender=0.6, Channel=0.4),
# optimx.args = list(control=list(trace=5)))
## ----Cov-summary--------------------------------------------------------------
summary(est.pnbd.static)
## ----cor-formula1, eval=FALSE-------------------------------------------------
# est.pnbd.cor <- latentAttrition(~pnbd(use.cor=TRUE),
# data=clv.apparel)
## ----Cov-cor, eval=FALSE------------------------------------------------------
# est.pnbd.cor <- pnbd(clv.apparel,
# use.cor= TRUE)
# summary(est.pnbd.cor)
## ----reg-formula, eval=FALSE--------------------------------------------------
# est.pnbd.reg <- latentAttrition(~pnbd()|.|.|regularization(life=3, trans=8), clv.static)
# summary(est.pnbd.reg)
## ----reg-advOptions, eval=FALSE-----------------------------------------------
# est.pnbd.reg <- pnbd(clv.static,
# start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
# reg.lambdas = c(trans=100, life=100))
# summary(est.pnbd.reg)
## ----constr-formula, eval=FALSE-----------------------------------------------
# est.pnbd.constr <- latentAttrition(~pnbd(names.cov.constr=c("Gender"),
# start.params.constr = c(Gender = 0.6))|.|.,
# clv.static)
# summary(est.pnbd.constr)
## ----constr-advOptions, eval=FALSE--------------------------------------------
# est.pnbd.constr <- pnbd(clv.static,
# start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
# start.params.constr = c(Gender=0.6),
# names.cov.constr=c("Gender"))
# summary(est.pnbd.constr)
## ----spending-load-data and initialize----------------------------------------
data("apparelTrans")
apparelTrans
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
## ----spending-estimate-formula1-----------------------------------------------
est.gg <- spending(~gg(),
data=clv.apparel)
est.gg
## ----spending-estimate-formula2, eval=FALSE-----------------------------------
# est.gg <- spending(~gg(start.params.model=c(p=0.5, q=15, gamma=2)),
# optimx.args = list(control=list(trace=5)),
# data=clv.apparel)
## ----spending-estimate-formula3, eval=FALSE-----------------------------------
# est.gg <- spending(~gg(remove.first.transaction=FALSE),
# data=clv.apparel)
## ----estimate-model-formula4, eval=FALSE--------------------------------------
# est.gg <- spending(data(split=40, format=ymd, unit=w)~gg(),
# data=apparelTrans)
## ----spending-estimate-model1, eval=FALSE-------------------------------------
# est.gg<- gg(clv.data = clv.apparel)
# est.gg
## ----spending-estimate-model2, eval=FALSE-------------------------------------
# est.gg<- gg(start.params.model=c(p=0.5, q=15, gamma=2), clv.data = clv.apparel)
# est.gg
## ----spending-estimate-model3, eval=FALSE-------------------------------------
# est.gg<- gg(clv.data = clv.apparel, remove.first.transaction=FALSE)
# est.gg
## ----spending-predict-model---------------------------------------------------
results.spending <- predict(est.gg)
print(results.spending)
## ----spending-plot-model4, fig.height=4.40, fig.width=9-----------------------
plot(est.gg)
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/inst/doc/CLVTools.R
|
---
title: "Walkthrough for the CLVTools Package"
output:
pdf_document:
latex_engine: xelatex
toc: true
number_sections: yes
bibliography: bibliography.bib
vignette: >
%\VignetteIndexEntry{The CLVTools Package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
#fig.path = "figures/WALKTHROUGH-",
out.width = "100%"
)
# On CRAN, code may not run with more than 2 threads
# Otherwise results in failed check with "Re-building vignettes had CPU time xxx times elapsed time"
data.table::setDTthreads(threads = 2)
```
# Prerequisites: Setup the R environment
Install the stable version from CRAN:
```{r install-package-CRAN, eval = FALSE}
install.packages("CLVTools")
```
Install the development version from GitHub (using the `devtools` package [@devtools]):
```{r install-package-GITHUB, eval = FALSE}
install.packages("devtools")
devtools::install_github("bachmannpatrick/CLVTools", ref = "development")
```
Load the package
```{r load-library}
library("CLVTools")
```
# Apply the `CLVTools` Package
## General workflow
Independent of the latent attrition model applied in `CLVTools`, the general workflow consists of three main steps:
1. Create a `clv.data` object containing the dataset and required meta-information such as date formats and column names in the dataset. After initializing the object, there is the option to add additional information on covariates in a separate step.
2. Fit the model on the data provided.
3. Use the estimated model parameters to predict future customer purchase behavior.

`CLVTools` provides two ways for evaluating latent attrition models: you can use of the provided formula interface or you can use standard functions (non-formula interface). Both offer the same functionality, however the formula interface is especially helpful when covariates are included in the model. Through out this walkthrough, we will illustrate both options.
Reporting and plotting results is facilitated by the implementation of well-known generic methods such as `plot()`, `print()` and `summary()`. These commands adapt their output according to the model state and may be used at any point of the workflow.
## Load sample data provided in the package
As Input data `CLVTools` requires customers' transaction history. Every transaction record consists of a purchase date and customer ID. Optionally, the price of the transaction may be included to allow for prediction of future customer spending using an additional Gamma/Gamma model[@Fader2005b; @Colombo1999]. Using the full history of transaction data allows for comprehensive plots and summary statistics, which allow the identification of possible issues prior to model estimation. Data may be provided as `data.frame` or `data.table` [@data.table].
It is common practice to split time series data into two parts, an estimation and a holdout period. The model is estimated based on the data from the estimation period while the data from the holdout period allows to rigorously assess model performance. Once model performance is checked on known data one can proceed to predict data without a holdout period. The length of the estimation period is heavily dependent on the characteristics of the analyzed dataset. We recommend to choose an estimation period that contains in minimum the length of the average inter-purchase time. Note that all customers in the dataset need to purchase at least once during the estimation period, i.e. these models do not account for prospects who have not yet a purchase record.
Some models included in `CLVTools` allow to model the impact of covariates. These covariates may explain heterogeneity among the customers and therefore increase the predictive accuracy of the model. At the same time, we may also identify and quantify the effects of these covariates on customer purchase and customer attrition. `CLVTools` distinguishes between time-invariant and time-varying covariates. Time-invariant covariates include customer characteristics such as demographics that do not change over time. Time-varying covariates are allowed to change over time. They include for example direct marketing information or seasonal patterns.
For the following example, we use simulated data comparable to data from a retailer in the apparel industry. The dataset contains transactional detail records for every customer consisting of customer id, date of purchase and the total monetary value of the transaction. The apparel dataset is available in the `CLVTools` package. Use the `data(apparelTrans)` to load it:
```{r load-data}
data("apparelTrans")
apparelTrans
```
## Initialize the CLV-Object{#clvdata}
Before we estimate a model, we are required to initialize a data object using the `clvdata()` command. The data object contains the prepared transactional data and is later used as input for model fitting. Make sure to store the generated object in a variable, e.g. in our example `clv.apparel`.
Be aware that probabilistic models such as the ones implemented in `CLVTools` are usually applied to specific customer cohorts. That means, you analyze customer that have joined your company at the same time (usually same day, week, month, or quarter). For more information on cohort analysis, see also [here](https://en.wikipedia.org/wiki/Cohort_analysis). Consequently, the data apparelTrans in this example is not the full transaction records of a fashion retailer, but rather only the customer cohort of 250 customers purchasing for the first time at this business on the day of 2005-01-03. This has to be done before initializing a data object using the `clvdata()` command.
Through the argument `data.transactions` a `data.frame` or `data.table` which contains the transaction records, is specified. In our example this is `data.transactions=apparelTrans`. The argument `date.format` is used to indicate the format of the date variable in the data used. The date format in the apparel dataset is given as "year-month-day" (i.e., "2005-01-03"), therefore we set `date.format="ymd"`. Other combinations such as `date.format="dmy"` are possible. See the documentation of `lubridate` [@lubridate] for all details. `time.unit` is the scale used to measure time between two dates. For this dataset and in most other cases The argument `time.unit="week"` is the preferred choice. Abbreviations may be used (i.e. "w"). `estimation.split` indicates the length of the estimation period. Either the length of the estimation period (in previous specified time units) or the date at which the estimation period ends can be specified. If no value is provided, the whole dataset is used as estimation period (i.e. no holdout period). In this example, we use an estimation period of 40 weeks. Finally, the three name arguments indicate the column names for customer ID, date and price in the supplied dataset. Note that the price column is optional.
```{r load-CreateObj}
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
```
## Check the `clvdata` Object
To get details on the `clvdata` object, print it to the console.
```{r print-CLVObject}
clv.apparel
```
Alternatively the `summary()` command provides full detailed summary statistics for the provided transactional detail. `summary()` is available at any step in the process of estimating a probabilistic customer attrition model with `CLVTools`. The result output is updated accordingly and additional information is added to the summary statistics.`nobs()` extracts the number of observations. For the this particular dataset we observe a total of 250 customers who made in total 2257 repeat purchases. Approximately 26% of the customers are zero repeaters, which means that the only a minority of the customers do not return to the store after their first purchase.
```{r summary-CLVObject}
summary(clv.apparel)
```
## Estimate Model Parameters{#estimate}
After initializing the object, we can start estimating the first probabilistic latent attrition model. We start with the standard Pareto/NBD model [@Schmittlein1987] and therefore use the command `pnbd()` to fit the model and estimate model parameters. `clv.data` specifies the initialized object prepared in the last step. Optionally, starting values for the model parameters and control settings for the optimization algorithm may be provided: The argument `start.params.model` allows to assign a vector (e.g. `c(alpha=1, beta=2, s=1, beta=2)` in the case of the Pareto/NBD model) of starting values for the optimization. This is useful if prior knowledge on the parameters of the distributions are available. By default starting values are set to 1 for all parameters. The argument `optimx.args` provides an option to control settings for the optimization routine. It passes a list of arguments to the optimizer. All options known from the package `optimx` [@optimx1; @optimx2] may be used. This option enables users to specify specific optimization algorithms, set upper and/or lower limits or enable tracing information on the progress of the optimization. In the case of the standard Pareto/NBD model, `CLVTools` uses by default the optimization method `L-BFGS-G` [@byrd1995limited]. If the result of the optimization is in-feasible, the optimization automatically switches to the more robust but often slower `Nelder-Mead` method [@nelder1965simplex]. `verbose` shows additional output.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r estimate-model-formula}
est.pnbd <- latentAttrition(~pnbd(),
data=clv.apparel)
est.pnbd
```
Using start parameters and other additional arguments for the optimzier:
```{r estimate-model-formula2, eval=FALSE}
est.pnbd <- latentAttrition(~pnbd(start.params.model=c(r=1, alpha=10, s=2, beta=8)),
optimx.args = list(control=list(trace=5),
method="Nelder-Mead"),
data=clv.apparel)
```
When using the formula interface, it is also possible to fit the model without prior specification of of a `clvdata` object:
```{r estimate-model-formula3, eval=FALSE}
est.pnbd <- latentAttrition(data(split=40, format=ymd, unit=w)~pnbd(), data=apparelTrans)
```
### **Estimating the model using non-formula interface:**
```{r estimate-model, eval=FALSE}
est.pnbd <- pnbd(clv.data = clv.apparel)
est.pnbd
```
If we assign starting parameters and additional arguments for the optimizer we use:
```{r estimate-model2, eval=FALSE}
est.pnbd <- pnbd(clv.data = clv.apparel,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
optimx.args = list(control=list(trace=5),
method="Nelder-Mead"
))
```
Parameter estimates may be reported by either printing the estimated object (i.e. `est.pnbd`) directly in the console or by calling `summary(est.pnbd)` to get a more detailed report including the likelihood value as well as AIC and BIC. Alternatively parameters may be directly extracted using `coef(est.pnbd)`. Also `loglik()`, `confint()` and `vcov()` are available to directly access the Loglikelihood value, confidence intervals for the parameters and to calculate the Variance-Covariance Matrix for the fitted model. For the standard Pareto/NBD model, we get 4 parameters $r, \alpha, s$ and $\beta$. where $r,\alpha$ represent the shape and scale parameter of the gamma distribution that determines the purchase rate and $s,\beta$ of the attrition rate across individual customers. $r/\alpha$ can be interpreted as the mean purchase and $s/\beta$ as the mean attrition rate. A significance level is provided for each parameter estimates. In the case of the apparelTrans dataset we observe a an average purchase rate of $r/\alpha=0.147$ transactions and an average attrition rate of $s/\beta=0.031$ per customer per week. KKT 1 and 2 indicate the Karush-Kuhn-Tucker optimality conditions of the first and second order [@KKT]. If those criteria are not met, the optimizer has probably not arrived at an optimal solution. If this is the case it is usually a good idea to rerun the estimation using alternative starting values.
```{r param-summary}
#Full detailed summary of the parameter estimates
summary(est.pnbd)
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
```
To extract only the coefficients, we can use `coef()`. To access the confidence intervals for all parameters `confint()` is available.
```{r coef-model}
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
#Extract the confidence intervals
confint(est.pnbd)
```
In order to get the Likelihood value and the corresponding Variance-Covariance Matrix we use the following commands:
```{r ll-model}
# LogLikelihood at maximum
logLik(est.pnbd)
# Variance-Covariance Matrix at maximum
vcov(est.pnbd)
```
As an alternative to the Pareto/NBD model `CLVTools` features the BG/NBD model [@Fader2005c] and the GGomp/NBD [@Bemmaor2012a]. To use the alternative models replace `pnbd()` by the corresponding model-command. Note that he naming and number of model parameters is dependent on the model. Consult the manual for more details on the individual models. Beside probabilistic latent attrition models, `CLVTools` also features the Gamma/Gamma model [@Colombo1999; @Fader2005c] which is used to predict customer spending. See section [Customer Spending](#spending) for details on the spending model.
|Command| Model | Covariates| Type |
|---|---|---|---|---|
| pnbd() |Pareto/NBD| time-invariant & time-varying | latent attrition model |
| bgnbd() |BG/NBD | time-invariant | latent attrition model |
| ggomnbd() |GGom/NBD | time-invariant | latent attrition model |
| gg() | Gamma/Gamma | - | spending model |
To estimate the GGom/NBD model we apply the `ggomnbd()`to the `clv.apparel` object. The GGom/NBD model is more flexible than the Pareto/NBD model, however it sometimes is challenging to optimize. Note that in this particular case providing start parameters is essential to arrive at an optimal solution (i.e. `kkt1: TRUE` and `kkt2: TRUE`).
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r estimate-ggomnbd-formula, eval=FALSE}
est.ggomnbd <- latentAttrition(~ggomnbd(start.params.model=
c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001)),
optimx.args = list(method="Nelder-Mead"),
data=clv.apparel)
```
### **Estimating the model using non-formula interface:**
```{r estimate-ggomnbd, eval=FALSE}
est.ggomnbd <- ggomnbd(clv.data = clv.apparel,
start.params.model = c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001),
optimx.args = list(method="Nelder-Mead"))
```
## Predict Customer Behavior{#predict}
Once the model parameters are estimated, we are able to predict future customer behavior on an individual level. To do so, we use `predict()` on the object with the estimated parameters (i.e. `est.pnbd`). The prediction period may be varied by specifying `prediction.end`. It is possible to provide either an end-date or a duration using the same time unit as specified when initializing the object (i.e `prediction.end = "2006-05-08"` or `prediction.end = 30`). By default, the prediction is made until the end of the dataset specified in the `clvdata()` command. The argument `continuous.discount.factor` allows to adjust the discount rate used to estimated the discounted expected transactions (DERT). The default value is `0.1` (=10%). Make sure to convert your discount rate if you use annual/monthly/weekly discount rates. An annual rate of `(100 x d)\%` equals a continuous rate `delta = ln(1+d)`. To account for time units which are not annual, the continuous rate has to be further adjusted to `delta=ln(1+d)/k`, where `k` are the number of time units in a year. Probabilistic customer attrition model predict in general three expected characteristics for every customer:
* "conditional expected transactions" (CET), which is the number of transactions to expect form a customer during the prediction period,
* "probability of a customer being alive" (PAlive) at the end of the estimation period and
* "discounted expected residual transactions" (DERT) for every customer, which is the total number of transactions for the residual lifetime of a customer discounted to the end of the estimation period.
If spending information was provided when initializing the `clvdata`-object, `CLVTools` provides prediction for
* predicted mean spending estimated by a Gamma/Gamma model [@Colombo1999; @Fader2005c] and
* the customer lifetime value (CLV). CLV is calculated as the product of DERT and predicted spending.
If a holdout period is available additionally the true numbers of transactions ("actual.x") and true spending ("actual.total.spending") during the holdout period are reported.
To use the parameter estimates on new data (e.g., an other customer cohort), the argument `newdata` optionally allows to provide a new `clvdata` object.
```{r predict-model}
results <- predict(est.pnbd)
print(results)
```
To change the duration of the prediction time, we use the `predicton.end` argument. We can either provide a time period (30 weeks in this example):
```{r predict-model2, eval = FALSE}
predict(est.pnbd, prediction.end = 30)
```
or provide a date indication the end of the prediction period:
```{r plot-model3, eval = FALSE}
predict(est.pnbd, prediction.end = "2006-05-08")
```
## Plotting{#plotting}
`CLVTools`, offers a variety of different plots. All `clvdata` objects may be plotted using the `plot()` command. Similar to `summary()`, the output of `plot()` and the corresponding options are dependent on the current modeling step. When applied to a data object created the `clvdata()` command, the following plots can be selected using the `which` option of plotting:
* Tracking plot (`which="tracking"`): plots the the aggregated repeat transactions per period over a given time period. The period can be specified using the `prediction.end` option. It is also possible to generate cumulative tracking plots (`cumulative = FALSE`). The tracking plot is the default option.
* Frequency plot (`which="frequency"`): plots the distribution of transactions or repeat transactions per customer, after aggregating transactions of the same customer on a single time point. The bins may be adjusted using the option `trans.bins`. (Note that if `trans.bins` is changed, the option for labeling (`label.remaining`) usually needs to be adapted as well.)
* Spending plot (`which="spending"`): plots the empirical density of either customer's average spending per transaction. Note that this includes all transactions and not only repeat-transactions. You can switch to plotting the value of every transaction for a customer (instead of the a customers mean spending) using `mean.spending=FALSE`.
* Interpurchase time plot (`which="interpurchasetime"`): plots the empirical density of customer's mean time (in number of periods) between transactions, after aggregating transactions of the same customer on a single time point. Note that customers without repeat-transactions are note part of this plot.
In the following, we have a basic tracking-plot for the aggregated repeat transactions
```{r plot-actual, fig.height=4.40, fig.width=9}
plot(clv.apparel)
```
To plot customers mean interpurchase time, we use:
```{r plot-interpurchase, fig.height=4.40, fig.width=9}
plot(clv.apparel, which="interpurchasetime")
```
When the `plot()` command is applied to an object with the an estimated model (i.e. `est.pnbd`), the following plots can be selected using the `which` option of:
* Tracking plot (`which="tracking"`): plots the actual repeat transactions and overlays it with the repeat transaction as predicted by the fitted model. Currently, following previous literature, the in-sample unconditional expectation is plotted in the holdout period. The period can be specified using the `prediction.end` option. It is also possible to generate cumulative tracking plots (`cumulative = FALSE`). The tracking plot is th the default option. The argument `transactions` disable for plotting actual transactions (`transactions=FALSE`). For further plotting options see the documentation. Note that only whole periods can be plotted and that the prediction end might not exactly match prediction.end. See the `?plot.clv.data` for more details.
* Probability mass function (pmf) plot (`which="pmf"`): plots the actual and expected number of customers which made a given number of repeat transaction in the estimation period. The expected number is based on the PMF of the fitted model, the probability to make exactly a given number of repeat transactions in the estimation period. For each bin, the expected number is the sum of all customers' individual PMF value. The bins for the transactions can be adjusted using the option `trans.bins`. (Note that if `trans.bins` is changed, `label.remaining` usually needs to be adapted as well.
For a standard tracking plot including the model, we use:
```{r plot-model, fig.height=4.40, fig.width=9}
plot(est.pnbd)
```
To plot the *cumulative* expected transactions 30 time units (30 weeks in this example) ahead of the end of the estimation plot, we use:
```{r plot-model2, eval = FALSE}
plot(est.pnbd, prediction.end = 30, cumulative = TRUE)
```
Alternatively, it is possible to specify a date for the `prediction.end`argument. Note that dates are rounded to the next full time unit (i.e. week):
```{r predict-model3, eval = FALSE}
plot(est.pnbd, prediction.end = "2006-05-08", cumulative = TRUE)
```
For a plot of the probability mass function (pmf), with 7 bins, we use:
```{r predict-model4, eval = FALSE}
plot(est.pnbd, which="pmf", trans.bins=0:5, label.remaining="6+")
```
## Covariates
`CLVTools` provides the option to include covariates into probabilistic customer attrition models. Covariates may affect the purchase or the attrition process, or both. It is also possible to include different covariates for the two processes. However, support for covariates is dependent on the model. Not all implemented models provide an option for covariates. In general, `CLVTools` distinguishes between two types of covariates: time-invariant and time-varying. The former include factors that do not change over time such as customer demographics or customer acquisition information. The latter may change over time and include marketing activities or seasonal patterns.
Data for time-invariant covariates must contain a unique customer ID and a single value for each covariate. It should be supplied as a `data.frame` or `data.table`. In the example of the apparel retailer we use demographic information "gender" as time-invariant and information on the acquisition channel as covariate for both, the purchase and the attrition process. Use the `data("apparelStaticCov")` command to load the time-invariant covariates. In this example gender is coded as a dummy variable with `male=0` and `female=1` and channel with `online=0` and `offline=1`.
```{r Cov-staticData}
data("apparelStaticCov")
apparelStaticCov
```
Data for time-varying covariates requires a time-series of covariate values for every customer. I.e. if the time-varying covariates are allowed to change every week, a value for every customer for every week is required. Note that all contextual factors are required to use the same time intervals for the time-series. In the example of the apparel retailer we use information on direct marketing (`Marekting`) as time-varying covariate. Additionally, we add gender as time-invariant contextual factors. Note that the data structure of invariant covariates needs to be aligned with the structure of time-varying covariate. Use `data("apparelDynCov")` command to load
```{r Cov-dynData}
data("apparelDynCov")
apparelDynCov
```
To add the covariates to an initialized `clvdata` object the commands `SetStaticCovariates()` and `SetDynamicCovariates()` are available. The two commands are mutually exclusive. The argument `clv.data` specifies the initialized object and the argument `data.cov.life` respectively `data.cov.trans` specifies the data source for the covariates for the attrition and the purchase process. Covariates are added separately for the purchase and the attrition process. Therefore if a covariate should affect both processes it has to be added in both arguments: `data.cov.life` *and* `data.cov.trans`. The arguments `names.cov.life` and `names.cov.trans` specify the column names of the covariates for the two processes. In our example, we use the same covariates for both processes. Accordingly, we specify the time-invariant covariates "Gender" and "Channel" as follows:
```{r Cov-setStatic}
clv.static<- SetStaticCovariates(clv.data = clv.apparel,
data.cov.life = apparelStaticCov,
data.cov.trans = apparelStaticCov,
names.cov.life = c("Gender", "Channel"),
names.cov.trans =c("Gender", "Channel"),
name.id = "Id")
```
To specify the time-varying contextual factors for seasonal patterns and direct marketing, we use the following:
```{r Cov-setDynamic, eval=FALSE, message=FALSE, warning=TRUE}
clv.dyn <- SetDynamicCovariates(clv.data = clv.apparel,
data.cov.life = apparelDynCov,
data.cov.trans = apparelDynCov,
names.cov.life = c("Marketing", "Gender", "Channel"),
names.cov.trans = c("Marketing", "Gender", "Channel"),
name.id = "Id",
name.date = "Cov.Date")
```
In order to include time-invariant covariates in a time-varying model, they may be recoded as a time-varying covariate with a constant value in every time period.
Once the covariates are added to the model the estimation process is almost identical to the standard model without covariates. The only difference is that the provided object now data for contains either time-invariant or time-varying covariates and the option to define start parameters for the covariates of both processes using the arguments `start.params.life` and `start.params.trans`. If not set, the staring values are set to 1. To define starting parameters for the covariates, the name of the corresponding factor has to be used. For example in the case of time-invariant covariates:
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface**:
We use all present covariates:
```{r static-cov-estimate-formula1, message=TRUE, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|.|., clv.static)
```
Using the formula interface, we can use only selected covariates (only Gender for the lifetime process and both, Channel and Gender for the transaction process):
```{r static-cov-estimate-formula2, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|Gender|Channel+Gender, clv.static)
```
Or we can transform covariates:
```{r, static-covariates-formula3, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|Channel+Gender|I(log(Channel+2)), clv.static)
```
It is also possible to not initialize a `clvdata` object for the covariates but instead specify the covariate data directly in the model:
```{r static-covariates-formula4, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(data()~pnbd()|.|.,
data=apparelTrans, cov=apparelStaticCov)
```
Analogously, we can estimate the model containing time-varying covariates. In this example we also activate output of the optimizer in order to observe the progress.
```{r dyn-cov-formula1, eval=FALSE}
est.pnbd.dyn <- latentAttrition(~pnbd()|.|., optimx.args = list(control=list(trace=5)),
clv.dyn)
```
### **Estimating the model using non-formula interface**:
```{r static-cov-estimate, message=TRUE, warning=FALSE}
est.pnbd.static <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.life = c(Gender=0.6, Channel=0.4),
start.params.trans = c(Gender=0.6, Channel=0.4))
```
It is not possible to alter or select covariates in the non-formula interface, but, we can also estimate a model containing time-varying covariates:
```{r dyn-cov-estimate, eval=FALSE}
est.pnbd.dyn <- pnbd(clv.dyn,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.life = c(Marketing=0.5, Gender=0.6, Channel=0.4),
start.params.trans = c(Marketing=0.5, Gender=0.6, Channel=0.4),
optimx.args = list(control=list(trace=5)))
```
To inspect the estimated model we use `summary()`, however all other commands such as `print()`, `coef()`, `loglike()`, `confint()` and `vcov()` are also available. Now, output contains also parameters for the covariates for both processes. Since covariates are added separately for the purchase and the attrition process, there are also separate model parameters for the two processes. These parameters are directly interpretable as rate elasticity of the corresponding factors: A 1% change in a contextual factor $\bf{X}^{P}$ or $\bf{X}^{L}$ changes the purchase or the attrition rate by $\gamma_{purch}\bf{X}^{P}$ or $\gamma_{life}\bf{X}^{L}$ percent, respectively [@Gupta1991]. In the example of the apparel retailer, we observe that female customer purchase significantly more (`trans.Gender=1.42576`). Note, that female customers are coded as 1, male customers as 0. Also customers acquired offline (coded as Channel=1), purchase more (`trans.Channel=0.40304`) and stay longer (`life.Channel=0.9343`). Make sure to check the Karush-Kuhn-Tucker optimality conditions of the first and second order [@KKT] (KKT1 and KKT1) before interpreting the parameters. If those criteria are not met, the optimizer has probably not arrived at an optimal solution. If this is the case it is usually a good idea to rerun the estimation using alternative starting values.
```{r Cov-summary}
summary(est.pnbd.static)
```
To predict future customer behavior we use `predict()`. Note that dependent on the model, the predicted metrics may differ. For example, in the case of the Pareto/NBD model with time-varying covariates, instead of DERT, DECT is predicted. DECT only covers a finite time horizon in contrast to DERT. Time-varying covariates must be provided for the entire prediction period. If the data initially provided in the `SetDynamicCovariates()` command does not cover the complete prediction period, the argument `new.data` offers the ability to supply new data for the time-varying covariates in the from of a `clvdata` object.
## Add Correlation to the model
To relax the assumption of independence between the purchase and the attrition process, `CLVTools` provides the option to specify the argument `use.cor` when fitting the model (i.e. `pnbd`). In case of `use.cor=TRUE`, a Sarmanov approach is used to correlate the two processes. `start.param.cor` allows to optionally specify a starting value for the correlation parameter. Correlation can be added with or without covariates.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r cor-formula1, eval=FALSE}
est.pnbd.cor <- latentAttrition(~pnbd(use.cor=TRUE),
data=clv.apparel)
```
### **Estimating the model using non-formula interface:**
```{r Cov-cor, eval=FALSE}
est.pnbd.cor <- pnbd(clv.apparel,
use.cor= TRUE)
summary(est.pnbd.cor)
```
The parameter `Cor(life,trans)` is added to the parameter estimates that may be directly interpreted as a correlation. In the example of the apparel retailer the correlation parameter is not significant and the correlation is very close to zero, indicating that the purchase and the attrition process may be independent.
## Advanced Options for Covariates
`CLVTools` provides two additional estimation options for models containing covariates (time-invariant or time-varying): regularization and constraints for the parameters of the covariates. Support for this option is dependent on the model. They may be used simultaneously.
In the following we illustrate code for both, a formula-based interface a non-formula-based interface.
***Regularization*** helps to prevent overfitting of the model when using covariates. We can add regularization lambdas for the two processes. The larger the lambdas the stronger the effects of the regularization. Regularization only affects the parameters of the covariates. The use of regularization is indicated at the end of the `summary()` output.
### **Estimating the model using formula interface:**
```{r reg-formula, eval=FALSE}
est.pnbd.reg <- latentAttrition(~pnbd()|.|.|regularization(life=3, trans=8), clv.static)
summary(est.pnbd.reg)
```
### **Estimating the model using non-formula interface:**
We use the argument `reg.lambdas` to specify the lambdas for the two processes (i.e. `reg.lambdas = c(trans=100, life=100)`:
```{r reg-advOptions, eval=FALSE}
est.pnbd.reg <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
reg.lambdas = c(trans=100, life=100))
summary(est.pnbd.reg)
```
***Constraints*** implement equality constraints for contextual factors with regards to the two processes. For example the variable "gender" is forced to have the same effect on the purchase as well as on the attrition process. We can use the argument `names.cov.constr`(i.e. `names.cov.constr=c("Gender")`). In this case, the output only contains one parameter for "Gender" as it is constrained to be the same for both processes. To provide starting parameters for the constrained variable use `start.params.constr`. The use of constraints is indicated at the end of the `summary()` output.
### **Estimating the model using formula interface:**
```{r constr-formula, eval=FALSE}
est.pnbd.constr <- latentAttrition(~pnbd(names.cov.constr=c("Gender"),
start.params.constr = c(Gender = 0.6))|.|.,
clv.static)
summary(est.pnbd.constr)
```
Note: providing a starting parameter for the constrained variable is optional.
### **Estimating the model using non-formula interface:**
```{r constr-advOptions, eval=FALSE}
est.pnbd.constr <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.constr = c(Gender=0.6),
names.cov.constr=c("Gender"))
summary(est.pnbd.constr)
```
# Customer Spending {#spending}
Customer lifetime value (CLV) is composed of three components of every customer: the future level of transactions, expected attrition behaviour (i.e. probability of being alive) and the monetary value. While probabilistic latent attrition models provide metrics for the first two components, they do not predict customer spending. To predict customer spending an additional model is required. The `CLVTools`package features the Gamma/Gamma (G/G) [@Fader2005b; @Colombo1999] model for predicting customer spending. For convenience, the `predict()` command allows to automatically predict customer spending for all latent attrition models using the option `predict.spending=TRUE` (see section [Customer Spending](#spending)). However, to provide more options and more granular insights the Gamma/Gamma model can be estimated independently. In the following, we discuss how to estimate a Gamma/Gamma model using `CLVTools`.
The general workflow remains identical. It consists of the three main steps: (1) creating a `clv.data` object containing the dataset and required meta-information, (2) fitting the model on the provided data and (3) predicting future customer purchase behavior based on the fitted model.
`CLVTools` provides two ways for evaluating spending models: you can use of the formula interface or you can use standard functions (non-formula interface). Both offer the same functionality. Through out this walkthrough, we will illustrate both options.
Reporting and plotting results is facilitated by the implementation of well-known generic methods such as `plot()`, `print()` and `summary()`.
## Load sample data provided in the package
For estimating customer spending `CLVTools` requires customers' transaction history including price. Every transaction record consists of a purchase date,customer ID and the price of the transaction. Data may be provided as `data.frame` or `data.table` [@data.table]. Currently, the Gamma/Gamma model does not allow for covariates.
We use again simulated data comparable to data from a retailer in the apparel industry. The apparel dataset is available in the `CLVTools` package. We use the `data(apparelTrans)` to load it and initialize a data object using the `clvdata()` command. For details see section [Initialize the CLV-Object](#clvdata).
```{r spending-load-data and initialize}
data("apparelTrans")
apparelTrans
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
```
## Estimate Model Parameters
To estimate the Gamma/Gamma spending model, we use the command `gg()` on the initialized `clvdata` object. `clv.data` specifies the initialized object prepared in the last step. Optionally, starting values for the model parameters and control settings for the optimization algorithm may be provided: The argument `start.params.model` allows to assign a vector of starting values for the optimization (i.e `c(p=1, q=2, gamma=1)` for the the Gamma/Gamma model). This is useful if prior knowledge on the parameters of the distributions are available. By default starting values are set to 1 for all parameters. The argument `optimx.args` provides an option to control settings for the optimization routine (see section [Estimate Model Parameters](#estimate)).
In line with literature, `CLVTools` does not use by default the monetary value of the first transaction to fit the model since it might be atypical of future purchases. If the first transaction should be considered the argument `remove.first.transaction` can be set to `FALSE`.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r spending-estimate-formula1}
est.gg <- spending(~gg(),
data=clv.apparel)
est.gg
```
Using start parameters or other additional arguments for the optimzier:
```{r spending-estimate-formula2, eval=FALSE}
est.gg <- spending(~gg(start.params.model=c(p=0.5, q=15, gamma=2)),
optimx.args = list(control=list(trace=5)),
data=clv.apparel)
```
Specify the option to NOT remove the first transaction:
```{r spending-estimate-formula3, eval=FALSE}
est.gg <- spending(~gg(remove.first.transaction=FALSE),
data=clv.apparel)
```
When using the formula interface, it is also possible to fit the model without prior specification of of a `clvdata` object:
```{r estimate-model-formula4, eval=FALSE}
est.gg <- spending(data(split=40, format=ymd, unit=w)~gg(),
data=apparelTrans)
```
### **Estimating the model using non-formula interface:**
```{r spending-estimate-model1, eval=FALSE}
est.gg<- gg(clv.data = clv.apparel)
est.gg
```
Using start parameters and other additional arguments for the optimzier:
```{r spending-estimate-model2, eval=FALSE}
est.gg<- gg(start.params.model=c(p=0.5, q=15, gamma=2), clv.data = clv.apparel)
est.gg
```
Specify the option to NOT remove the first transaction:
```{r spending-estimate-model3, eval=FALSE}
est.gg<- gg(clv.data = clv.apparel, remove.first.transaction=FALSE)
est.gg
```
## Predict Customer Spending {#predictspending}
Once the model parameters are estimated, we are able to predict future customer mean spending on an individual level. To do so, we use `predict()` on the object with the estimated parameters (i.e. `est.gg`). Note that there is no need to specify a prediction period as we predict mean spending.
In general, probabilistic spending models predict the following expected characteristic for every customer:
* predicted mean spending ("predicted.mean.spending")
If a holdout period is available additionally the true mean spending ("actual.mean.spending") during the holdout period is reported.
To use the parameter estimates on new data (e.g., an other customer cohort), the argument `newdata` optionally allows to provide a new `clvdata` object.
```{r spending-predict-model}
results.spending <- predict(est.gg)
print(results.spending)
```
## Plot Spendings
an estimated spending model object (i.e. `est.gg`) may be plotted using the `plot()` command. The plot provides a comparison of the estimated and actual density of customer spending. The argument `plot.interpolation.points` allows to adjust the number of interpolation points in density graph.
```{r spending-plot-model4, fig.height=4.40, fig.width=9}
plot(est.gg)
```
### Literature
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/inst/doc/CLVTools.Rmd
|
---
title: "Walkthrough for the CLVTools Package"
output:
pdf_document:
latex_engine: xelatex
toc: true
number_sections: yes
bibliography: bibliography.bib
vignette: >
%\VignetteIndexEntry{The CLVTools Package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
#fig.path = "figures/WALKTHROUGH-",
out.width = "100%"
)
# On CRAN, code may not run with more than 2 threads
# Otherwise results in failed check with "Re-building vignettes had CPU time xxx times elapsed time"
data.table::setDTthreads(threads = 2)
```
# Prerequisites: Setup the R environment
Install the stable version from CRAN:
```{r install-package-CRAN, eval = FALSE}
install.packages("CLVTools")
```
Install the development version from GitHub (using the `devtools` package [@devtools]):
```{r install-package-GITHUB, eval = FALSE}
install.packages("devtools")
devtools::install_github("bachmannpatrick/CLVTools", ref = "development")
```
Load the package
```{r load-library}
library("CLVTools")
```
# Apply the `CLVTools` Package
## General workflow
Independent of the latent attrition model applied in `CLVTools`, the general workflow consists of three main steps:
1. Create a `clv.data` object containing the dataset and required meta-information such as date formats and column names in the dataset. After initializing the object, there is the option to add additional information on covariates in a separate step.
2. Fit the model on the data provided.
3. Use the estimated model parameters to predict future customer purchase behavior.

`CLVTools` provides two ways for evaluating latent attrition models: you can use of the provided formula interface or you can use standard functions (non-formula interface). Both offer the same functionality, however the formula interface is especially helpful when covariates are included in the model. Through out this walkthrough, we will illustrate both options.
Reporting and plotting results is facilitated by the implementation of well-known generic methods such as `plot()`, `print()` and `summary()`. These commands adapt their output according to the model state and may be used at any point of the workflow.
## Load sample data provided in the package
As Input data `CLVTools` requires customers' transaction history. Every transaction record consists of a purchase date and customer ID. Optionally, the price of the transaction may be included to allow for prediction of future customer spending using an additional Gamma/Gamma model[@Fader2005b; @Colombo1999]. Using the full history of transaction data allows for comprehensive plots and summary statistics, which allow the identification of possible issues prior to model estimation. Data may be provided as `data.frame` or `data.table` [@data.table].
It is common practice to split time series data into two parts, an estimation and a holdout period. The model is estimated based on the data from the estimation period while the data from the holdout period allows to rigorously assess model performance. Once model performance is checked on known data one can proceed to predict data without a holdout period. The length of the estimation period is heavily dependent on the characteristics of the analyzed dataset. We recommend to choose an estimation period that contains in minimum the length of the average inter-purchase time. Note that all customers in the dataset need to purchase at least once during the estimation period, i.e. these models do not account for prospects who have not yet a purchase record.
Some models included in `CLVTools` allow to model the impact of covariates. These covariates may explain heterogeneity among the customers and therefore increase the predictive accuracy of the model. At the same time, we may also identify and quantify the effects of these covariates on customer purchase and customer attrition. `CLVTools` distinguishes between time-invariant and time-varying covariates. Time-invariant covariates include customer characteristics such as demographics that do not change over time. Time-varying covariates are allowed to change over time. They include for example direct marketing information or seasonal patterns.
For the following example, we use simulated data comparable to data from a retailer in the apparel industry. The dataset contains transactional detail records for every customer consisting of customer id, date of purchase and the total monetary value of the transaction. The apparel dataset is available in the `CLVTools` package. Use the `data(apparelTrans)` to load it:
```{r load-data}
data("apparelTrans")
apparelTrans
```
## Initialize the CLV-Object{#clvdata}
Before we estimate a model, we are required to initialize a data object using the `clvdata()` command. The data object contains the prepared transactional data and is later used as input for model fitting. Make sure to store the generated object in a variable, e.g. in our example `clv.apparel`.
Be aware that probabilistic models such as the ones implemented in `CLVTools` are usually applied to specific customer cohorts. That means, you analyze customer that have joined your company at the same time (usually same day, week, month, or quarter). For more information on cohort analysis, see also [here](https://en.wikipedia.org/wiki/Cohort_analysis). Consequently, the data apparelTrans in this example is not the full transaction records of a fashion retailer, but rather only the customer cohort of 250 customers purchasing for the first time at this business on the day of 2005-01-03. This has to be done before initializing a data object using the `clvdata()` command.
Through the argument `data.transactions` a `data.frame` or `data.table` which contains the transaction records, is specified. In our example this is `data.transactions=apparelTrans`. The argument `date.format` is used to indicate the format of the date variable in the data used. The date format in the apparel dataset is given as "year-month-day" (i.e., "2005-01-03"), therefore we set `date.format="ymd"`. Other combinations such as `date.format="dmy"` are possible. See the documentation of `lubridate` [@lubridate] for all details. `time.unit` is the scale used to measure time between two dates. For this dataset and in most other cases The argument `time.unit="week"` is the preferred choice. Abbreviations may be used (i.e. "w"). `estimation.split` indicates the length of the estimation period. Either the length of the estimation period (in previous specified time units) or the date at which the estimation period ends can be specified. If no value is provided, the whole dataset is used as estimation period (i.e. no holdout period). In this example, we use an estimation period of 40 weeks. Finally, the three name arguments indicate the column names for customer ID, date and price in the supplied dataset. Note that the price column is optional.
```{r load-CreateObj}
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
```
## Check the `clvdata` Object
To get details on the `clvdata` object, print it to the console.
```{r print-CLVObject}
clv.apparel
```
Alternatively the `summary()` command provides full detailed summary statistics for the provided transactional detail. `summary()` is available at any step in the process of estimating a probabilistic customer attrition model with `CLVTools`. The result output is updated accordingly and additional information is added to the summary statistics.`nobs()` extracts the number of observations. For the this particular dataset we observe a total of 250 customers who made in total 2257 repeat purchases. Approximately 26% of the customers are zero repeaters, which means that the only a minority of the customers do not return to the store after their first purchase.
```{r summary-CLVObject}
summary(clv.apparel)
```
## Estimate Model Parameters{#estimate}
After initializing the object, we can start estimating the first probabilistic latent attrition model. We start with the standard Pareto/NBD model [@Schmittlein1987] and therefore use the command `pnbd()` to fit the model and estimate model parameters. `clv.data` specifies the initialized object prepared in the last step. Optionally, starting values for the model parameters and control settings for the optimization algorithm may be provided: The argument `start.params.model` allows to assign a vector (e.g. `c(alpha=1, beta=2, s=1, beta=2)` in the case of the Pareto/NBD model) of starting values for the optimization. This is useful if prior knowledge on the parameters of the distributions are available. By default starting values are set to 1 for all parameters. The argument `optimx.args` provides an option to control settings for the optimization routine. It passes a list of arguments to the optimizer. All options known from the package `optimx` [@optimx1; @optimx2] may be used. This option enables users to specify specific optimization algorithms, set upper and/or lower limits or enable tracing information on the progress of the optimization. In the case of the standard Pareto/NBD model, `CLVTools` uses by default the optimization method `L-BFGS-G` [@byrd1995limited]. If the result of the optimization is in-feasible, the optimization automatically switches to the more robust but often slower `Nelder-Mead` method [@nelder1965simplex]. `verbose` shows additional output.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r estimate-model-formula}
est.pnbd <- latentAttrition(~pnbd(),
data=clv.apparel)
est.pnbd
```
Using start parameters and other additional arguments for the optimzier:
```{r estimate-model-formula2, eval=FALSE}
est.pnbd <- latentAttrition(~pnbd(start.params.model=c(r=1, alpha=10, s=2, beta=8)),
optimx.args = list(control=list(trace=5),
method="Nelder-Mead"),
data=clv.apparel)
```
When using the formula interface, it is also possible to fit the model without prior specification of of a `clvdata` object:
```{r estimate-model-formula3, eval=FALSE}
est.pnbd <- latentAttrition(data(split=40, format=ymd, unit=w)~pnbd(), data=apparelTrans)
```
### **Estimating the model using non-formula interface:**
```{r estimate-model, eval=FALSE}
est.pnbd <- pnbd(clv.data = clv.apparel)
est.pnbd
```
If we assign starting parameters and additional arguments for the optimizer we use:
```{r estimate-model2, eval=FALSE}
est.pnbd <- pnbd(clv.data = clv.apparel,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
optimx.args = list(control=list(trace=5),
method="Nelder-Mead"
))
```
Parameter estimates may be reported by either printing the estimated object (i.e. `est.pnbd`) directly in the console or by calling `summary(est.pnbd)` to get a more detailed report including the likelihood value as well as AIC and BIC. Alternatively parameters may be directly extracted using `coef(est.pnbd)`. Also `loglik()`, `confint()` and `vcov()` are available to directly access the Loglikelihood value, confidence intervals for the parameters and to calculate the Variance-Covariance Matrix for the fitted model. For the standard Pareto/NBD model, we get 4 parameters $r, \alpha, s$ and $\beta$. where $r,\alpha$ represent the shape and scale parameter of the gamma distribution that determines the purchase rate and $s,\beta$ of the attrition rate across individual customers. $r/\alpha$ can be interpreted as the mean purchase and $s/\beta$ as the mean attrition rate. A significance level is provided for each parameter estimates. In the case of the apparelTrans dataset we observe a an average purchase rate of $r/\alpha=0.147$ transactions and an average attrition rate of $s/\beta=0.031$ per customer per week. KKT 1 and 2 indicate the Karush-Kuhn-Tucker optimality conditions of the first and second order [@KKT]. If those criteria are not met, the optimizer has probably not arrived at an optimal solution. If this is the case it is usually a good idea to rerun the estimation using alternative starting values.
```{r param-summary}
#Full detailed summary of the parameter estimates
summary(est.pnbd)
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
```
To extract only the coefficients, we can use `coef()`. To access the confidence intervals for all parameters `confint()` is available.
```{r coef-model}
#Extract the coefficients only
coef(est.pnbd)
#Alternative: oefficients(est.pnbd.obj)
#Extract the confidence intervals
confint(est.pnbd)
```
In order to get the Likelihood value and the corresponding Variance-Covariance Matrix we use the following commands:
```{r ll-model}
# LogLikelihood at maximum
logLik(est.pnbd)
# Variance-Covariance Matrix at maximum
vcov(est.pnbd)
```
As an alternative to the Pareto/NBD model `CLVTools` features the BG/NBD model [@Fader2005c] and the GGomp/NBD [@Bemmaor2012a]. To use the alternative models replace `pnbd()` by the corresponding model-command. Note that he naming and number of model parameters is dependent on the model. Consult the manual for more details on the individual models. Beside probabilistic latent attrition models, `CLVTools` also features the Gamma/Gamma model [@Colombo1999; @Fader2005c] which is used to predict customer spending. See section [Customer Spending](#spending) for details on the spending model.
|Command| Model | Covariates| Type |
|---|---|---|---|---|
| pnbd() |Pareto/NBD| time-invariant & time-varying | latent attrition model |
| bgnbd() |BG/NBD | time-invariant | latent attrition model |
| ggomnbd() |GGom/NBD | time-invariant | latent attrition model |
| gg() | Gamma/Gamma | - | spending model |
To estimate the GGom/NBD model we apply the `ggomnbd()`to the `clv.apparel` object. The GGom/NBD model is more flexible than the Pareto/NBD model, however it sometimes is challenging to optimize. Note that in this particular case providing start parameters is essential to arrive at an optimal solution (i.e. `kkt1: TRUE` and `kkt2: TRUE`).
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r estimate-ggomnbd-formula, eval=FALSE}
est.ggomnbd <- latentAttrition(~ggomnbd(start.params.model=
c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001)),
optimx.args = list(method="Nelder-Mead"),
data=clv.apparel)
```
### **Estimating the model using non-formula interface:**
```{r estimate-ggomnbd, eval=FALSE}
est.ggomnbd <- ggomnbd(clv.data = clv.apparel,
start.params.model = c(r=0.7, alpha=5, b=0.005, s=0.02, beta=0.001),
optimx.args = list(method="Nelder-Mead"))
```
## Predict Customer Behavior{#predict}
Once the model parameters are estimated, we are able to predict future customer behavior on an individual level. To do so, we use `predict()` on the object with the estimated parameters (i.e. `est.pnbd`). The prediction period may be varied by specifying `prediction.end`. It is possible to provide either an end-date or a duration using the same time unit as specified when initializing the object (i.e `prediction.end = "2006-05-08"` or `prediction.end = 30`). By default, the prediction is made until the end of the dataset specified in the `clvdata()` command. The argument `continuous.discount.factor` allows to adjust the discount rate used to estimated the discounted expected transactions (DERT). The default value is `0.1` (=10%). Make sure to convert your discount rate if you use annual/monthly/weekly discount rates. An annual rate of `(100 x d)\%` equals a continuous rate `delta = ln(1+d)`. To account for time units which are not annual, the continuous rate has to be further adjusted to `delta=ln(1+d)/k`, where `k` are the number of time units in a year. Probabilistic customer attrition model predict in general three expected characteristics for every customer:
* "conditional expected transactions" (CET), which is the number of transactions to expect form a customer during the prediction period,
* "probability of a customer being alive" (PAlive) at the end of the estimation period and
* "discounted expected residual transactions" (DERT) for every customer, which is the total number of transactions for the residual lifetime of a customer discounted to the end of the estimation period.
If spending information was provided when initializing the `clvdata`-object, `CLVTools` provides prediction for
* predicted mean spending estimated by a Gamma/Gamma model [@Colombo1999; @Fader2005c] and
* the customer lifetime value (CLV). CLV is calculated as the product of DERT and predicted spending.
If a holdout period is available additionally the true numbers of transactions ("actual.x") and true spending ("actual.total.spending") during the holdout period are reported.
To use the parameter estimates on new data (e.g., an other customer cohort), the argument `newdata` optionally allows to provide a new `clvdata` object.
```{r predict-model}
results <- predict(est.pnbd)
print(results)
```
To change the duration of the prediction time, we use the `predicton.end` argument. We can either provide a time period (30 weeks in this example):
```{r predict-model2, eval = FALSE}
predict(est.pnbd, prediction.end = 30)
```
or provide a date indication the end of the prediction period:
```{r plot-model3, eval = FALSE}
predict(est.pnbd, prediction.end = "2006-05-08")
```
## Plotting{#plotting}
`CLVTools`, offers a variety of different plots. All `clvdata` objects may be plotted using the `plot()` command. Similar to `summary()`, the output of `plot()` and the corresponding options are dependent on the current modeling step. When applied to a data object created the `clvdata()` command, the following plots can be selected using the `which` option of plotting:
* Tracking plot (`which="tracking"`): plots the the aggregated repeat transactions per period over a given time period. The period can be specified using the `prediction.end` option. It is also possible to generate cumulative tracking plots (`cumulative = FALSE`). The tracking plot is the default option.
* Frequency plot (`which="frequency"`): plots the distribution of transactions or repeat transactions per customer, after aggregating transactions of the same customer on a single time point. The bins may be adjusted using the option `trans.bins`. (Note that if `trans.bins` is changed, the option for labeling (`label.remaining`) usually needs to be adapted as well.)
* Spending plot (`which="spending"`): plots the empirical density of either customer's average spending per transaction. Note that this includes all transactions and not only repeat-transactions. You can switch to plotting the value of every transaction for a customer (instead of the a customers mean spending) using `mean.spending=FALSE`.
* Interpurchase time plot (`which="interpurchasetime"`): plots the empirical density of customer's mean time (in number of periods) between transactions, after aggregating transactions of the same customer on a single time point. Note that customers without repeat-transactions are note part of this plot.
In the following, we have a basic tracking-plot for the aggregated repeat transactions
```{r plot-actual, fig.height=4.40, fig.width=9}
plot(clv.apparel)
```
To plot customers mean interpurchase time, we use:
```{r plot-interpurchase, fig.height=4.40, fig.width=9}
plot(clv.apparel, which="interpurchasetime")
```
When the `plot()` command is applied to an object with the an estimated model (i.e. `est.pnbd`), the following plots can be selected using the `which` option of:
* Tracking plot (`which="tracking"`): plots the actual repeat transactions and overlays it with the repeat transaction as predicted by the fitted model. Currently, following previous literature, the in-sample unconditional expectation is plotted in the holdout period. The period can be specified using the `prediction.end` option. It is also possible to generate cumulative tracking plots (`cumulative = FALSE`). The tracking plot is th the default option. The argument `transactions` disable for plotting actual transactions (`transactions=FALSE`). For further plotting options see the documentation. Note that only whole periods can be plotted and that the prediction end might not exactly match prediction.end. See the `?plot.clv.data` for more details.
* Probability mass function (pmf) plot (`which="pmf"`): plots the actual and expected number of customers which made a given number of repeat transaction in the estimation period. The expected number is based on the PMF of the fitted model, the probability to make exactly a given number of repeat transactions in the estimation period. For each bin, the expected number is the sum of all customers' individual PMF value. The bins for the transactions can be adjusted using the option `trans.bins`. (Note that if `trans.bins` is changed, `label.remaining` usually needs to be adapted as well.
For a standard tracking plot including the model, we use:
```{r plot-model, fig.height=4.40, fig.width=9}
plot(est.pnbd)
```
To plot the *cumulative* expected transactions 30 time units (30 weeks in this example) ahead of the end of the estimation plot, we use:
```{r plot-model2, eval = FALSE}
plot(est.pnbd, prediction.end = 30, cumulative = TRUE)
```
Alternatively, it is possible to specify a date for the `prediction.end`argument. Note that dates are rounded to the next full time unit (i.e. week):
```{r predict-model3, eval = FALSE}
plot(est.pnbd, prediction.end = "2006-05-08", cumulative = TRUE)
```
For a plot of the probability mass function (pmf), with 7 bins, we use:
```{r predict-model4, eval = FALSE}
plot(est.pnbd, which="pmf", trans.bins=0:5, label.remaining="6+")
```
## Covariates
`CLVTools` provides the option to include covariates into probabilistic customer attrition models. Covariates may affect the purchase or the attrition process, or both. It is also possible to include different covariates for the two processes. However, support for covariates is dependent on the model. Not all implemented models provide an option for covariates. In general, `CLVTools` distinguishes between two types of covariates: time-invariant and time-varying. The former include factors that do not change over time such as customer demographics or customer acquisition information. The latter may change over time and include marketing activities or seasonal patterns.
Data for time-invariant covariates must contain a unique customer ID and a single value for each covariate. It should be supplied as a `data.frame` or `data.table`. In the example of the apparel retailer we use demographic information "gender" as time-invariant and information on the acquisition channel as covariate for both, the purchase and the attrition process. Use the `data("apparelStaticCov")` command to load the time-invariant covariates. In this example gender is coded as a dummy variable with `male=0` and `female=1` and channel with `online=0` and `offline=1`.
```{r Cov-staticData}
data("apparelStaticCov")
apparelStaticCov
```
Data for time-varying covariates requires a time-series of covariate values for every customer. I.e. if the time-varying covariates are allowed to change every week, a value for every customer for every week is required. Note that all contextual factors are required to use the same time intervals for the time-series. In the example of the apparel retailer we use information on direct marketing (`Marekting`) as time-varying covariate. Additionally, we add gender as time-invariant contextual factors. Note that the data structure of invariant covariates needs to be aligned with the structure of time-varying covariate. Use `data("apparelDynCov")` command to load
```{r Cov-dynData}
data("apparelDynCov")
apparelDynCov
```
To add the covariates to an initialized `clvdata` object the commands `SetStaticCovariates()` and `SetDynamicCovariates()` are available. The two commands are mutually exclusive. The argument `clv.data` specifies the initialized object and the argument `data.cov.life` respectively `data.cov.trans` specifies the data source for the covariates for the attrition and the purchase process. Covariates are added separately for the purchase and the attrition process. Therefore if a covariate should affect both processes it has to be added in both arguments: `data.cov.life` *and* `data.cov.trans`. The arguments `names.cov.life` and `names.cov.trans` specify the column names of the covariates for the two processes. In our example, we use the same covariates for both processes. Accordingly, we specify the time-invariant covariates "Gender" and "Channel" as follows:
```{r Cov-setStatic}
clv.static<- SetStaticCovariates(clv.data = clv.apparel,
data.cov.life = apparelStaticCov,
data.cov.trans = apparelStaticCov,
names.cov.life = c("Gender", "Channel"),
names.cov.trans =c("Gender", "Channel"),
name.id = "Id")
```
To specify the time-varying contextual factors for seasonal patterns and direct marketing, we use the following:
```{r Cov-setDynamic, eval=FALSE, message=FALSE, warning=TRUE}
clv.dyn <- SetDynamicCovariates(clv.data = clv.apparel,
data.cov.life = apparelDynCov,
data.cov.trans = apparelDynCov,
names.cov.life = c("Marketing", "Gender", "Channel"),
names.cov.trans = c("Marketing", "Gender", "Channel"),
name.id = "Id",
name.date = "Cov.Date")
```
In order to include time-invariant covariates in a time-varying model, they may be recoded as a time-varying covariate with a constant value in every time period.
Once the covariates are added to the model the estimation process is almost identical to the standard model without covariates. The only difference is that the provided object now data for contains either time-invariant or time-varying covariates and the option to define start parameters for the covariates of both processes using the arguments `start.params.life` and `start.params.trans`. If not set, the staring values are set to 1. To define starting parameters for the covariates, the name of the corresponding factor has to be used. For example in the case of time-invariant covariates:
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface**:
We use all present covariates:
```{r static-cov-estimate-formula1, message=TRUE, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|.|., clv.static)
```
Using the formula interface, we can use only selected covariates (only Gender for the lifetime process and both, Channel and Gender for the transaction process):
```{r static-cov-estimate-formula2, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|Gender|Channel+Gender, clv.static)
```
Or we can transform covariates:
```{r, static-covariates-formula3, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(~pnbd()|Channel+Gender|I(log(Channel+2)), clv.static)
```
It is also possible to not initialize a `clvdata` object for the covariates but instead specify the covariate data directly in the model:
```{r static-covariates-formula4, warning=FALSE, eval=FALSE}
est.pnbd.static <- latentAttrition(data()~pnbd()|.|.,
data=apparelTrans, cov=apparelStaticCov)
```
Analogously, we can estimate the model containing time-varying covariates. In this example we also activate output of the optimizer in order to observe the progress.
```{r dyn-cov-formula1, eval=FALSE}
est.pnbd.dyn <- latentAttrition(~pnbd()|.|., optimx.args = list(control=list(trace=5)),
clv.dyn)
```
### **Estimating the model using non-formula interface**:
```{r static-cov-estimate, message=TRUE, warning=FALSE}
est.pnbd.static <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.life = c(Gender=0.6, Channel=0.4),
start.params.trans = c(Gender=0.6, Channel=0.4))
```
It is not possible to alter or select covariates in the non-formula interface, but, we can also estimate a model containing time-varying covariates:
```{r dyn-cov-estimate, eval=FALSE}
est.pnbd.dyn <- pnbd(clv.dyn,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.life = c(Marketing=0.5, Gender=0.6, Channel=0.4),
start.params.trans = c(Marketing=0.5, Gender=0.6, Channel=0.4),
optimx.args = list(control=list(trace=5)))
```
To inspect the estimated model we use `summary()`, however all other commands such as `print()`, `coef()`, `loglike()`, `confint()` and `vcov()` are also available. Now, output contains also parameters for the covariates for both processes. Since covariates are added separately for the purchase and the attrition process, there are also separate model parameters for the two processes. These parameters are directly interpretable as rate elasticity of the corresponding factors: A 1% change in a contextual factor $\bf{X}^{P}$ or $\bf{X}^{L}$ changes the purchase or the attrition rate by $\gamma_{purch}\bf{X}^{P}$ or $\gamma_{life}\bf{X}^{L}$ percent, respectively [@Gupta1991]. In the example of the apparel retailer, we observe that female customer purchase significantly more (`trans.Gender=1.42576`). Note, that female customers are coded as 1, male customers as 0. Also customers acquired offline (coded as Channel=1), purchase more (`trans.Channel=0.40304`) and stay longer (`life.Channel=0.9343`). Make sure to check the Karush-Kuhn-Tucker optimality conditions of the first and second order [@KKT] (KKT1 and KKT1) before interpreting the parameters. If those criteria are not met, the optimizer has probably not arrived at an optimal solution. If this is the case it is usually a good idea to rerun the estimation using alternative starting values.
```{r Cov-summary}
summary(est.pnbd.static)
```
To predict future customer behavior we use `predict()`. Note that dependent on the model, the predicted metrics may differ. For example, in the case of the Pareto/NBD model with time-varying covariates, instead of DERT, DECT is predicted. DECT only covers a finite time horizon in contrast to DERT. Time-varying covariates must be provided for the entire prediction period. If the data initially provided in the `SetDynamicCovariates()` command does not cover the complete prediction period, the argument `new.data` offers the ability to supply new data for the time-varying covariates in the from of a `clvdata` object.
## Add Correlation to the model
To relax the assumption of independence between the purchase and the attrition process, `CLVTools` provides the option to specify the argument `use.cor` when fitting the model (i.e. `pnbd`). In case of `use.cor=TRUE`, a Sarmanov approach is used to correlate the two processes. `start.param.cor` allows to optionally specify a starting value for the correlation parameter. Correlation can be added with or without covariates.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r cor-formula1, eval=FALSE}
est.pnbd.cor <- latentAttrition(~pnbd(use.cor=TRUE),
data=clv.apparel)
```
### **Estimating the model using non-formula interface:**
```{r Cov-cor, eval=FALSE}
est.pnbd.cor <- pnbd(clv.apparel,
use.cor= TRUE)
summary(est.pnbd.cor)
```
The parameter `Cor(life,trans)` is added to the parameter estimates that may be directly interpreted as a correlation. In the example of the apparel retailer the correlation parameter is not significant and the correlation is very close to zero, indicating that the purchase and the attrition process may be independent.
## Advanced Options for Covariates
`CLVTools` provides two additional estimation options for models containing covariates (time-invariant or time-varying): regularization and constraints for the parameters of the covariates. Support for this option is dependent on the model. They may be used simultaneously.
In the following we illustrate code for both, a formula-based interface a non-formula-based interface.
***Regularization*** helps to prevent overfitting of the model when using covariates. We can add regularization lambdas for the two processes. The larger the lambdas the stronger the effects of the regularization. Regularization only affects the parameters of the covariates. The use of regularization is indicated at the end of the `summary()` output.
### **Estimating the model using formula interface:**
```{r reg-formula, eval=FALSE}
est.pnbd.reg <- latentAttrition(~pnbd()|.|.|regularization(life=3, trans=8), clv.static)
summary(est.pnbd.reg)
```
### **Estimating the model using non-formula interface:**
We use the argument `reg.lambdas` to specify the lambdas for the two processes (i.e. `reg.lambdas = c(trans=100, life=100)`:
```{r reg-advOptions, eval=FALSE}
est.pnbd.reg <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
reg.lambdas = c(trans=100, life=100))
summary(est.pnbd.reg)
```
***Constraints*** implement equality constraints for contextual factors with regards to the two processes. For example the variable "gender" is forced to have the same effect on the purchase as well as on the attrition process. We can use the argument `names.cov.constr`(i.e. `names.cov.constr=c("Gender")`). In this case, the output only contains one parameter for "Gender" as it is constrained to be the same for both processes. To provide starting parameters for the constrained variable use `start.params.constr`. The use of constraints is indicated at the end of the `summary()` output.
### **Estimating the model using formula interface:**
```{r constr-formula, eval=FALSE}
est.pnbd.constr <- latentAttrition(~pnbd(names.cov.constr=c("Gender"),
start.params.constr = c(Gender = 0.6))|.|.,
clv.static)
summary(est.pnbd.constr)
```
Note: providing a starting parameter for the constrained variable is optional.
### **Estimating the model using non-formula interface:**
```{r constr-advOptions, eval=FALSE}
est.pnbd.constr <- pnbd(clv.static,
start.params.model = c(r=1, alpha = 2, s = 1, beta = 2),
start.params.constr = c(Gender=0.6),
names.cov.constr=c("Gender"))
summary(est.pnbd.constr)
```
# Customer Spending {#spending}
Customer lifetime value (CLV) is composed of three components of every customer: the future level of transactions, expected attrition behaviour (i.e. probability of being alive) and the monetary value. While probabilistic latent attrition models provide metrics for the first two components, they do not predict customer spending. To predict customer spending an additional model is required. The `CLVTools`package features the Gamma/Gamma (G/G) [@Fader2005b; @Colombo1999] model for predicting customer spending. For convenience, the `predict()` command allows to automatically predict customer spending for all latent attrition models using the option `predict.spending=TRUE` (see section [Customer Spending](#spending)). However, to provide more options and more granular insights the Gamma/Gamma model can be estimated independently. In the following, we discuss how to estimate a Gamma/Gamma model using `CLVTools`.
The general workflow remains identical. It consists of the three main steps: (1) creating a `clv.data` object containing the dataset and required meta-information, (2) fitting the model on the provided data and (3) predicting future customer purchase behavior based on the fitted model.
`CLVTools` provides two ways for evaluating spending models: you can use of the formula interface or you can use standard functions (non-formula interface). Both offer the same functionality. Through out this walkthrough, we will illustrate both options.
Reporting and plotting results is facilitated by the implementation of well-known generic methods such as `plot()`, `print()` and `summary()`.
## Load sample data provided in the package
For estimating customer spending `CLVTools` requires customers' transaction history including price. Every transaction record consists of a purchase date,customer ID and the price of the transaction. Data may be provided as `data.frame` or `data.table` [@data.table]. Currently, the Gamma/Gamma model does not allow for covariates.
We use again simulated data comparable to data from a retailer in the apparel industry. The apparel dataset is available in the `CLVTools` package. We use the `data(apparelTrans)` to load it and initialize a data object using the `clvdata()` command. For details see section [Initialize the CLV-Object](#clvdata).
```{r spending-load-data and initialize}
data("apparelTrans")
apparelTrans
clv.apparel <- clvdata(apparelTrans,
date.format="ymd",
time.unit = "week",
estimation.split = 40,
name.id = "Id",
name.date = "Date",
name.price = "Price")
```
## Estimate Model Parameters
To estimate the Gamma/Gamma spending model, we use the command `gg()` on the initialized `clvdata` object. `clv.data` specifies the initialized object prepared in the last step. Optionally, starting values for the model parameters and control settings for the optimization algorithm may be provided: The argument `start.params.model` allows to assign a vector of starting values for the optimization (i.e `c(p=1, q=2, gamma=1)` for the the Gamma/Gamma model). This is useful if prior knowledge on the parameters of the distributions are available. By default starting values are set to 1 for all parameters. The argument `optimx.args` provides an option to control settings for the optimization routine (see section [Estimate Model Parameters](#estimate)).
In line with literature, `CLVTools` does not use by default the monetary value of the first transaction to fit the model since it might be atypical of future purchases. If the first transaction should be considered the argument `remove.first.transaction` can be set to `FALSE`.
To execute the model estimation you have the choice between a formula-based interface and a non-formula-based interface. In the following we illustrate the two alternatives.
### **Estimating the model using formula interface:**
```{r spending-estimate-formula1}
est.gg <- spending(~gg(),
data=clv.apparel)
est.gg
```
Using start parameters or other additional arguments for the optimzier:
```{r spending-estimate-formula2, eval=FALSE}
est.gg <- spending(~gg(start.params.model=c(p=0.5, q=15, gamma=2)),
optimx.args = list(control=list(trace=5)),
data=clv.apparel)
```
Specify the option to NOT remove the first transaction:
```{r spending-estimate-formula3, eval=FALSE}
est.gg <- spending(~gg(remove.first.transaction=FALSE),
data=clv.apparel)
```
When using the formula interface, it is also possible to fit the model without prior specification of of a `clvdata` object:
```{r estimate-model-formula4, eval=FALSE}
est.gg <- spending(data(split=40, format=ymd, unit=w)~gg(),
data=apparelTrans)
```
### **Estimating the model using non-formula interface:**
```{r spending-estimate-model1, eval=FALSE}
est.gg<- gg(clv.data = clv.apparel)
est.gg
```
Using start parameters and other additional arguments for the optimzier:
```{r spending-estimate-model2, eval=FALSE}
est.gg<- gg(start.params.model=c(p=0.5, q=15, gamma=2), clv.data = clv.apparel)
est.gg
```
Specify the option to NOT remove the first transaction:
```{r spending-estimate-model3, eval=FALSE}
est.gg<- gg(clv.data = clv.apparel, remove.first.transaction=FALSE)
est.gg
```
## Predict Customer Spending {#predictspending}
Once the model parameters are estimated, we are able to predict future customer mean spending on an individual level. To do so, we use `predict()` on the object with the estimated parameters (i.e. `est.gg`). Note that there is no need to specify a prediction period as we predict mean spending.
In general, probabilistic spending models predict the following expected characteristic for every customer:
* predicted mean spending ("predicted.mean.spending")
If a holdout period is available additionally the true mean spending ("actual.mean.spending") during the holdout period is reported.
To use the parameter estimates on new data (e.g., an other customer cohort), the argument `newdata` optionally allows to provide a new `clvdata` object.
```{r spending-predict-model}
results.spending <- predict(est.gg)
print(results.spending)
```
## Plot Spendings
an estimated spending model object (i.e. `est.gg`) may be plotted using the `plot()` command. The plot provides a comparison of the estimated and actual density of customer spending. The argument `plot.interpolation.points` allows to adjust the number of interpolation points in density graph.
```{r spending-plot-model4, fig.height=4.40, fig.width=9}
plot(est.gg)
```
### Literature
|
/scratch/gouwar.j/cran-all/cranData/CLVTools/vignettes/CLVTools.Rmd
|
#' Generating Annual rainfall raster from IMD NetCDF file
#'
#' @param nc_data Path to the IMD rainfall NetCDF file
#' @param output_dir Directory to save the generated annual rainfall raster (Optional)
#' @param fun Aggregation function ("sum", "min", "max", "mean", "sd")(Default is "sum")
#' @param year Year for which to generate annual rainfall raster
#' @return Annual rainfall raster in GeoTIFF format
#' @examples
#' \donttest{
#' library(CLimd)
#' # Example usage:
#' nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
#' output_dir <- NULL
#' fun<-"sum"
#' year<-2022
#' # Calculate annual rainfall sum for 2022
#' annual_rainfall_sum<-AnnualRF_raster(nc_data, output_dir=NULL, fun="sum", year)
#' }
#' @references
#' 1. Pai et al. (2014). Development of a new high spatial resolution (0.25° X 0.25°)Long period (1901-2010) daily gridded rainfall data set over India and its comparison with existing data sets over the region, MAUSAM, 65(1),1-18.
#' 2. Hijmans, R. J. (2022). raster: Geographic Data Analysis and Modeling. R package version 3.5-13.
#' 3. Kumar et al. (2023). SpatGRID:Spatial Grid Generation from Longitude and Latitude List. R package version 0.1.0.
#' @export
#' @import raster
#' @import ncdf4
#' @import qpdf
#'
AnnualRF_raster <- function(nc_data, output_dir=NULL, fun="sum", year) {
# Load the NetCDF file
rs <- stack(nc_data)
# Calculate annual rainfall sum from daily data
AnnualRF<- calc(rs, fun = match.fun(fun))
# Save Annual raster (Optional)
if (!is.null(output_dir)) {
writeRaster(AnnualRF, filename = paste0(output_dir,"/", "Annual_", year, ".tif"), bylayer = TRUE, format = "GTiff", overwrite = TRUE)
}
return(AnnualRF)
}
|
/scratch/gouwar.j/cran-all/cranData/CLimd/R/AnnualRF_raster.R
|
#' Generating Monthly Rainfall Rasters from IMD NetCDF file
#'
#' @param nc_data Path to the IMD rainfall NetCDF file
#' @param output_dir Directory to save the generated monthly rainfall raster (Optional)
#' @param fun Aggregation function ("sum", "min", "max", "mean", "sd")(Default is "sum")
#' @param year Year for which to generate monthly rainfall raster
#'
#' @return A list of monthly rainfall rasters in GeoTIFF format
#' @examples
#' \donttest{
#' library(CLimd)
#' # Example usage:
#' nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
#' output_dir <- NULL
#' fun<-"sum"
#' year<-2022
#' # Calculate monthly rainfall sums for 2022
#' monthly_rainfall <-MonthRF_raster(nc_data, output_dir=NULL, fun="sum", year)
#' # Calculate monthly rainfall means for 2022
#' fun<-"mean"
#' monthly_rainfall_means <- MonthRF_raster(nc_data, output_dir=NULL, fun="mean", year)
#' }
#' @references
#' 1. Pai et al. (2014). Development of a new high spatial resolution (0.25° X 0.25°)Long period (1901-2010) daily gridded rainfall data set over India and its comparison with existing data sets over the region, MAUSAM, 65(1),1-18.
#' 2. Hijmans, R. J. (2022). raster: Geographic Data Analysis and Modeling. R package version 3.5-13.
#' 3. Kumar et al. (2023). SpatGRID:Spatial Grid Generation from Longitude and Latitude List. R package version 0.1.0.
#' @export
#' @import raster
#' @import ncdf4
#' @import qpdf
#'
MonthRF_raster <- function(nc_data, output_dir=NULL, fun="sum", year) {
# Load the NetCDF file
rs <- stack(nc_data)
# Attribute name for each raster stacked
start_date <- as.Date(paste0(year, "-01-01"))
end_date <- as.Date(paste0(year, "-12-31"))
nameindex <- seq(start_date, end_date, '1 day')
# Rename the stack
names(rs) <- nameindex
# Get the date from the names of the layers and extract the month
indices <- format(as.Date(names(rs), format = "X%Y.%m.%d"), format = "%m")
indices <- as.numeric(indices)
# Apply the specified function for monthly aggregation
MonthRF<- stackApply(rs, indices, fun = match.fun(fun))
names(MonthRF) <- month.abb
# Save monthly rasters (Optional)
if (!is.null(output_dir)) {
writeRaster(MonthRF, filename = paste0(output_dir, "/", month.abb, "_", year, ".tif"),
bylayer = TRUE, format = "GTiff", overwrite = TRUE)
}
return( MonthRF)
}
|
/scratch/gouwar.j/cran-all/cranData/CLimd/R/MonthlyRF_raster.R
|
#' Generating Seasonal rainfall rasters from IMD NetCDF file
#'
#' @param nc_data Path to the IMD rainfall NetCDF file
#' @param output_dir Directory to save the generated seasonal rainfall rasters (Optional)
#' @param fun Aggregation function ("sum", "min", "max", "mean", "sd")(Default is "sum")
#' @param year Year for which to generate seasonal rainfall raster
#'
#' @return Returns a list containing the four seasonal rasters in GeoTIFF format
#' @examples
#' \donttest{
#' library(CLimd)
#' # Example usage:
#' nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
#' output_dir <- NULL
#' fun<-"sum"
#' year<-2022
#' # Calculate seasonal rainfall sum for 2022
#' seasonal_rainfall <-SeasonalRF_raster(nc_data, output_dir=NULL, fun="sum", year)
#' }
#' @references
#' 1. Pai et al. (2014). Development of a new high spatial resolution (0.25° X 0.25°)Long period (1901-2010) daily gridded rainfall data set over India and its comparison with existing data sets over the region, MAUSAM, 65(1),1-18.
#' 2. Hijmans, R. J. (2022). raster: Geographic Data Analysis and Modeling. R package version 3.5-13.
#' 3. Kumar et al. (2023). SpatGRID:Spatial Grid Generation from Longitude and Latitude List. R package version 0.1.0.
#' @export
#' @import raster
#' @import ncdf4
#' @import qpdf
#'
SeasonalRF_raster <- function(nc_data, output_dir=NULL, fun="sum", year) {
# Load the NetCDF file
rs <- stack(nc_data)
# Attribute name for each raster stacked
start_date <- as.Date(paste0(year, "-01-01"))
end_date <- as.Date(paste0(year, "-12-31"))
nameindex <- seq(start_date, end_date, '1 day')
# Rename the stack
names(rs) <- nameindex
# Get the date from the names of the layers and extract the month
indices <- format(as.Date(names(rs), format = "X%Y.%m.%d"), format = "%m")
indices <- as.numeric(indices)
# Apply the specified function for monthly aggregation
MonthRF<- stackApply(rs, indices, fun = match.fun(fun))
names(MonthRF) <- month.abb
# Extract layers for Winter Season (January and February)
Winter_stack<-stack(MonthRF$Jan,MonthRF$Feb)
# Calculate seasonal rainfall
Winter<-calc(Winter_stack, fun = match.fun(fun))
# Extract layers for PreMonsoon Season (March, April, May)
PreMonsoon_stack<-stack(MonthRF$Mar,MonthRF$Apr,MonthRF$May)
# Calculate seasonal rainfall
PreMonsoon<-calc(PreMonsoon_stack, fun = match.fun(fun))
# Extract layers for SWMonsoon Season (June to September)
SWMonsoon_stack<-stack(MonthRF$Jun,MonthRF$Jul,MonthRF$Aug,MonthRF$Sep)
# Calculate seasonal rainfall
SWMonsoon<-calc(SWMonsoon_stack, fun = match.fun(fun))
# Extract layers for Post_monsoon Season (October to December)
PostMonsoon_stack<-stack(MonthRF$Oct,MonthRF$Nov,MonthRF$Dec)
# Calculate seasonal rainfall
PostMonsoon<-calc(PostMonsoon_stack, fun = match.fun(fun))
# Save seasonal rasters (optional)
if (!is.null(output_dir)) {
seasons <- c("Winter", "PreMonsoon", "SWMonsoon", "PostMonsoon")
for (season in seasons) {
filename <- paste0(output_dir, "/", season, "_", year, ".tif")
writeRaster(get(season), filename = filename, format = "GTiff", overwrite = TRUE)
}
}
return(list(Winter = Winter, PreMonsoon = PreMonsoon, SWMonsoon = SWMonsoon, PostMonsoon = PostMonsoon))
}
|
/scratch/gouwar.j/cran-all/cranData/CLimd/R/SeasonalRF_raster.R
|
#' Generating weekly rainfall rasters from IMD NetCDF file
#'
#' @param nc_data Path to the IMD rainfall NetCDF file
#' @param output_dir Directory to save the generated weekly rainfall rasters (Optional)
#' @param fun Aggregation function ("sum", "min", "max", "mean", "sd")(Default is "sum")
#' @param year Year for which to generate weekly rainfall raster
#'
#' @return A list of weekly rainfall rasters in GeoTIFF format
#' @examples
#' \donttest{
#' library(CLimd)
#' # Example usage:
#' nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
#' output_dir <- NULL
#' fun<-"sum"
#' year<-2022
#' # Calculate weekly rainfall sum for 2022
#' weekly_rainfall_sum <-WeeklyRF_raster(nc_data, output_dir=NULL, fun="sum", year)
#' }
#' @references
#' 1. Pai et al. (2014). Development of a new high spatial resolution (0.25° X 0.25°)Long period (1901-2010) daily gridded rainfall data set over India and its comparison with existing data sets over the region, MAUSAM, 65(1),1-18.
#' 2. Hijmans, R. J. (2022). raster: Geographic Data Analysis and Modeling. R package version 3.5-13.
#' 3. Kumar et al. (2023). SpatGRID:Spatial Grid Generation from Longitude and Latitude List. R package version 0.1.0.
#' @export
#' @import raster
#' @import ncdf4
#' @import qpdf
#'
WeeklyRF_raster <- function(nc_data, output_dir=NULL, fun="sum", year) {
# Load the NetCDF file
rs <- stack(nc_data)
# Extract the dates from the band names as integer
x<-as.integer(substr(names(rs), 2, 6))
# Convert them as date with origin of 31st December, 1900
x1 = as.Date(x, origin=as.Date("1900-12-31"))
# Convert them as week numbers
x2<- strftime(x1, format = "%V")
# Get first 7 days as list
z1<- x2[c(1:7)]
# Identify initial days with week number 52 of previous year
z2<- z1[z1 %in% c("52", "53")]
# Remove initial days with week number 52 of previous year from the main list
x3<- x2[-(1:length(z2))]
# Prefix "Week" to the name list
x3.1 <- paste("Week", x3)
# Drop initial layers with week number 52 of previous year
rs2<- dropLayer(rs, (1:length(z2)))
# Rename the stack layers
names(rs2)<- x3.1
# Get weekly sum of rasters
WeeklyRF<- stackApply(rs2, x3.1, fun = match.fun(fun))
# Rename
x4<-(substr(names(WeeklyRF), 7, 13))
names(WeeklyRF)<- x4
# Save weekly rasters (Optional)
if (!is.null(output_dir)) {
writeRaster(WeeklyRF, filename = paste0(output_dir,"/", "Weekly_", year, ".tif"), bylayer = TRUE, format = "GTiff", overwrite = TRUE)
}
return(WeeklyRF)
}
|
/scratch/gouwar.j/cran-all/cranData/CLimd/R/WeeklyRF_raster.R
|
## -----------------------------------------------------------------------------
### Installation and loading the library of CLimd R package
# You can install the CLimd package from CRAN using the following command:
# install.packages("CLimd")
# Once installed, you can load the package using
library(CLimd)
### Generating Monthly Rainfall Rasters from IMD NetCDF Data
# The "MonthRF_raster" function generates the monthly rainfall rasters.
# Example:
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
# nc_data: Path to the IMD NetCDF rainfall file.
# output_dir: Directory to save the generated rasters. (Optional)
# fun: Aggregation function ("sum", "min", "max", "mean", "sd").
# year: Year for which to generate monthly rasters.
# Calculate monthly rainfall sum for the year 2022
MonthRF<-MonthRF_raster(nc_data, output_dir=NULL, fun="sum", year)
MonthRF
### This creates a list of 12 rasters, one for each month in 2022. Each raster provides a detailed snapshot of rainfall distribution for that specific month. You can visualize these rasters using the plot function to gain insights into monthly trends and variations in rainfall patterns
# plot(MonthRF[[1]]) # Plot the first layer (Jan)
# plot(MonthRF) # Plot all layers (Jan to Dec) as a multi-panel display
### Generating Weekly Rainfall Rasters from IMD NetCDF Data
# The "WeeklyRF_raster" function generates weekly rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
WeekRF<-WeeklyRF_raster(nc_data, output_dir=NULL, fun="sum", year)
WeekRF
### This creates a list of 52 rasters, one for each week in 2022. You can visualize them using the plot function to explore rainfall dynamics at a weekly scale.
# plot(WeekRF)
# plot(WeekRF[[45:52]])
### Generating Seasonal Rainfall Rasters from IMD NetCDF Data
# According to the IMD, four prominent seasons namely (i) Winter (December-February), (ii) Pre-Monsoon (March–May), (iii) Monsoon (June-September), and (iv) Post-Monsoon (October-November) are dominant in India.
# The "SeasonalRF_raster" function generates seasonal rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
SeasonalRF<-SeasonalRF_raster(nc_data, output_dir=NULL, fun="sum", year)
SeasonalRF
### This creates a set of 4 rasters representing the four seasons (Winter, Pre-Monsoon, Monsoon, and Post-Monsoon) of 2022. Visualize them using the plot function to uncover seasonal rainfall patterns and their impacts
# plot(SeasonalRF$Winter)
# plot(SeasonalRF$PreMonsoon)
# plot(SeasonalRF$SWMonsoon)
# plot(SeasonalRF$PostMonsoon)
### Generating Annual Rainfall Raster from IMD NetCDF Data
# The "AnnualRF_raster" function generates annual rainfall raster. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
AnnualRF<-AnnualRF_raster(nc_data, output_dir=NULL, fun="sum", year)
AnnualRF
### This generates a single raster summarizing the total rainfall for the entire year 2022. Plot this raster to visualize the overall rainfall distribution and identify areas of high and low precipitation.
# plot(AnnualRF)
|
/scratch/gouwar.j/cran-all/cranData/CLimd/inst/doc/CLimd.R
|
---
title: "CLimd: Generating Rainfall Rasters from IMD NetCDF Data"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{CLimd: Generating Rainfall Rasters from IMD NetCDF Data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
---
Authors - Nirmal Kumar, Nobin Chandra Paul and G.P. Obi Reddy
---
## Welcome to the CLimd vignette
***<br/>
*This vignette will guide users through the features and functionalities of the CLimd package, which allows users to convert the IMD NetCDF rainfall data into raster maps for various temporal scales,facilitating spatial-temporal trend analysis.*
***<br/>
## Introduction
****<br/>
*The developed function is a comprehensive tool for the analysis of India Meteorological Department (IMD) NetCDF rainfall data. Specifically designed to process high-resolution daily gridded rainfall datasets. It provides four key functions to process IMD NetCDF rainfall data and create rasters for various temporal scales, including annual, seasonal, monthly, and weekly rainfall.It supports different aggregation methods, such as sum, min, max, mean, and standard deviation. These functions are designed for spatial-temporal analysis of rainfall patterns, trend analysis, geo-statistical modeling of rainfall variability, identifying rainfall anomalies and extreme events and can be an input for hydrological and agricultural models.*
****<br/>
``` {r}
### Installation and loading the library of CLimd R package
# You can install the CLimd package from CRAN using the following command:
# install.packages("CLimd")
# Once installed, you can load the package using
library(CLimd)
### Generating Monthly Rainfall Rasters from IMD NetCDF Data
# The "MonthRF_raster" function generates the monthly rainfall rasters.
# Example:
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
# nc_data: Path to the IMD NetCDF rainfall file.
# output_dir: Directory to save the generated rasters. (Optional)
# fun: Aggregation function ("sum", "min", "max", "mean", "sd").
# year: Year for which to generate monthly rasters.
# Calculate monthly rainfall sum for the year 2022
MonthRF<-MonthRF_raster(nc_data, output_dir=NULL, fun="sum", year)
MonthRF
### This creates a list of 12 rasters, one for each month in 2022. Each raster provides a detailed snapshot of rainfall distribution for that specific month. You can visualize these rasters using the plot function to gain insights into monthly trends and variations in rainfall patterns
# plot(MonthRF[[1]]) # Plot the first layer (Jan)
# plot(MonthRF) # Plot all layers (Jan to Dec) as a multi-panel display
### Generating Weekly Rainfall Rasters from IMD NetCDF Data
# The "WeeklyRF_raster" function generates weekly rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
WeekRF<-WeeklyRF_raster(nc_data, output_dir=NULL, fun="sum", year)
WeekRF
### This creates a list of 52 rasters, one for each week in 2022. You can visualize them using the plot function to explore rainfall dynamics at a weekly scale.
# plot(WeekRF)
# plot(WeekRF[[45:52]])
### Generating Seasonal Rainfall Rasters from IMD NetCDF Data
# According to the IMD, four prominent seasons namely (i) Winter (December-February), (ii) Pre-Monsoon (March–May), (iii) Monsoon (June-September), and (iv) Post-Monsoon (October-November) are dominant in India.
# The "SeasonalRF_raster" function generates seasonal rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
SeasonalRF<-SeasonalRF_raster(nc_data, output_dir=NULL, fun="sum", year)
SeasonalRF
### This creates a set of 4 rasters representing the four seasons (Winter, Pre-Monsoon, Monsoon, and Post-Monsoon) of 2022. Visualize them using the plot function to uncover seasonal rainfall patterns and their impacts
# plot(SeasonalRF$Winter)
# plot(SeasonalRF$PreMonsoon)
# plot(SeasonalRF$SWMonsoon)
# plot(SeasonalRF$PostMonsoon)
### Generating Annual Rainfall Raster from IMD NetCDF Data
# The "AnnualRF_raster" function generates annual rainfall raster. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
AnnualRF<-AnnualRF_raster(nc_data, output_dir=NULL, fun="sum", year)
AnnualRF
### This generates a single raster summarizing the total rainfall for the entire year 2022. Plot this raster to visualize the overall rainfall distribution and identify areas of high and low precipitation.
# plot(AnnualRF)
```
|
/scratch/gouwar.j/cran-all/cranData/CLimd/inst/doc/CLimd.Rmd
|
---
title: "CLimd: Generating Rainfall Rasters from IMD NetCDF Data"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{CLimd: Generating Rainfall Rasters from IMD NetCDF Data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
---
Authors - Nirmal Kumar, Nobin Chandra Paul and G.P. Obi Reddy
---
## Welcome to the CLimd vignette
***<br/>
*This vignette will guide users through the features and functionalities of the CLimd package, which allows users to convert the IMD NetCDF rainfall data into raster maps for various temporal scales,facilitating spatial-temporal trend analysis.*
***<br/>
## Introduction
****<br/>
*The developed function is a comprehensive tool for the analysis of India Meteorological Department (IMD) NetCDF rainfall data. Specifically designed to process high-resolution daily gridded rainfall datasets. It provides four key functions to process IMD NetCDF rainfall data and create rasters for various temporal scales, including annual, seasonal, monthly, and weekly rainfall.It supports different aggregation methods, such as sum, min, max, mean, and standard deviation. These functions are designed for spatial-temporal analysis of rainfall patterns, trend analysis, geo-statistical modeling of rainfall variability, identifying rainfall anomalies and extreme events and can be an input for hydrological and agricultural models.*
****<br/>
``` {r}
### Installation and loading the library of CLimd R package
# You can install the CLimd package from CRAN using the following command:
# install.packages("CLimd")
# Once installed, you can load the package using
library(CLimd)
### Generating Monthly Rainfall Rasters from IMD NetCDF Data
# The "MonthRF_raster" function generates the monthly rainfall rasters.
# Example:
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
# nc_data: Path to the IMD NetCDF rainfall file.
# output_dir: Directory to save the generated rasters. (Optional)
# fun: Aggregation function ("sum", "min", "max", "mean", "sd").
# year: Year for which to generate monthly rasters.
# Calculate monthly rainfall sum for the year 2022
MonthRF<-MonthRF_raster(nc_data, output_dir=NULL, fun="sum", year)
MonthRF
### This creates a list of 12 rasters, one for each month in 2022. Each raster provides a detailed snapshot of rainfall distribution for that specific month. You can visualize these rasters using the plot function to gain insights into monthly trends and variations in rainfall patterns
# plot(MonthRF[[1]]) # Plot the first layer (Jan)
# plot(MonthRF) # Plot all layers (Jan to Dec) as a multi-panel display
### Generating Weekly Rainfall Rasters from IMD NetCDF Data
# The "WeeklyRF_raster" function generates weekly rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
WeekRF<-WeeklyRF_raster(nc_data, output_dir=NULL, fun="sum", year)
WeekRF
### This creates a list of 52 rasters, one for each week in 2022. You can visualize them using the plot function to explore rainfall dynamics at a weekly scale.
# plot(WeekRF)
# plot(WeekRF[[45:52]])
### Generating Seasonal Rainfall Rasters from IMD NetCDF Data
# According to the IMD, four prominent seasons namely (i) Winter (December-February), (ii) Pre-Monsoon (March–May), (iii) Monsoon (June-September), and (iv) Post-Monsoon (October-November) are dominant in India.
# The "SeasonalRF_raster" function generates seasonal rainfall rasters. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
SeasonalRF<-SeasonalRF_raster(nc_data, output_dir=NULL, fun="sum", year)
SeasonalRF
### This creates a set of 4 rasters representing the four seasons (Winter, Pre-Monsoon, Monsoon, and Post-Monsoon) of 2022. Visualize them using the plot function to uncover seasonal rainfall patterns and their impacts
# plot(SeasonalRF$Winter)
# plot(SeasonalRF$PreMonsoon)
# plot(SeasonalRF$SWMonsoon)
# plot(SeasonalRF$PostMonsoon)
### Generating Annual Rainfall Raster from IMD NetCDF Data
# The "AnnualRF_raster" function generates annual rainfall raster. Example:
library(CLimd)
nc_data <- system.file("extdata", "imd_RF_2022.nc", package = "CLimd")
output_dir <- NULL
fun<-"sum"
year<-2022
AnnualRF<-AnnualRF_raster(nc_data, output_dir=NULL, fun="sum", year)
AnnualRF
### This generates a single raster summarizing the total rainfall for the entire year 2022. Plot this raster to visualize the overall rainfall distribution and identify areas of high and low precipitation.
# plot(AnnualRF)
```
|
/scratch/gouwar.j/cran-all/cranData/CLimd/vignettes/CLimd.Rmd
|
#' CMAPSS data set
#'
#' Commercial Modular Aero-Propulsion System Simulation (C-MAPSS) Data Set.
#'
#' @author Morteza Amini, \email{morteza.amini@@ut.ac.ir}, Afarin Bayat, \email{aftbayat@@gmail.com}
#'
#' @usage data("CMAPSS")
#'
#' @format A list of the following 2 objects:
#' \itemize{
#' \item \code{train}{ a list of class "hhsmm.data" as the train dataset}
#' \item \code{test}{ a list of class "hhsmm.data" as the test dataset}
#' \item \code{subsets}{ a matrix containig the number of units in each subset of the CMAPSS data set (FD001-FD004) for the train and test datasets}
#' }
#'
#' @details
#' The turbofan engine data is from the Prognostic Center of Excellence
#' (PCoE) of NASA Ames Research Center, which is simulated by the Commercial Modular Aero-Propulsion
#' System Simulation (C-MAPSS). Only 14 out of 21 variables, by a method mentioned by Li, et al. (2019)
#' are selected. The \code{train} and \code{test} lists are of class \code{"hhsmm.data"}, which is used
#' in the \code{hhsmm} package.
#' @references
#' Frederick, D. K., DeCastro, J. A., & Litt, J. S. (2007). User's guide for the commercial modular aero-propulsion system simulation (C-MAPSS).
#'
#' Saxena, A., Goebel, K., Simon, D., & Eklund, N. (2008, October). Damage propagation modeling for aircraft engine run-to-failure simulation. In \emph{2008 international conference on prognostics and health management} (pp. 1-9). IEEE.
#'
#' Li, J., Li, X., & He, D. (2019). A directed acyclic graph network combined with CNN and LSTM for remaining useful life prediction. \emph{IEEE Access}, 7, 75464-75475.
#'
#' @examples
#' data(CMAPSS)
#' str(CMAPSS$train)
#' str(CMAPSS$test)
#' CMAPSS$subsets
#' @keywords datasets
#'
"CMAPSS"
|
/scratch/gouwar.j/cran-all/cranData/CMAPSS/R/CMAPSS.R
|
#' Collective Matrix Factorization (CMF)
#'
#' Collective matrix factorization (CMF) finds joint low-rank
#' representations for a collection of matrices with shared
#' row or column entities. This package learns a variational
#' Bayesian approximation for CMF, supporting multiple
#' likelihood potentials and missing data, while identifying
#' both factors shared by multiple matrices and factors
#' private for each matrix.
#'
#' This package implements a variational Bayesian approximation for
#' CMF, following the presentation in "Group-sparse embeddings in
#' collective matrix factorization" (see references below).
#'
#' The main functionality is provided by the function
#' [CMF()] that is used for learning the model, and by the
#' function [predictCMF()] that estimates missing entries
#' based on the learned model. These functions take as input
#' lists of matrices in a specific sparse format that stores
#' only the observed entries but that explicitly stores
#' zeroes (unlike most sparse matrix representations).
#' For converting between regular matrices and this sparse
#' format see [matrix_to_triplets()] and [triplets_to_matrix()].
#'
#' The package can also be used to learn Bayesian canonical
#' correlation analysis (CCA) and group factor analysis (GFA)
#' models, both of which are special cases of CMF. This is likely to be
#' useful for people looking for CCA and GFA solutions supporting
#' missing data and non-Gaussian likelihoods.
#'
#' @author Arto Klami \email{arto.klami@@cs.helsinki.fi} and Lauri Väre
#'
#' Maintainer: Felix Held \email{felix.held@@gmail.se}
#'
#' @references
#' Arto Klami, Guillaume Bouchard, and Abhishek Tripathi.
#' Group-sparse embeddings in collective matrix factorization.
#' arXiv:1312.5921, 2013.
#'
#' Arto Klami, Seppo Virtanen, and Samuel Kaski.
#' Bayesian canonical correlation analysis. Journal of Machine
#' Learning Research, 14(1):965--1003, 2013.
#'
#' Seppo Virtanen, Arto Klami, Suleiman A. Khan, and Samuel Kaski.
#' Bayesian group factor analysis. In Proceedings of the 15th
#' International Conference on Artificial Intelligence and Statistics,
#' volume 22 of JMLR:W&CP, pages 1269-1277, 2012.
#'
#' @examples
#' require("CMF")
#'
#' # Create data for a circular setup with three matrices and three
#' # object sets of varying sizes.
#' X <- list()
#' D <- c(10, 20, 30)
#' inds <- matrix(0, nrow = 3, ncol = 2)
#'
#' # Matrix 1 is between sets 1 and 2 and has continuous data
#' inds[1, ] <- c(1, 2)
#' X[[1]] <- matrix(
#' rnorm(D[inds[1, 1]] * D[inds[1, 2]], 0, 1),
#' nrow = D[inds[1, 1]]
#' )
#'
#' # Matrix 2 is between sets 1 and 3 and has binary data
#' inds[2, ] <- c(1, 3)
#' X[[2]] <- matrix(
#' round(runif(D[inds[2, 1]] * D[inds[2, 2]], 0, 1)),
#' nrow = D[inds[2, 1]]
#' )
#'
#' # Matrix 3 is between sets 2 and 3 and has count data
#' inds[3, ] <- c(2, 3)
#' X[[3]] <- matrix(
#' round(runif(D[inds[3, 1]] * D[inds[3, 2]], 0, 6)),
#' nrow = D[inds[3, 1]]
#' )
#'
#' # Convert the data into the right format
#' triplets <- lapply(X, matrix_to_triplets)
#'
#' # Missing entries correspond to missing rows in the triple representation
#' # so they can be removed from training data by simply taking a subset
#' # of the rows.
#' train <- list()
#' test <- list()
#' keep_for_training <- c(100, 200, 300)
#' for (m in 1:3) {
#' subset <- sample(nrow(triplets[[m]]), keep_for_training[m])
#' train[[m]] <- triplets[[m]][subset, ]
#' test[[m]] <- triplets[[m]][-subset, ]
#' }
#'
#' # Learn the model with the correct likelihoods
#' K <- 4
#' likelihood <- c("gaussian", "bernoulli", "poisson")
#' opts <- getCMFopts()
#' opts$iter.max <- 500 # Less iterations for faster computation
#' model <- CMF(train, inds, K, likelihood, D, test = test, opts = opts)
#'
#' # Check the predictions
#' # Note that the data created here has no low-rank structure,
#' # so we should not expect good accuracy.
#' print(test[[1]][1:3, ])
#' print(model$out[[1]][1:3, ])
#'
#' # predictions for the test set using the previously learned model
#' out <- predictCMF(test, model)
#' print(out$out[[1]][1:3, ])
#' print(out$error[[1]])
#' # ...this should be the same as the output provided by CMF()
#' print(model$out[[1]][1:3, ])
#'
#' @docType package
#' @name CMF-package
#' @useDynLib CMF, .registration = TRUE
NULL
#' Default options for CMF
#'
#' A helper function that creates a list of options to be passed to `CMF`.
#' To run the code with other option values, first run this function and
#' then directly modify the entries before passing the list to `CMF`.
#'
#' Most of the parameters are for controlling the optimization, but some will
#' alter the model itself. In particular, `useBias` is used for turning
#' the bias terms on and off, and `method` will change the prior for `U`.
#'
#' The default choice for `method` is `"gCMF"`, providing the
#' group-wise sparse CMF that identifies both shared and private factors
#' (see Klami et al. (2013) for details). The value `"CMF"` turns off
#' the group-wise sparsity, providing a CMF solution that attempts to learn
#' only factors shared by all matrices. Finally, `method="GFA"` implements
#' the group factor analysis (GFA) method, by fixing the variance of
#' `U[[1]]` to one and forcing `useBias=FALSE`. Then `U[[1]]` can be
#' interpreted as latent variables with unit variance and zero mean,
#' as assumed by GFA and CCA (special case of GFA with `M = 2`). Note that as a
#' multi-view learning method `"GFA"` requires all matrices to share the
#' same rows, the very first entity set.
#'
#' @return Returns a list of:
#' \item{init.tau}{Initial value for the noise precisions. Only matters for
#' Gaussian likelihood.}
#' \item{init.alpha}{Initial value for the automatic relevance determination
#' (ARD) prior precisions.}
#' \item{grad.reg }{The regularization parameter for the under-relaxed Newton
#' iterations. 0 = no regularization, larger values provide
#' increasing regularization. The value must be below 1.}
#' \item{gradIter}{How many gradient steps for updating the projections are
#' performed during each iteration of the whole algorithm.
#' Default is 1.}
#' \item{grad.max}{Maximum absolute change for the elements of the projection
#' matrices during one gradient step. Small values help to
#' prevent over-shooting, wheres inf results to no constraints.
#' Default is `inf`.}
#' \item{iter.max }{Number of iterations for the whole algorithm.}
#' \item{computeCost}{Should the cost function values be computed or not.
#' Defaults to `TRUE`.}
#' \item{verbose}{0 = supress all printing, 1 = print current iteration and
#' test RMSE every now and then, 2 = in addition to level 1
#' print also the current gradient norm.}
#' \item{useBias}{Set this to `FALSE` to exclude the row and column bias terms.
#' The default is `TRUE`.}
#' \item{method}{Default value of "gCMF" computes the CMF with group-sparsity.
#' The other possible values are "CMF" for turning off the
#' group-sparsity prior, and "GFA" for implementing group factor
#' analysis (and canonical correlation analysis when `M = 2`).}
#' \item{prior.alpha_0}{Hyperprior values for the gamma prior for ARD.}
#' \item{prior.alpha_0t}{Hyperprior values for the gamma prior for tau.}
#' @author Arto Klami and Lauri Väre
#' @seealso 'CMF'
#' @references
#' Arto Klami, Guillaume Bouchard, and Abhishek Tripathi.
#' Group-sparse embeddings in collective matrix factorization.
#' arXiv:1312.5921, 2014.
#'
#' Seppo Virtanen, Arto Klami, Suleiman A. Khan, and Samuel Kaski.
#' Bayesian group factor analysis. In Proceedings of the 15th
#' International Conference on Artificial Intelligence and Statistics,
#' volume 22 of JMLR:W&CP, pages 1269-1277, 2012.
#' @examples
#'
#' CMF_options <- getCMFopts()
#' CMF_options$iter.max <- 500 # Change the number of iterations from default
#' # of 200 to 500.
#' CMF_options$useBias <- FALSE # Do not take row and column means into
#' # consideration.
#' # These options will be in effect when CMF_options is passed on to CMF.
#'
#' @export
getCMFopts <- function() {
# Initial value for the noise precisions (only matters for
# Gaussian likelihood)
init.tau <- 10
# Initial value for the prior precisions
init.alpha <- 5
# Parameters for the gradient optimization of the projection
# matrices.
# The algorithm is Newton-Raphson with diagonal Hessian
# and successive under-relaxation (= Richardson extrapolation),
# so that
# theta_new = grad.reg*theta_old + (1-grad.reg)(theta_old - g/h)
# where g is gradient and h is Hessian. grad.reg should be between 0 and 1
# to stabilize the algorithm. 0 overshoots, 1 does not update anything.
#
# If grad.max < Inf, the step lengths are capped at grad.Max
# grad.iter tells how many gradient steps to take within each update.
grad.reg <- 0.7
grad.iter <- 1
grad.max <- Inf
# Parameters for controlling when the algorithm stops.
iter.max <- 200
computeCost <- TRUE
verbose <- 1 # 1=print progress every now and then, 0=supress all printing
useBias <- TRUE # Whether to include bias terms;
# useBias = FALSE means no bias terms
# Whether to do GFA/CCA instead of CMF
# If this is set to "GFA" then useBias=FALSE and alpha is set to one for
# the first entity set, so that U[[1]] become latent variables with zero mean
# and unit variance.
# It this is set fo "CMF" the alpha-parameter becomes the same for all
# matrices.
method <- "gCMF"
# Hyperparameters
# - alpha_0, beta_0 for the ARD precisions
# - alpha_0t, beta_0t for the residual noise predictions
prior.alpha_0 <- prior.beta_0 <- 1
prior.alpha_0t <- prior.beta_0t <- 0.001
return(list(
init.tau = init.tau,
init.alpha = init.alpha,
grad.iter = grad.iter,
iter.max = iter.max,
verbose = verbose,
computeCost = computeCost,
grad.reg = grad.reg,
grad.max = grad.max,
useBias = useBias,
method = method,
prior.alpha_0 = prior.alpha_0,
prior.beta_0 = prior.beta_0,
prior.alpha_0t = prior.alpha_0t,
prior.beta_0t = prior.beta_0t
))
}
#' Predict with CMF
#'
#' Code for predicting missing elements with an existing CMF model.
#' The predictions are made for all of the elements specified in the list of
#' input matrices `X`. The function also returns the root mean square error
#' (RMSE) between the predicted outputs and the values provided in `X`.
#'
#' Note that `X` needs to be provided as a set of triplets instead of as
#' a regular matrix. See [matrix_to_triplets()].
#'
#' @param X A list of sparse matrices specifying the indices for which to
#' make the predictions.
#' These matrices must correspond to the structure used for `X`
#' when learning the model with `CMF`.
#' @param model A list of model parameter values provided by `CMF`.
#' @return A list of
#' \item{out}{A list of matrices corresponding to predictions for each
#' matrix in `X`.}
#' \item{error}{A vector containing the root-mean-square error for each
#' matrix separately.}
#'
#' @author Arto Klami and Lauri Väre
#' @examples
#'
#' # See CMF-package for an example.
#'
#' @export
predictCMF <- function(X, model) {
D <- model$D
inds <- model$inds
for (i in seq_along(X)) {
if(!p_check_sparsity(
X[[i]], D[inds[i, 1]], D[inds[i, 2]])) {
stop(paste0("Input matrix ", i, " is not in the correct format."))
}
}
out <- list()
for (m in 1:model$M) {
indices <- matrix(as.integer(X[[m]][, 1:2]), ncol = 2)
xi <- p_updatePseudoData(
indices, model$U[[inds[m, 1]]], model$U[[inds[m, 2]]],
model$bias[[m]]$row$mu, model$bias[[m]]$col$mu
)
out[[m]] <- unname(cbind(indices, xi))
}
for (m in which(model$likelihood == "bernoulli")) {
out[[m]][, 3] <- exp(out[[m]][, 3])
out[[m]][, 3] <- out[[m]][, 3] / (1 + out[[m]][, 3])
}
for (m in which(model$likelihood == "poisson")) {
out[[m]][, 3] <- exp(out[[m]][, 3])
out[[m]][, 3] <- log(1 + out[[m]][, 3])
}
error <- rep(0, length(X))
for (m in seq_along(X)) {
for (r in seq_len(nrow(X[[m]]))) {
error[m] <- error[m] + (X[[m]][r, 3] - out[[m]][r, 3])^2
}
error[m] <- sqrt(error[m] / nrow(X[[m]]))
}
return(list(out = out, error = error))
}
#' Collective Matrix Factorization
#'
#' Learns the CMF model for a given collection of M matrices.
#' The code learns the parameters of a variational approximation for CMF,
#' and also computes predictions for indices specified in `test`.
#'
#' The variational approximation is fully factorized over all of the model
#' parameters, including individual elements of the projection matrices.
#' The parameters for the projection matrices are updated jointly by
#' Newton-Raphson method, whereas the rest use closed-form updates.
#'
#' Note that the input data needs to be given in a specific sparse format.
#' See [matrix_to_triplets()] for details.
#'
#' The behavior of the algorithm can be modified via the `opts` parameter.
#' See [getCMFopts()] for details. Of particular interest are the elements
#' `useBias` and `method`.
#'
#' For full description of the output parameters, see the referred publication.
#' The notation in the code follows roughly the notation used in the paper.
#'
#' @param X List of input matrices.
#' @param inds A `length(X)` times 2 matrix that links dimensions of the
#' matrices in `X` to object sets. `inds[m, 1]` tells which
#' object set corresponds to the rows in matrix `X[[m]]`,
#' and `inds[m, 2]` tells the same for the columns.
#' @param K The number of factors.
#' @param opts A list of options as given by [getCMFopts()].
#' If set to `NULL`, the default values will be used.
#' @param likelihood A list of likelihood choices, one for each matrix in X.
#' Each entry should be a string with possible values of:
#' "gaussian", "bernoulli" or "poisson".
#' @param D A vector containing sizes of each object set.
#' @param test A list of test matrices. If not NULL, the code will compute
#' predictions for these elements of the matrices. This duplicates
#' the functionality of [predictCMF()].
#' @return A list of
#' \item{U}{A list of the mean parameters for the rank-K projection matrices,
#' one for each object set.}
#' \item{covU}{A list of the variance parameters for the rank-K projection
#' matrices, one for each object set.}
#' \item{tau}{A vector of the precision parameter means.}
#' \item{alpha}{A vector of the ARD parameter means.}
#' \item{cost}{A vector of variational lower bound values.}
#' \item{inds}{The input parameter `inds` stored for further use.}
#' \item{errors}{A vector containing root-mean-square errors for each
#' iteration, computed over the elements indicated by the
#' `test` parameter.}
#' \item{bias}{A list (of lists) storing the parameters of the row and
#' column bias terms.}
#' \item{D}{The sizes of the object sets as given in the parameters.}
#' \item{K}{The number of components as given in the parameters.}
#' \item{Uall}{Matrices of U joined into one sum(D) by K matrix, for
#' easier plotting of the results.}
#' \item{items}{A list containing the running number for each item among
#' all object sets. This corresponds to rows of the `Uall`
#' matrix. Each part of the list contains a vector that has the
#' numbers for each particular object set.}
#' \item{out}{If test matrices were provided, returns the reconstructed data
#' sets. Otherwise returns `NULL`.}
#' \item{M}{The number of input matrices.}
#' \item{likelihood}{The likelihoods of the matrices.}
#' \item{opts}{The options used for running the code.}
#' @author Arto Klami and Lauri Väre
#' @references
#' Arto Klami, Guillaume Bouchard, and Abhishek Tripathi.
#' Group-sparse embeddings in collective matrix factorization.
#' arXiv:1312.5921, 2014.
#' @examples
#' # See CMF-package for an example.
#'
#' @importFrom stats rnorm
#' @export
CMF <- function(X, inds, K, likelihood, D, test = NULL, opts = NULL) {
if (is.null(opts)) {
opts <- getCMFopts()
}
for (i in seq_along(X)) {
if (!p_check_sparsity(X[[i]], D[inds[i, 1]], D[inds[i, 2]])) {
stop(paste0("Input matrix ", i, " is not in the correct format."))
}
}
# Store indices separately as integers
indices <- lapply(X, function(x) matrix(as.integer(x[, 1:2]), ncol = 2))
if (opts$method == "GFA") {
opts$useBias <- FALSE
if (!all(inds[, 1] == 1)) {
stop(paste0(
"GFA requires all matrices to share the first entity set, ",
"since it is a multi-view learning method."
))
}
}
# Construct the index sets and the symmetric matrix
#
# X are lists of observed values
# M is the number of data sets
# C is the number of itemsets
# D[i] is the size of the c-th itemset
# items[[inds[m, 1]]] tells which samples correspond to rows in X[m]
# and items[[inds[m, 2]]] is the same for columns
M <- length(X)
indvec <- as.vector(inds)
types <- seq_len(max(indvec))
C <- max(types)
items <- list()
N <- 0
for (t in types) {
count <- D[t]
items[[t]] <- N + seq_len(count)
N <- N + count
}
alpha_0 <- opts$prior.alpha_0 # Easier access for hyperprior values
beta_0 <- opts$prior.beta_0
alpha_0t <- opts$prior.alpha_0t
beta_0t <- opts$prior.beta_0t
# ARD and noise parameters
alpha <- matrix(opts$init.alpha, C, K) # The mean of the ARD precisions
b_ard <- matrix(0, C, K) # The parameters of the Gamma
# distribution
a_ard <- alpha_0 + D / 2 # for ARD precisions
tau <- rep(opts$init.tau, M) # The mean noise precisions
a_tau <- rep(alpha_0t, M) # The parameters of the Gamma
# distribution
for (m in seq_len(M)) {
a_tau[m] <- a_tau[m] + nrow(X[[m]]) / 2
}
b_tau <- rep(0, M) # for the noise precisions
# The projections
U <- vector("list", length = C)
covU <- vector("list", length = C) # The covariances
bias <- vector("list", length = M)
for (i in 1:C) {
# Random initialization
U[[i]] <- matrix(rnorm(D[i] * K, 0, 1 / sqrt(opts$init.alpha)), D[i], K)
covU[[i]] <- matrix(1 / D[i], D[i], K)
}
#
# Parameters for modeling the row and column bias terms
#
for (m in 1:M) {
bias[[m]]$row$mu <- rep(0, D[inds[m, 1]])
bias[[m]]$row$m <- 0
if (!opts$useBias) {
bias[[m]]$row$nu <- rep(0, D[inds[m, 1]])
bias[[m]]$row$lambda <- 0
bias[[m]]$row$scale <- 0
} else {
bias[[m]]$row$nu <- rep(1, D[inds[m, 1]])
bias[[m]]$row$lambda <- 1
bias[[m]]$row$scale <- 1
}
bias[[m]]$col$mu <- rep(0, D[inds[m, 2]])
bias[[m]]$col$m <- 0
if (!opts$useBias) {
bias[[m]]$col$nu <- rep(0, D[inds[m, 2]])
bias[[m]]$col$lambda <- 0
bias[[m]]$col$scale <- 0
} else {
bias[[m]]$col$nu <- rep(1, D[inds[m, 2]])
bias[[m]]$col$lambda <- 1
bias[[m]]$col$scale <- 1
}
}
# Pseudo data
origX <- lapply(X, function(x) x[, 3])
for (m in which(likelihood == "bernoulli")) {
tau[m] <- 0.25
xi <- p_updatePseudoData(
indices[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
X[[m]][, 3] <- (
xi - (1 / (1 + exp(-xi)) - origX[[m]]) / tau[m]
)
}
for (m in which(likelihood == "poisson")) {
maxval <- max(X[[m]][, 3])
# print(paste("Maximal count in view ",m," is ",maxval,
# "; consider clipping if this is very large.",sep=""))
tau[m] <- 0.25 + 0.17 * maxval
xi <- p_updatePseudoData(
indices[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
X[[m]][, 3] <- (
xi - 1 / (1 + exp(-xi)) * (1 - origX[[m]] / log(1 + exp(xi))) / tau[m]
)
}
cost <- vector() # For storing the lower bounds
#
# The main loop
#
errors <- array(0, c(opts$iter.max, M))
for (iter in seq_len(opts$iter.max)) {
#gc() # Just to make sure there are no memory leaks
if ((opts$verbose > 0) && (iter %% 10 == 1)) {
cat(paste0("Iteration: ", iter, "/", opts$iter.max, "\n"))
}
#
# Update the weight matrices, using gradients (and diagonal Hessian)
#
norm <- 0
for (i in sample(C)) {
#
# Update the variance
#
covU[[i]] <- matrix(alpha[i, ], nrow = D[i], ncol = K, byrow = TRUE)
for (m in which(inds[, 1] == i)) {
# NOTE: Directly modifies covU[[i]]
p_covUsparse(
X[[m]], covU[[i]], U[[inds[m, 2]]], covU[[inds[m, 2]]], 1, tau[m]
)
}
for (m in which(inds[, 2] == i)) {
p_covUsparse(
X[[m]], covU[[i]], U[[inds[m, 1]]], covU[[inds[m, 1]]], 2, tau[m]
)
}
covU[[i]] <- 1 / covU[[i]]
# Update U itself
par <- list(
D = D, alpha = alpha, tau = tau,
X = X, U = U, covU = covU, inds = inds, bias = bias
)
par$this <- i
# The inverse Hessian happens to be the covariance
# (see Ilin & Raiko, JMLR 2010)
scale <- covU[[i]]
reg <- opts$grad.reg
for (n in 1:opts$grad.iter) {
g <- p_gradUsparseWrapper(U[[i]], par, stochastic = FALSE)
if (max(abs(scale * g)) > opts$grad.max) {
scale <- opts$grad.max * scale / max(abs(scale * g))
}
U[[i]] <- reg * U[[i]] + (1 - reg) * (U[[i]] - scale * g)
norm <- norm + sum(g^2)
}
}
if ((opts$verbose > 1) && (iter %% 10 == 1)) {
cat(paste0(" Gradient norm: ", norm, "\n"))
}
#
# Update the mean profiles (and their priors)
#
if (opts$useBias) {
for (m in seq_len(M)) {
# The approximations for each data point
temp <- p_updateMean(
X[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]], 1, bias[[m]]$col$mu
)
bias[[m]]$row$count <- temp$count
bias[[m]]$row$nu <- (
1 / (tau[m] * bias[[m]]$row$count + 1 / bias[[m]]$row$scale)
)
bias[[m]]$row$mu <- (
(tau[m] * temp$sum + bias[[m]]$row$m / bias[[m]]$row$scale)
* bias[[m]]$row$nu
)
# The approximation for the mean
bias[[m]]$row$lambda <- (
1 / (1 + 1 / bias[[m]]$row$scale * D[inds[m, 1]])
)
bias[[m]]$row$m <- (
1 / bias[[m]]$row$scale * sum(bias[[m]]$row$mu) * bias[[m]]$row$lambda
)
# The scale
bias[[m]]$row$scale <- (
mean(bias[[m]]$row$nu + (bias[[m]]$row$mu - bias[[m]]$row$m)^2)
)
# The approximations for each data point
temp <- p_updateMean(
X[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]], 2, bias[[m]]$row$mu
)
bias[[m]]$col$count <- temp$count
bias[[m]]$col$nu <- (
1 / (tau[m] * bias[[m]]$col$count + 1 / bias[[m]]$col$scale)
)
bias[[m]]$col$mu <- (
(tau[m] * temp$sum + bias[[m]]$col$m / bias[[m]]$col$scale)
* bias[[m]]$col$nu
)
# The approximation for the mean
bias[[m]]$col$lambda <- (
1 / (1 + 1 / bias[[m]]$col$scale * D[inds[m, 2]])
)
bias[[m]]$col$m <- (
1 / bias[[m]]$col$scale * sum(bias[[m]]$col$mu) * bias[[m]]$col$lambda
)
# The scale
bias[[m]]$col$scale <- (
mean(bias[[m]]$col$nu + (bias[[m]]$col$mu - bias[[m]]$col$m)^2)
)
}
}
#
# Update alpha, the ARD parameters
#
for (i in seq_len(C)) {
tmp <- rep(beta_0 * 2, K)
for (k in seq_len(K)) {
tmp[k] <- tmp[k] + sum(U[[i]][, k]^2) + sum(covU[[i]][, k])
}
tmp <- tmp / 2
alpha[i, ] <- a_ard[i] / tmp
b_ard[i, ] <- tmp
}
if (opts$method == "CMF") {
for (k in seq_len(K)) {
alpha[, k] <- sum(a_ard) / sum(b_ard[, k])
}
}
if (opts$method == "GFA") {
alpha[1, ] <- 1
}
#
# Update tau, the noise precisions; only needed for Gaussian likelihood
#
for (m in which(likelihood == "gaussian")) {
b_tau[m] <- beta_0t
v1 <- inds[m, 1]
v2 <- inds[m, 2]
b_tau[m] <- beta_0t + 0.5 * p_updateTau(
X[[m]], U[[v1]], U[[v2]],
covU[[v1]], covU[[v2]],
bias[[m]]$row$mu, bias[[m]]$col$mu,
bias[[m]]$row$nu, bias[[m]]$col$nu
)
tau[m] <- a_tau[m] / b_tau[m]
}
#
# Update the pseudo-data; only needed for non-Gaussian likelihoods
#
#print("Update pseudo data")
for (m in which(likelihood == "bernoulli")) {
xi <- p_updatePseudoData(
indices[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
X[[m]][, 3] <- (
xi - (1 / (1 + exp(-xi)) - origX[[m]]) / tau[m]
)
}
for (m in which(likelihood == "poisson")) {
xi <- p_updatePseudoData(
indices[[m]], U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
X[[m]][, 3] <- (
xi - 1 / (1 + exp(-xi)) * (1 - origX[[m]] / log(1 + exp(xi))) / tau[m]
)
}
par <- list(
D = D, alpha = alpha, tau = tau,
X = X, U = U, covU = covU, inds = inds, this = 1
)
if (!is.null(test)) {
pred <- list()
for (m in seq_len(M)) {
indices_test <- matrix(as.integer(test[[m]][, 1:2]), ncol = 2)
pred[[m]] <- p_updatePseudoData(
indices_test, U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
}
for (m in which(likelihood == "bernoulli")) {
pred[[m]] <- exp(pred[[m]])
pred[[m]] <- pred[[m]] / (1 + pred[[m]])
}
for (m in which(likelihood == "poisson")) {
pred[[m]] <- exp(pred[[m]])
pred[[m]] <- log(1 + pred[[m]])
}
error <- rep(0, M)
for (m in seq_len(M)) {
error[m] <- sqrt(mean((test[[m]][, 3] - pred[[m]])^2))
}
errors[iter, ] <- error
if ((opts$verbose > 0) && (iter %% 10 == 1)) {
cat(paste0("Test error: ", paste(error, collapse = " "), "\n"))
}
}
# Compute the cost function on training data
if (opts$computeCost) {
tcost <- 0
for (m in seq_len(M)) {
if (likelihood[m] == "gaussian") {
# The likelihood term
logtau <- digamma(a_tau[m]) - log(b_tau[m])
tcost <- (
tcost
- dim(X[[m]])[1] * 0.5 * logtau
+ (b_tau[m] - a_tau[m]) * tau[m]
)
# KL divergence for tau
temp <- (
-lgamma(alpha_0t)
+ alpha_0t * log(beta_0t)
+ (alpha_0t - 1) * logtau
- beta_0t * tau[m]
+ lgamma(a_tau[m])
- a_tau[m] * log(b_tau[m])
- (a_tau[m] - 1) * logtau
+ b_tau[m] * tau[m]
)
tcost <- tcost - temp
} else {
# Quadratic likelihood for non-Gaussian data
temp <- sum(tau[m] * (X[[m]][, 3] - origX[[m]])^2 / 2)
tcost <- tcost - temp
}
# Bias terms
if (opts$useBias) {
temp <- sum(
-0.5 * log(bias[[m]]$row$nu)
+ 0.5 * log(bias[[m]]$row$scale)
+ (
(bias[[m]]$row$nu + (bias[[m]]$row$m - bias[[m]]$row$mu)^2)
/ (2 * bias[[m]]$row$scale) - 0.5
)
)
temp <- temp + sum(
-0.5 * log(bias[[m]]$col$nu)
+ 0.5 * log(bias[[m]]$col$scale)
+ (
(bias[[m]]$col$nu + (bias[[m]]$col$m - bias[[m]]$col$mu)^2)
/ (2 * bias[[m]]$col$scale) - 0.5
)
)
temp <- (
temp
- 0.5 * log(bias[[m]]$row$scale)
+ 0.5 * log(1)
+ (
(bias[[m]]$row$scale - (0 - bias[[m]]$row$m)^2)
/ (2 * 1^2) - 0.5
)
)
temp <- (
temp
- 0.5 * log(bias[[m]]$col$scale)
+ 0.5 * log(1)
+ (
(bias[[m]]$col$scale - (0 - bias[[m]]$col$m)^2)
/ (2 * 1^2) - 0.5
)
)
tcost <- tcost + temp
}
}
if (opts$method == "CMF") {
for (i in seq_len(C)) {
for (k in seq_len(K)) {
logalpha <- digamma(a_ard[i]) - log(b_ard[i,k])
# The U and covU terms
temp <- (
0.5 * dim(covU[[i]])[1] * logalpha
- 0.5 * sum(covU[[i]][,k] + U[[i]][,k]^2) * alpha[i,k]
+ 0.5 * sum(log(covU[[i]][,k]))
)
tcost <- tcost - temp
# The alpha part
temp <- (
-lgamma(alpha_0)
+ alpha_0 * log(beta_0)
+ (alpha_0 - 1) * logalpha
- beta_0 * alpha[i, k]
+ lgamma(a_ard[i])
- a_ard[i] * log(b_ard[i, k])
- (a_ard[i] - 1) * logalpha + b_ard[i, k] * alpha[i, k]
)
tcost <- tcost - temp
}
}
} else {
for (k in seq_len(K)) {
logalpha <- digamma(sum(a_ard)) - log(sum(b_ard))
# The U and covU terms
for (i in seq_len(C)) {
temp <- (
0.5 * dim(covU[[i]])[1] * logalpha
- 0.5 * sum(covU[[i]][, k] + U[[i]][, k] ^ 2) * alpha[i, k]
+ 0.5 * sum(log(covU[[i]][, k]))
)
tcost <- tcost - temp
}
# The alpha part
temp <- (
-lgamma(alpha_0)
+ alpha_0 * log(beta_0)
+ (alpha_0 - 1) * logalpha
- beta_0 * alpha[i, k]
+ lgamma(sum(a_ard))
- sum(a_ard) * log(sum(b_ard[, k]))
- (sum(a_ard) - 1) * logalpha
+ sum(b_ard[, k]) * alpha[i, k]
)
tcost <- tcost - temp
}
}
cost <- c(cost, tcost)
}
} # the main loop of the algorithm ends
Uall <- U[[1]]
if (C > 1) {
for (i in 2:C) {
Uall <- rbind(Uall, U[[i]])
}
}
# Reconstructed datasets
if (!is.null(test)) {
out <- list()
for (m in seq_len(M)) {
indices_test <- matrix(as.integer(test[[m]][, 1:2]), ncol = 2)
xi <- p_updatePseudoData(
indices_test, U[[inds[m, 1]]], U[[inds[m, 2]]],
bias[[m]]$row$mu, bias[[m]]$col$mu
)
out[[m]] <- unname(cbind(indices_test, xi))
}
for (m in which(likelihood == "bernoulli")) {
out[[m]][, 3] <- exp(out[[m]][, 3])
out[[m]][, 3] <- out[[m]][, 3] / (1 + out[[m]][, 3])
}
for (m in which(likelihood == "poisson")) {
out[[m]][, 3] <- exp(out[[m]][, 3])
out[[m]][, 3] <- log(1 + out[[m]][, 3])
}
} else {
out <- NULL
}
# return the output of the model as a list
return(list(
U = U,
covU = covU,
tau = tau,
alpha = alpha,
cost = cost,
inds = inds,
errors = errors,
bias = bias,
D = D,
K = K,
Uall = Uall,
items = items,
out = out,
M = M,
likelihood = likelihood,
opts = opts
))
}
#' Internal function for computing the gradients
#'
#' @param r ?
#' @param par ?
#' @param stochastic Whether or not to perform updates on a subsample
#'
#' @return Gradient
p_gradUsparseWrapper <- function(r, par, stochastic = FALSE) {
g <- matrix(r, nrow = par$D[par$this])
cur <- g
for (j in seq_len(par$D[par$this])) {
g[j, ] <- g[j, ] * par$alpha[par$this, ]
}
for (m in which(par$inds[, 1] == par$this)) {
v2 <- par$inds[m, 2]
if (stochastic && m == 1) {
part <- sample(nrow(par$X[[m]]), round(nrow(par$X[[m]]) / 10))
# NOTE: p_gradUsparse directly modifies g
p_gradUsparse(
par$X[[m]][part, ], g, cur, par$U[[v2]], par$covU[[v2]], 1,
par$tau[m], par$bias[[m]]$row$mu, par$bias[[m]]$col$mu
)
} else {
p_gradUsparse(
par$X[[m]], g, cur, par$U[[v2]], par$covU[[v2]], 1,
par$tau[m], par$bias[[m]]$row$mu, par$bias[[m]]$col$mu
)
}
}
for (m in which(par$inds[, 2] == par$this)) {
v1 <- par$inds[m, 1]
if (stochastic && m == 1) {
part <- sample(nrow(par$X[[m]]), round(nrow(par$X[[m]]) / 10))
p_gradUsparse(
par$X[[m]][part, ], g, cur, par$U[[v1]], par$covU[[v1]], 2,
par$tau[m], par$bias[[m]]$row$mu, par$bias[[m]]$col$mu
)
} else {
p_gradUsparse(
par$X[[m]], g, cur, par$U[[v1]], par$covU[[v1]], 2,
par$tau[m], par$bias[[m]]$row$mu, par$bias[[m]]$col$mu
)
}
}
return(g)
}
#' Internal function for checking whether the input is in the right format
#'
#' @param mat An input matrix of class `matrix`
#' @param max_row Maximum row index for `mat`
#' @param max_col Maximum column index for `mat`
#'
#' @return `TRUE` if the input is in coordinate/triplet format.
#' `FALSE` otherwise.
p_check_sparsity <- function(mat, max_row, max_col) {
if (is.matrix(mat)) {
if (
ncol(mat) != 3
|| min(mat[, 1:2]) < 1
|| max(mat[, 1]) > max_row
|| max(mat[, 2]) > max_col
) {
cat("Matrix not in coordinate/triplet format")
return(FALSE)
} else {
return(TRUE)
}
}
cat("Input not of class `matrix`")
return(FALSE)
}
#' Conversion from matrix to coordinate/triplet format
#'
#' The CMF code requires inputs to be speficied in a specific
#' sparse format. This function converts regular R matrices
#' into that format.
#'
#' The element `X[i, j]` on the `i`-th row and `j`-th column is represented
#' as a triple `(i, j, X[i,k])`. The input for CMF is then a matrix
#' where each row specifies one element, and hence the representation
#' is of size `N x 3`, where `N` is the total number of observed entries.
#'
#' In the original input matrix the missing entries should be marked
#' as `NA`. In the output they will be completely omitted.
#'
#' Even though this format reminds the representation often used
#' for representing sparse matrices, it is important to notice that
#' observed zeroes are retained in the representation. The
#' elements missing from this representation are considered unknown,
#' not zero.
#'
#' @param orig A matrix of class `matrix`
#' @return The input matrix in triplet/coordinate format.
#'
#' @author Arto Klami and Lauri Väre
#' @seealso [triplets_to_matrix()]
#' @examples
#'
#' x <- matrix(c(1, 2, NA, NA, 5, 6), nrow = 3)
#' triplet <- matrix_to_triplets(x)
#' print(triplet)
#'
#' @export
matrix_to_triplets <- function(orig) {
triplets <- matrix(0, nrow = length(which(!is.na(orig))), ncol = 3)
count <- 1
for (y in seq_len(nrow(orig))) {
for (x in seq_len(ncol(orig))) {
if (!is.na(orig[y, x])) {
triplets[count, ] <- c(y, x, orig[y, x])
count <- count + 1
}
}
}
return(triplets)
}
#' Conversion from triplet/coordinate format to matrix
#'
#' This function is the inverse of [matrix_to_triplets()].
#' It converts a matrix represented as a set of triplets into
#' an object of the class `matrix`. The missing entries
#' (the ones not present in the triplet representation) are
#' filled in as `NA`.
#'
#' See [matrix_to_triplets()] for a description of the
#' representation.
#'
#' @param triplets A matrix in triplet/coordinate format
#' @return The input matrix as a normal matrix of class `matrix`
#' @author Arto Klami and Lauri Väre
#' @seealso [matrix_to_triplets()]
#' @examples
#'
#' x <- matrix(c(1, 2, NA, NA, 5, 6), nrow = 3)
#' triplet <- matrix_to_triplets(x)
#' print(triplet)
#' xnew <- triplets_to_matrix(triplet)
#' print(xnew)
#'
#' @export
triplets_to_matrix <- function(triplets) {
mat <- matrix(NA, nrow = max(triplets[, 1]), ncol = max(triplets[, 2]))
for (t in seq_len(nrow(triplets))) {
mat[triplets[t, 1], triplets[t, 2]] <- triplets[t, 3]
}
return(mat)
}
|
/scratch/gouwar.j/cran-all/cranData/CMF/R/CMF.R
|
# Generated by cpp11: do not edit by hand
p_gradUsparse <- function(Xm, Gm, CUm, OUm, Cm, idx, tau, Rowm, Colm) {
invisible(.Call(`_CMF_p_gradUsparse`, Xm, Gm, CUm, OUm, Cm, idx, tau, Rowm, Colm))
}
p_updatePseudoData <- function(indices, U1m, U2m, Rv, Cv) {
.Call(`_CMF_p_updatePseudoData`, indices, U1m, U2m, Rv, Cv)
}
p_updateTau <- function(Xm, U1m, U2m, cov1m, cov2m, Rv, Cv, nu1v, nu2v) {
.Call(`_CMF_p_updateTau`, Xm, U1m, U2m, cov1m, cov2m, Rv, Cv, nu1v, nu2v)
}
p_updateMean <- function(Xm, U1m, U2m, idx, Mv) {
.Call(`_CMF_p_updateMean`, Xm, U1m, U2m, idx, Mv)
}
p_covUsparse <- function(Xm, Cm, OUm, OCm, idx, tau) {
invisible(.Call(`_CMF_p_covUsparse`, Xm, Cm, OUm, OCm, idx, tau))
}
|
/scratch/gouwar.j/cran-all/cranData/CMF/R/cpp11.R
|
Kern.FUN <- function(zz,zi,bw)
{
out = (VTM(zz,length(zi))- zi)/bw
dnorm(out)/bw
}
Kern.FUN.M <- function(zz,zi,bw)
{
out=NULL
pro=1
for (j in 1:ncol(zz)){
out[[j]] = (VTM(zz[,j],nrow(zi))- zi[,j])/bw[j]
pro=pro*(dnorm(out[[j]])/bw[j])
}
pro
}
Kern.FUN.d <- function(zz,zi,bw)
{
out=NULL
pro=1
for (j in 1:ncol(zz)){
out[[j]] = (VTM(zz[,j],nrow(zi))- zi[,j])/bw[j]
pro=pro*(dnorm(out[[j]])/bw[j])*(-out[[j]])/bw[j]
}
pro
}
VTM<-function(vc, dm){
matrix(vc, ncol=length(vc), nrow=dm, byrow=T)
}
gen.bootstrap.weights=function( n, num.perturb=500){
sapply(1:num.perturb,function(x) sample(1:n,n,replace=T))
}
resam<- function(index,yob,sob,aob,n){
yob=yob[index]
sob=sob[index,]
aob=aob[index]
######## parametric all the way
sobsob=cbind(sob[, 1],sob[, 2],sob[, 3],sob[, 4],sob[, 1]*sob[, 2],sob[, 1]*sob[, 3],sob[, 1]*sob[, 4],
sob[, 2]*sob[, 3],sob[, 2]*sob[, 4],sob[, 3]*sob[, 4],sob[,1]^2,sob[,2]^2,sob[,3]^2,sob[,4]^2)#
y=yob[aob==0]
# x=sob[aob==0,]
# temp=lm(y~x)
# m0.ob=cbind(rep(1,nrow(sob)),sob)%*%temp$coefficients
xx=sobsob[aob==0,]
temp=lm(y~xx)
m0.ob=cbind(rep(1,nrow(sob)),sobsob)%*%temp$coefficients
y=yob[aob==1]
# x=sob[aob==1,]
# temp=lm(y~x)
# m1.ob=cbind(rep(1,nrow(sob)),sob)%*%temp$coefficients
xx=sobsob[aob==1,]
temp=lm(y~xx)
m1.ob=cbind(rep(1,nrow(sob)),sobsob)%*%temp$coefficients
temp=glm(aob~sobsob,family=binomial)
p1=temp$fitted.values
p0=1-p1
ms.p=m1.ob*p1+m0.ob*p0
c.hat=mean(yob*(1-aob))/mean(1-aob)-mean(ms.p*(1-aob))/mean(1-aob)
temp=mean(p0*(1-aob))/mean((1-aob))
gs.p=ms.p+p0*c.hat/temp
# causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
# causals=mean(gs.p*aob)/mean(aob)-mean(gs.p*(1-aob))/mean((1-aob))
# pte.pa=causals/causal
################ additive linear
sobs=cbind(ns(sob[,1],df=4),ns(sob[,2],df=4),ns(sob[,3],df=4),ns(sob[,4],df=4))
temp=t(sobs)%*%(sobs*aob)/sum(aob)+t(sobs)%*%(sobs*(1-aob))/sum(1-aob)-
matrix(apply(sobs*aob,2,sum)/sum(aob),ncol=1)%*%apply(sobs*(1-aob),2,sum)/sum(1-aob)-
matrix(apply(sobs*(1-aob),2,sum)/sum(1-aob),ncol=1)%*%apply(sobs*aob,2,sum)/sum(aob)
temp2=apply(sobs*yob*aob,2,sum)/sum(aob)+apply(sobs*yob*(1-aob),2,sum)/sum(1-aob)-
sum(yob*aob)/sum(aob)*apply(sobs*(1-aob),2,sum)/sum(1-aob)-
sum(yob*(1-aob))/sum(1-aob)*apply(sobs*aob,2,sum)/sum(aob)
beta=ginv(temp)%*%temp2
gs.l=sobs%*%beta
# causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
# causals=mean(gs.l*aob)/mean(aob)-mean(gs.l*(1-aob))/mean((1-aob))
# pte.l=causals/causal
######## convex combination
model.new <- function(temp) {
sob.r=as.numeric(temp*gs.p+(1-temp)*gs.l)
bw = 1.06*sd(sob.r)*n^(-1/5)/(n^0.2)
kern = Kern.FUN(zz=sob.r,zi=sob.r,bw)
ms.r=apply(yob*kern,2,sum)/apply(kern,2,sum)
c.hat=mean(yob*(1-aob))/mean(1-aob)-mean(ms.r*(1-aob))/mean(1-aob)
p0s.hat=apply((1-aob)*kern,2,sum)/apply(kern,2,sum)
temp=mean(p0s.hat*(1-aob))/mean((1-aob))
gs.r=ms.r+p0s.hat*c.hat/temp
causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
causals=mean(gs.r*aob)/mean(aob)-mean(gs.r*(1-aob))/mean((1-aob))
-causals/causal
}
# opt=optimize(model.new,lower=0, upper=1)
# pte.convex=-opt$objective
opt=nlm(model.new, 0, hessian = FALSE, iterlim = 100)
pte.convex=-opt$minimum
pte.pa=-model.new(1)
pte.l=-model.new(0)
out=c( pte.pa,pte.l,pte.convex)
}
pte.estimate.multiple = function(sob, yob, aob, var = TRUE , rep=500) {
n=length(yob)
################ parametric all the way
sobsob=cbind(sob[, 1],sob[, 2],sob[, 3],sob[, 4],sob[, 1]*sob[, 2],sob[, 1]*sob[, 3],sob[, 1]*sob[, 4],
sob[, 2]*sob[, 3],sob[, 2]*sob[, 4],sob[, 3]*sob[, 4],sob[,1]^2,sob[,2]^2,sob[,3]^2,sob[,4]^2)#
y=yob[aob==0]
xx=sobsob[aob==0,]
temp=lm(y~xx)
m0.ob=cbind(rep(1,nrow(sob)),sobsob)%*%temp$coefficients
y=yob[aob==1]
xx=sobsob[aob==1,]
temp=lm(y~xx)
m1.ob=cbind(rep(1,nrow(sob)),sobsob)%*%temp$coefficients
temp=glm(aob~sobsob,family=binomial)
p1=temp$fitted.values
p0=1-p1
ms.p=m1.ob*p1+m0.ob*p0
c.hat=mean(yob*(1-aob))/mean(1-aob)-mean(ms.p*(1-aob))/mean(1-aob)
temp=mean(p0*(1-aob))/mean((1-aob))
gs.p=ms.p+p0*c.hat/temp
causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
causals=mean(gs.p*aob)/mean(aob)-mean(gs.p*(1-aob))/mean((1-aob))
pte.pa=causals/causal
################ additive linear
sobs=cbind(ns(sob[,1],df=4),ns(sob[,2],df=4),ns(sob[,3],df=4),ns(sob[,4],df=4))
temp=t(sobs)%*%(sobs*aob)/sum(aob)+t(sobs)%*%(sobs*(1-aob))/sum(1-aob)-
matrix(apply(sobs*aob,2,sum)/sum(aob),ncol=1)%*%apply(sobs*(1-aob),2,sum)/sum(1-aob)-
matrix(apply(sobs*(1-aob),2,sum)/sum(1-aob),ncol=1)%*%apply(sobs*aob,2,sum)/sum(aob)
temp2=apply(sobs*yob*aob,2,sum)/sum(aob)+apply(sobs*yob*(1-aob),2,sum)/sum(1-aob)-
sum(yob*aob)/sum(aob)*apply(sobs*(1-aob),2,sum)/sum(1-aob)-
sum(yob*(1-aob))/sum(1-aob)*apply(sobs*aob,2,sum)/sum(aob)
beta=ginv(temp)%*%temp2
gs.l=sobs%*%beta
causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
causals=mean(gs.l*aob)/mean(aob)-mean(gs.l*(1-aob))/mean((1-aob))
pte.l=causals/causal
######## convex combination
model.new <- function(temp) {
sob.r=as.numeric(temp*gs.p+(1-temp)*gs.l)
bw = 1.06*sd(sob.r)*n^(-1/5)/(n^0.2)
kern = Kern.FUN(zz=sob.r,zi=sob.r,bw)
ms.r=apply(yob*kern,2,sum)/apply(kern,2,sum)
c.hat=mean(yob*(1-aob))/mean(1-aob)-mean(ms.r*(1-aob))/mean(1-aob)
p0s.hat=apply((1-aob)*kern,2,sum)/apply(kern,2,sum)
temp=mean(p0s.hat*(1-aob))/mean((1-aob))
gs.r=ms.r+p0s.hat*c.hat/temp
causal=mean(yob*aob)/mean(aob)-mean(yob*(1-aob))/mean(1-aob)
causals=mean(gs.r*aob)/mean(aob)-mean(gs.r*(1-aob))/mean((1-aob))
-causals/causal
}
opt=nlm(model.new, 0, hessian = FALSE, iterlim = 100)
pte.convex=-opt$minimum
index.max=opt$estimate
pte.pa=-model.new(1)
pte.l=-model.new(0)
#### variance
if (var==T){
re=rep
index=gen.bootstrap.weights( n, num.perturb=re)
temp=apply(index,2,resam,yob,sob,aob,n)
pte.se=apply(temp,1,sd)[3]
return(list('pte.es'=pte.convex,'pte.se'=pte.se))
}else{
return(list('pte.es'=pte.convex))
}
}
|
/scratch/gouwar.j/cran-all/cranData/CMFsurrogate/R/funs.R
|
#' Asbestos data
#'
#' A data set showing individuals' grade of asbestosis together with their
#' length of expposure to asbestos.
#'
#'
#' @details
#' Irving J. Selikoff (1915–1992) was a chest physician and researcher who had
#' often been described as America’s foremost medical expert on asbestos related
#' diseases between the 1960s and the early 1990s.
#'
#' Through a lung clinic that he operated in New Jersey, Selikoff collected data
#' from a sample of around 1200 insulation workers in metropolitan New York in
#' 1963.
#'
#' @docType data
#'
#' @usage data(asbestos)
#'
#' @format A data frame with 1117 rows and two columns.
#' \describe{
#' \item{exposure}{a factor representing the number of years of exposure to asbestos}
#' \item{grade}{a factor representing the grade of asbestosis. Grade 0 represents none present}
#' }
#'
#' @keywords datasets asbestos asbestosis
#'
#' @source Selikoff IJ. Household risks with inorganic fibers. Bull N Y Acad Med. 1981 Dec;57(10):947-61.
#'
#' @references Selikoff IJ. Household risks with inorganic fibers. Bull N Y Acad Med. 1981 Dec;57(10):947-61.
#'
#' @examples
#' attach(asbestos)
#' KW(treatment = exposure, response = grade)
"asbestos"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_asbestos.R
|
#' Cereal data
#'
#' Each of five breakfast cereals are ranked by ten judges, who each taste three
#' cereals. Each cereal is assessed six times.
#'
#' @details
#' The data comes from a Balanced Incomplete Block Design with the number of
#' treatments t = 5, number of blocks b = 10, with k = 3 and r = 6.
#'
#' @docType data
#'
#' @usage data(cereal)
#'
#' @format A data frame with 30 rows and three columns.
#' \describe{
#' \item{rank}{the rank of the cereal within each judge block}
#' \item{judge}{the judge that was used}
#' \item{type}{the type of cereal}
#' }
#'
#' @keywords datasets cereal BIB
#'
#' @source Kutner et al. (2005, section 28.1)
#'
#' @references Kutner, M., Nachtsheim, C., Neter, J. and Li, W. (2005). Applied linear statistical models (5th ed.). Boston: McGraw-Hill Irwin.
#'
#' @examples
#' attach(cereal)
#' durbin(y = rank, groups = type, blocks = judge)
"cereal"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_cereal.R
|
#' Corn data
#'
#' Corn yields when grown by four different methods.
#'
#' @docType data
#'
#' @usage data(corn)
#'
#' @format A data frame with 34 rows and two columns.
#' \describe{
#' \item{method}{one of four different methods used to grow corn}
#' \item{outcome}{corn yield categorised into four levels}
#' }
#'
#' @keywords datasets corn
#'
#' @source Rayner and Best (2001)
#'
#' @references
#' Rayner, J.C.W. and Best, D.J. (2001). A Contingency Table Approach to Nonparametric Testing. Chapman & Hall/CRC: Boca Raton FL.
#'
#' @examples
#' attach(corn)
#' KW(treatment = method, response = outcome)
"corn"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_corn.R
|
#' Cross-over data
#'
#' A success or fail response variable with three treatments repeated over 11
#' patients.
#'
#' @details
#' In StatXact (2003), three treatment, three period cross-over clinical data
#' for 11 patients are given. This is a CMH design with t = 3, c = 2, and
#' b = 11.
#'
#' @docType data
#'
#' @usage data(crossover)
#'
#' @format A data frame with 33 rows and three columns.
#' \describe{
#' \item{treatment}{the type of treatment applied. The three treatments are
#' placebo, aspirin and a new drug}
#' \item{success}{whether the treatment was a success or not}
#' \item{patient}{the patient the treatment was applied to}
#' }
#'
#' @keywords datasets crossover
#'
#' @references
#' StatXact (2003). User Manual Volume 2. CYTEL Software.
#'
#' @source StatXact (2003)
#'
#'
#' @examples
#' attach(crossover)
#' CMH(treatment = treatment,response = success,strata = patient)
"crossover"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_crossover.R
|
#' Dynamite data
#'
#' A data set for the explosiveness of five different formulations of explosive.
#'
#' @details
#' The effect of five different formulations of an explosive mixture are
#' assessed. A batch of raw material is large enough for only five
#' formulations. Each formulation is prepared by five operators. The response
#' here is the explosiveness of dynamite formulations. This is a Latin square
#' design.
#'
#' @docType data
#'
#' @usage data(dynamite)
#'
#' @format A data frame with 25 rows and four columns.
#' \describe{
#' \item{response}{a numeric vector for the explosiveness of the formulation with corresponding \code{treatment}, \code{batch} and \code{operator}}
#' \item{treatment}{a factor distinguishing the formulation for the
#' explosive mixture}
#' \item{batch}{a factor describing the batch the raw materials come from}
#' \item{operator}{a factor describing the operator who prepares the
#' explosive formulation}
#' }
#'
#' @keywords datasets dynamite LSD
#'
#' @references
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#' @source
#' https://www.fox.temple.edu/cms/wp-content/uploads/2016/05/Randomized-Block-Design.pdf
#'
#' @examples
#' attach(dynamite)
#' CARL(y = response, treatment = treatment, block1 = batch, block2 = operator)
"dynamite"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_dynamite.R
|
#' Food data
#'
#' Categorical responses made by 15 subjects for two different prices of the
#' same food product. The data is from a CMH design.
#'
#' @docType data
#'
#' @usage data(food)
#'
#' @format A data frame with 30 rows and three columns.
#' \describe{
#' \item{price}{a factor showing two price points for the product}
#' \item{decision}{a factor indicating the decision of either buy, undecided, or not_buy the product}
#' \item{subject}{a factor showing the individual making a decison about the product}
#' }
#'
#' @keywords datasets food CMH
#'
#' @references
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#' @examples
#' attach(food)
#' b_hj = matrix(1:3,ncol=15,nrow=3)
#' CMH(treatment = price, response = decision, strata = subject, b_hj = b_hj,
#' test_OPA = FALSE, test_C = FALSE)
"food"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_food.R
|
#' HR data
#'
#' Human resource ranking data.
#'
#' @details Applications for a position are vetted and ranked by Human Resource
#' (HR) professionals. The top five are interviewed by a selection committee of
#' ten. Each member of the committee gives an initial ranking of the applicants
#' and no one on the committee sees either the ranking by the HR professionals
#' or the initial rankings of the other committee members. Ties are not
#' permitted in any ranking. It is of interest to know if the rankings of the HR
#' professionals and the initial rankings of the selection committee are
#' correlated.
#'
#' @docType data
#'
#' @usage data(hr)
#'
#' @format A data frame with 50 rows and three columns.
#' \describe{
#' \item{applicant}{the applicant to which ratings are applied}
#' \item{applicant_ranking}{the ranking from made by the committee member}
#' \item{committee_member}{member of the selection panel that ranks five candidates}
#' }
#'
#' @keywords datasets hr CMH
#'
#' @references
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#'
#' @examples
#' attach(hr)
#' a_ij = matrix(1:5,ncol=10,nrow=5)
#' b_hj = matrix(1:5,ncol=10,nrow=5)
#' CMH(treatment = applicant, response = applicant_ranking,
#' strata = committee_member, a_ij = a_ij, b_hj = b_hj,
#' test_OPA = FALSE, test_GA = FALSE, test_MS = FALSE)
"hr"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_hr.R
|
#' Ice Cream data
#'
#'
#' @details
#' The icecream data set comes from a Balanced Incomplete Block Design. There
#' are seven vanilla ice-creams that are the same except for increasing amounts
#' of vanilla flavouring. Seven judges each taste three varieties.
#'
#' @docType data
#'
#' @usage data(icecream)
#'
#' @format A data frame with 21 rows and three columns.
#' \describe{
#' \item{rank}{the rank of the ice cream within each judging block}
#' \item{judge}{the judge that was used}
#' \item{variety}{the type of ice cream that was tested}
#' }
#'
#' @keywords datasets icecream BIBD
#'
#' @source Table 5.1 in Conover (1998, p. 391).
#'
#' @references
#' Conover, W. J. (1998). Practical nonparametric statistics (3rd ed.). New York: Wiley.
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#' @examples
#' attach(icecream)
#' durbin(y = rank, groups = variety, blocks = judge)
"icecream"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_icecream.R
|
#' Intelligence data
#'
#' Intelligence scores for individuals from different age groups.
#'
#' @docType data
#'
#' @usage data(intelligence)
#'
#' @format A data frame with 15 rows and two columns.
#' \describe{
#' \item{age}{age of the respondents}
#' \item{score}{intelligence score achieved}
#' }
#'
#' @keywords datasets intelligence
#'
#' @references
#' Rayner, J. C. W. and Best, D. J. (2001). A Contingency Table Approach to Nonparametric Testing. Boca Raton: Chapman & Hall/CRC.
#'
#' @source
#' Rayner and Best (2001, section 8.1)
#'
#' @examples
#' attach(intelligence)
#' gen_cor(x = rank(score), y = age, U = 2, V = 2)
"intelligence"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_intelligence.R
|
#' Jam data
#'
#' Plum jam sweetness data based on JAR judge scores.
#'
#' @details Three plum jams, A, B and C are given JAR sweetness codes by eight judges.
#' Here, 1 denotes not sweet enough, 2 not quite sweet enough, 3 just about
#' right, 4 a little too sweet and 5 too sweet.
#'
#' @docType data
#'
#' @usage data(jam)
#'
#' @format A data frame with 24 rows and four columns.
#' \describe{
#' \item{type}{the type of jam that was tested}
#' \item{judge}{the judge that was used for tasting}
#' \item{sweetness}{the judges score for sweetness: 1 denotes not sweet
#' enough, 2 not quite sweet enough, 3 just about right, 4 a little too sweet
#' and 5 too sweet}
#' \item{sweetness_ranks}{the ranks within judge}
#' }
#'
#' @keywords datasets jam RBD
#'
#' @references
#' Rayner, J.C.W. and Best, D.J. (2017). Unconditional analogues of Cochran-Mantel-Haenszel tests. Australian & NZ Journal of Statistics, 59(4), 485-494.
#'
#' Rayner, J.C.W. and Best, D.J. (2018). Extensions to the Cochran-Mantel-Haenszel mean scores and correlation tests. Journal of Statistical Theory and Practice.
#'
#' @source
#' Rayner and Best (2017, 2018)
#'
#' @examples
#' attach(jam)
#' a_ij = matrix(rep(1:3,8), ncol = 8)
#' b_hj = matrix(rep(1:5,8), ncol = 8)
#' CMH(treatment = type, response = sweetness, strata = judge,
#' a_ij = a_ij, b_hj = b_hj, test_OPA = FALSE, test_GA = FALSE,
#' test_MS = FALSE)
"jam"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_jam.R
|
#' Job Satisfaction data
#'
#' Job satisfaction data based on income and gender.
#'
#' @details The data relate job satisfaction and income in males and females.
#' Gender induces two strata; the treatments are income with categories scored
#' 3, 10, 20 and 35 while the response is job satisfaction with categories
#' scored 1, 3, 4, and 5.
#'
#' @docType data
#'
#' @usage data(job_satisfaction)
#'
#' @format A data frame with 104 rows and three columns.
#' \describe{
#' \item{income}{income level categorised}
#' \item{satisfaction}{the level of job satisfaction for the respondent}
#' \item{gender}{gender of the respondent}
#' }
#'
#' @keywords datasets job_satisfaction
#'
#' @references Agresti, A. (2003). Categorical Data Analysis. Hoboken: John Wiley & Sons.
#'
#'
#' @source Agresti (2003)
#'
#'
#' @examples
#' attach(job_satisfaction)
#' a_ij = matrix(rep(c(3,10,20,35),2),nrow=4)
#' b_hj = matrix(rep(c(1,3,4,5),2),nrow=4)
#' unconditional_CMH(treatment = income, response = satisfaction,
#' strata = gender, U = 2, V = 2, a_ij = a_ij,
#' b_hj = b_hj)
"job_satisfaction"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_job_satisfaction.R
|
#' Lemonade data
#'
#' The Lemonade data set comes from a Randomised Block Design. There
#' are four types of lemonades which are all tasted by five tasters.
#'
#' @docType data
#'
#' @usage data(lemonade)
#'
#' @format A data frame with 20 rows and three columns.
#' \describe{
#' \item{rank}{the rank of the lemonade within each judging block}
#' \item{type}{the type of lemonade that was tested}
#' \item{taster}{the judge that was used for tasting}
#' }
#'
#' @keywords datasets lemonade RBD
#'
#' @source Thas et al. (2012, section 4.2)
#'
#' @references Thas, O., Best, D.J. and Rayner, J.C.W. (2012). Using orthogonal trend contrasts for testing ranked data with ordered alternatives. Statisticia Neerlandica, 66(4), 452-471.
#'
#' @examples
#' attach(lemonade)
#' friedman(y = rank, groups = type, blocks = taster)
"lemonade"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_lemonade.R
|
#' Lemonade Sugar data
#'
#' Five lemonades with increasing sugar content are ranked by each of ten
#' judges. They were not permitted to give tied outcomes. This is a randomised
#' block design.
#'
#' @docType data
#'
#' @usage data(lemonade_sugar)
#'
#' @format A data frame with 50 rows and three columns.
#' \describe{
#' \item{ranks}{the rank each lemonade based on sugar content}
#' \item{sugar_content}{type of lemonade ordered by sugar content}
#' \item{judge}{the judge providing the ranking}
#' }
#'
#' @keywords datasets lemonade_sugar RBD
#'
#' @references
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#' @examples
#' attach(lemonade_sugar)
#' gen_cor(x = ranks, y = sugar_content, U = 3, V = 3, rounding = 3)
"lemonade_sugar"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_lemonade_sugar.R
|
#' Lizard data
#'
#' The data come from Manly (2007) and relate to the number of ants consumed by
#' two sizes of Eastern Horned Lizards over a four month period.
#'
#' @docType data
#'
#' @usage data(lizard)
#'
#' @format A data frame with 24 rows and three columns.
#' \describe{
#' \item{month}{the month in which the measurements were taken}
#' \item{size}{the size of the Eastern Horned Lizards}
#' \item{ants}{the number of ants consumed}
#' }
#'
#' @keywords datasets lizard RBD
#'
#' @references
#' Manly, B. F. J. (2007). Randomization, Bootstrap and Monte Carlo Methods in Biology, Third Edition. Boca Raton: Chapman & Hall/CRC.
#'
#' @source Manly (2007)
#'
#' @examples
#' attach(lizard)
#' gen_cor(x = ants, y = month, z = size, U = 3, V = 3, W = 1)
"lizard"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_lizard.R
|
#' Marriage data
#'
#' Scores of 1, 2 and 3 are assigned to the responses agree, neutral and
#' disagree respectively to the proposition "Homosexuals should be able to
#' marry" and scores of 1, 2 and 3 are assigned to the religious categories
#' fundamentalist, moderate and liberal respectively.
#'
#' @docType data
#'
#' @usage data(marriage)
#'
#' @format A data frame with 133 rows and three columns.
#' \describe{
#' \item{education}{highest level of eduction for the respondent}
#' \item{religion}{level of religiosity. Scores of 1, 2 and 3 are assigned to the religious categories fundamentalist, moderate and liberal respectively}
#' \item{opinion}{the response to the proposition: "Homosexuals should be able to marry". Scores of 1, 2 and 3 are assigned to the responses agree, neutral and
#' disagree respectively}
#' }
#'
#' @keywords datasets marriage
#'
#' @source Agresti (2002)
#'
#' @references
#' Agresti, A. (2002). Categorical Data Analysis, 2nd ed; Wiley: New York.
#'
#' @examples
#' attach(marriage)
#' lm(as.numeric(opinion)~religion+education)
"marriage"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_marriage.R
|
#' Milk data
#'
#' In each of four lactation periods each of four cows are fed a different diet.
#' There is a washout period so previous diet does not affect future results.
#' A 4 × 4 Latin square is used to assess how diet affects milk production.
#'
#' @docType data
#'
#' @usage data(milk)
#'
#' @format A data frame with 16 rows and four columns.
#' \describe{
#' \item{production}{a numerical measure of the milk production for the given diet, cow, and period}
#' \item{diet}{a factor showing which diet the cow was administered}
#' \item{cow}{a factor indicating the cow}
#' \item{period}{a factor showing the relevant period}
#' }
#'
#' @keywords datasets milk LSD
#'
#'
#' @source
#' https://www.stat.purdue.edu/~yuzhu/stat514fall05/Lecnot/latinsquarefall05.pdf
#'
#' @examples
#' attach(milk)
#' CARL(y = production, treatment = diet, block1 = cow, block2 = period)
"milk"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_milk.R
|
#' Peanuts data
#'
#' A plant biologist conducted an experiment to compare the yields of four
#' varieties of peanuts, denoted as A, B, C, and D. A plot of land was divided
#' into 16 subplots (four rows and four columns).
#'
#' @docType data
#'
#' @usage data(peanuts)
#'
#' @format A data frame with 16 rows and four columns.
#' \describe{
#' \item{yield}{the peanut yield}
#' \item{treatment}{the variety of peanut plant}
#' \item{row}{the row the plants were grown in of the plot}
#' \item{col}{the column the plants were grown in of the plot}
#' }
#'
#' @keywords datasets peanuts LSD
#'
#' @source http://www.math.montana.edu/jobo/st541/sec3c.pdf
#'
#' @references
#' Rayner, J.C.W and Livingston, G. C. (2022). An Introduction to Cochran-Mantel-Haenszel Testing and Nonparametric ANOVA. Wiley.
#'
#' @examples
#' attach(peanuts)
#' CARL(y = yield, treatment = treatment, block1 = row, block2 = col)
"peanuts"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_peanuts.R
|
#' Saltiness data
#'
#' Three products, A, B and C, were tasted by 107 consumers who gave responses
#' ‘not salty enough’, ‘just about right saltiness’ and ‘too salty’, which were
#' then scored as 1, 2 and 3. The design is randomised blocks.
#'
#'
#' @docType data
#'
#' @usage data(saltiness)
#'
#' @format A data frame with 321 rows and three columns.
#' \describe{
#' \item{product}{the type of product being tested}
#' \item{scores}{the saltiness score. Scores of 1, 2 and 3 correspond to responses
#' ‘not salty enough’, ‘just about right saltiness’ and ‘too salty’}
#' \item{participant}{the participant providing the rating}
#' }
#'
#' @keywords datasets saltiness RBD
#'
#' @source Rayner, J. C. W. and Best, D. J. (2017)
#'
#' @references
#' Rayner, J. C. W. and Best, D. J. (2017). Unconditional analogues of Cochran-Mantel-Haenszel tests. Australian & New Zealand Journal of Statistics, 59(4):485–494.
#'
#' @examples
#' attach(saltiness)
#' CMH(treatment = product, response = scores, strata = participant,
#' test_OPA = FALSE, test_MS = FALSE, test_C = FALSE)
"saltiness"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_saltiness.R
|
#' Strawberry data
#'
#' Strawberry growth rates for different pesticides.
#'
#' @details Pesticides are applied to strawberry plants to inhibit the growth of
#' weeds. The question is, do they also inhibit the growth of the strawberries?
#' The design is a supplemented balanced design.
#'
#' @docType data
#'
#' @usage data(strawberry)
#'
#' @format A data frame with 28 rows and four columns.
#' \describe{
#' \item{block}{the experimental block}
#' \item{pesticide}{the pesticide applied to the plant. Pesticide O is a control.}
#' \item{response}{a measure of the growth rate of strawberry plants with \code{pesticide} applied.}
#' \item{rank}{rank of the response}
#' }
#'
#' @keywords datasets strawberry
#'
#' @source Pearce (1960)
#'
#' @references Pearce, S.C. (1960). Supplemented balanced. Biometrika, 47, 263-271.
#'
#' @examples
#' attach(strawberry)
#' lm_strawberry = lm(rank~pesticide+block)
#' anova(lm_strawberry)
"strawberry"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_strawberry.R
|
#' Traffic data
#'
#' Traffic light data for different light sequences, intersections, and times of
#' day.
#'
#' @details A traffic engineer conducted a study to compare the total unused red-light
#' time for five different traffic light signal sequences. The experiment was
#' conducted with a Latin square design in which blocking factors were (1) five
#' intersections and (2) five time of day periods.
#'
#'
#' @docType data
#'
#' @usage data(traffic)
#'
#' @format A data frame with 25 rows and four columns.
#' \describe{
#' \item{minutes}{the amount of unused red-light time in minutes}
#' \item{treatment}{the traffic light sequence}
#' \item{intersection}{the intersection the \code{treatment} was applied}
#' \item{time_of_day}{the time of the day the \code{treatment} was applied}
#' }
#'
#' @keywords datasets traffic LSD
#'
#' @source Kuehl, R. (2000)
#'
#' @references
#' Kuehl, R. (2000). Design of Experiments: Statistical Principles of Research Design and Analysis. Belmont, California: Duxbury Press.
#'
#' Best, D. J. and Rayner, J. C. W. (2011). Nonparametric tests for Latin squares. NIASRA Statistics Working Paper Series, 11-11.
#'
#' @examples
#' attach(traffic)
#' np_anova(ordered_vars = rank(minutes),
#' predictor_vars = data.frame(treatment,intersection,time_of_day), uvw = 1)
"traffic"
|
/scratch/gouwar.j/cran-all/cranData/CMHNPA/R/data_doc_traffic.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.