library("cpss")
if (!requireNamespace("L1pack", quietly = TRUE)) {
stop("Please install the package \"L1pack\".")
}
set.seed(666)
n <- 1000
tau <- c(250, 500, 750)
tau_ext <- c(0, tau, n)
be0 <- c(1, 1, 0, -1)
be <- c(1, -1, -1, 1)
seg_len <- diff(c(0, tau, n))
x <- rnorm(n)
eta <- unlist(lapply(seq(1, length(tau) + 1), function(k) {
be0[k] + be[k] * x[(tau_ext[k] + 1):tau_ext[k + 1]]
}))
ep <- L1pack::rlaplace(n)
y <- eta + ep
g_subdat_l1 <- function(dat, indices) {
matrix(dat[indices, ], sum(indices), ncol(dat))
}
g_param_l1 <- function(dat, param.opt = NULL) {
y <- dat[, 1]
x <- dat[, -1]
return(L1pack::l1fit(x, y)$coefficients)
}
g_cost_l1 <- function(dat, param) {
y <- dat[, 1]
x <- dat[, -1]
return(sum(abs(y - cbind(1, x) %*% as.matrix(param))))
}
res <- cpss.custom(
dataset = cbind(y, x), n = n,
g_subdat = g_subdat_l1, g_param = g_param_l1, g_cost = g_cost_l1,
algorithm = "BS", dist_min = 10, ncps_max = 10,
g_smry = NULL, easy_cost = NULL
)
summary(res)
# 250 500 744
do.call(rbind,res@params)
# Intercept X
# [1,] 0.9327557 0.9558247
# [2,] 0.9868086 -1.0254999
# [3,] -0.0464067 -0.9076744
# [4,] -0.9746133 0.9671701
Run the code above in your browser using DataLab