# generate some simple data
set.seed(1)
N <- 100
data.vec <- c(rnorm(N), rnorm(N, 2), rnorm(N))
# example one - calling fpop via crops using global scope
# need the fpop library
library(pacman)
p_load(fpop)
# create a function to wrap a call to fpop for use with crops
fpop.for.crops<-function(beta)
{
# Note - this code is taken from the example in the fpop package
fit <- Fpop(data.vec, beta)
end.vec <- fit$t.est
change.vec <- end.vec[-length(end.vec)]
start.vec <- c(1, change.vec+1)
segs.list <- list()
for(seg.i in seq_along(start.vec))
{
start <- start.vec[seg.i]
end <- end.vec[seg.i]
seg.data <- data.vec[start:end]
seg.mean <- mean(seg.data)
segs.list[[seg.i]] <- data.frame(
start, end,
mean=seg.mean,
seg.cost=sum((seg.data-seg.mean)^2))
}
segs <- do.call(rbind, segs.list)
return(list(sum(segs$seg.cost),segs$end[-length(segs$end)]))
}
# now use this wrapper function with crops
res<-crops(fpop.for.crops,0.5*log(300),2.5*log(300))
# print summary of analysis
summary(res)
# summarise the segmentations
segmentations(res)
# visualise the segmentations
plot(res)
# overlay the data on the segmentations
df <- data.frame("x"=1:300,"y"=data.vec)
plot(res,df)
Run the code above in your browser using DataLab