content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
plot.tfl <- function (x, y, ...,
min.rank=1, max.rank=NULL, log=c("", "x", "y", "xy"),
type=c("p", "l", "b", "o", "s"),
xlim=NULL, ylim=NULL, freq=TRUE,
xlab="rank", ylab="frequency", legend=NULL, grid=FALSE,
main="Type-Frequency List (Zipf ranking)",
bw=zipfR.par("bw"), cex=1, steps=200,
pch=NULL, lty=NULL, lwd=NULL, col=NULL)
{
## collect all specified TFL in single list
if (is.list(x) && inherits(x[[1]], c("tfl", "lnre"))) {
if (!missing(y)) stop("only a single list of TFLs may be specified")
TFLs <- x
} else {
TFLs <- list(x) # this is a bit complicated because of the plot() prototype
if (! missing(y)) TFLs <- c(TFLs, list(y), list(...))
}
n.tfl <- length(TFLs)
if (!all(sapply(TFLs, inherits, c("tfl", "lnre")))) stop("all unnamed arguments must be type-frequency lists or LNRE models")
idx.lnre <- sapply(TFLs, inherits, "lnre") # which arguments are LNRE models
## check other arguments
if (any(idx.lnre) && freq) stop("LNRE models can only be plotted with freq=FALSE")
if (length(log) > 1 || log != "") log <- match.arg(log)
type <- match.arg(type)
if (!missing(legend) && length(legend) != n.tfl) stop("'legend' argument must be character or expression vector of same length as number of TFLs")
if (any(sapply(TFLs[!idx.lnre], function (.TFL) isTRUE(attr(.TFL, "incomplete"))))) stop("plotting of incomplete type-frequency lists is not supported")
x.log <- log == "x" || log == "xy"
y.log <- log == "y" || log == "xy"
if (missing(ylab) && !freq) ylab <- "relative frequency (per million words)"
## determine range of ranks available & check requested min/max
if (any(!idx.lnre)) {
max.rank.available <- max(sapply(TFLs[!idx.lnre], function (.TFL) length(.TFL$f)))
if (is.null(max.rank)) {
max.rank <- max.rank.available
} else {
if (min.rank >= max.rank.available) stop(sprintf("no data available for ranks > %d (min.rank)", min.rank))
}
}
else {
if (is.null(max.rank)) stop("max.rank must be specified if only LNRE models are plotted")
}
if (min.rank < 1) stop(sprintf("min.rank=%d invalid, must be integer >= 1", min.rank))
if (min.rank >= max.rank) stop(sprintf("min.rank=%d must be smaller than max.rank=%d", min.rank, max.rank))
## collect x/y-coordinates for each TFL or LNRE model to be plotted
coord <- lapply(seq_len(n.tfl), function (i) {
.TFL <- TFLs[[i]]
x <- NULL
y <- NULL
if (idx.lnre[i]) {
## LNRE model: plot type probabilities for equidistant steps from min.rank to max.rank
.max <- min(max.rank, .TFL$S)
if (.max >= min.rank) {
if (!x.log) {
x <- seq(min.rank, .max, length.out=steps) # ranks (not rounded to integer)
} else {
x <- exp( seq(log(min.rank), log(.max), length.out=steps) ) # logarithmic steps
}
y <- 1e6 * tqlnre(.TFL, x - .5) # approximate probability pmw of type i = G^{-1}(i - 0.5)
## correct probability mass is F(G^{-1}(i - 1)) - F(G^{-1}(i)), but this would have
## cancellation issues for small probabilities, so the simple approximation is preferred
}
} else {
## TFL: collect selected ranks and corresponding (relative) frequencies; adjust for type="s"
f <- sort(.TFL$f, decreasing=TRUE)
.max <- min(max.rank, length(f))
x <- seq(min.rank, .max)
y <- f[x]
if (type == "s") {
idx <- c(diff(y) != 0, TRUE) # for every horizontal bar, keep only last point as right upper edge
idx[1] <- TRUE # but make sure the first point isn't discarded
x <- x[idx]
y <- y[idx]
}
if (!freq) y <- 1e6 * y / N(.TFL) # rescale to relative frequency pmw
}
list(x=x, y=y)
})
## determine range of y-coordinates
tmp <- unlist(lapply(coord, function (.XY) .XY$y))
f.max <- max(tmp)
f.min <- if (freq) 1 else min(tmp)
## get default styles unless manually overridden
if (is.null(pch)) pch <- zipfR.par("pch", bw.mode=bw)
if (is.null(lty)) lty <- zipfR.par("lty", bw.mode=bw)
if (is.null(lwd)) lwd <- zipfR.par("lwd", bw.mode=bw)
if (is.null(col)) col <- zipfR.par("col", bw.mode=bw)
## choose suitable ranges on the axes, unless specified by user
if (is.null(xlim)) xlim <- c(min.rank, max.rank)
if (is.null(ylim)) ylim <- if (y.log) c(2/3*f.min, 1.5*f.max) else c(0, 1.05 * f.max)
## set up plotting region and labels
plot(1, 1, type="n", xlim=xlim, ylim=ylim, log=log, xaxs="r", yaxs="i",
xlab=xlab, ylab=ylab, main=main)
## display grid (orders of magnitude) on any logarithmic axis
if (grid) {
log.steps <- function (x) 10 ^ seq(floor(log10(min(x))), ceiling(log10(max(x))))
if (x.log) abline(v=log.steps(xlim), lwd=.5)
if (y.log) abline(h=log.steps(ylim), lwd=.5)
}
## go through all specified TFLs / LNRE models and plot the pre-computed coordinates
for (i in seq_len(n.tfl)) {
.XY <- coord[[i]]
if (length(.XY$x) > 0) {
.type <- if (idx.lnre[i]) "l" else if (type == "s") "S" else type
points(.XY$x, .XY$y, type=.type, cex=cex, pch=pch[i], lty=lty[i], lwd=lwd[i], col=col[i])
}
}
## add legend if specified by user
if (!is.null(legend)) {
legend.args <- list("topright", inset=.02, bg="white", legend=legend, col=col)
if (type %in% c("p","b","o")) {
.pch <- ifelse(idx.lnre, NA, pch)
legend.args <- append(legend.args, list(pch=.pch, pt.cex=1.4*cex, pt.lwd=lwd))
}
if (type != "p" || any(idx.lnre)) legend.args <- append(legend.args, list(lwd=lwd, lty=lty))
do.call("legend", legend.args)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/plot_tfl.R |
plot.vgc <- function (x, y, ...,
m=NULL, add.m=NULL, N0=NULL,
conf.level=.95, conf.style=c("ticks", "lines"),
log=c("", "x", "y", "xy"),
bw=zipfR.par("bw"),
xlim=NULL, ylim=NULL,
xlab="N", ylab="V(N)", legend=NULL,
main="Vocabulary Growth",
lty=NULL, lwd=NULL, col=NULL)
{
## collect all specified VGCs in single list
if (is.list(x) && inherits(x[[1]], "vgc")) {
VGCs <- x
if (!missing(y)) stop("only a single list of VGCs may be specified")
} else {
VGCs <- list(x) # this is a bit complicated because of the plot() prototype
if (!missing(y)) VGCs <- c(VGCs, list(y), list(...))
}
n.vgc <- length(VGCs)
## check other arguments
log <- match.arg(log)
conf.style <- match.arg(conf.style)
if (!is.null(m) && !is.null(add.m)) stop("'m' and 'add.m' must not be specified at the same time")
if (!is.null(m) && !( is.numeric(m) && all(1 <= m & m <= 9) && length(m) == 1 ))
stop("'m' must be a single integer between 1 and 9")
if (!is.null(add.m) && !( is.numeric(add.m) && all(1 <= add.m & add.m <= 9) ))
stop("'add.m' must be a vector of integers between 1 and 9")
if (!is.null(legend) && length(legend) != n.vgc)
stop("'legend' argument must be character or expression vector of same length as number of VGCs")
x.log <- log == "x" || log == "xy"
y.log <- log == "y" || log == "xy"
## check availability of Vm in 'vgc' objects (with m or add.m option)
req.m <- 0 # required spectrum elements (up to req.m)
if (!is.null(m)) req.m <- m
if (!is.null(add.m)) req.m <- max(add.m)
if (req.m > 0 && any( sapply(VGCs, function (.VGC) attr(.VGC, "m.max") < req.m) ))
stop("all VGC arguments must include spectrum elements up to m=", req.m)
## determine maximum value that has to be accommodated on y-axis
V.max <- max(sapply(VGCs, function (.VGC) max(V(.VGC)) ))
if (!is.null(m)) V.max <- max(sapply(VGCs, function (.VGC) max(Vm(.VGC, m)) ))
if (!is.null(add.m)) {
for (.m in add.m) V.max <- max(V.max, sapply(VGCs, function (.VGC) max(Vm(.VGC, .m)) ))
}
N.max <- max(sapply(VGCs, function (.VGC) max(N(.VGC)) ))
## get default styles unless manually overridden
if (missing(lty)) lty <- zipfR.par("lty", bw.mode=bw)
if (missing(lwd)) lwd <- zipfR.par("lwd", bw.mode=bw)
if (missing(col)) col <- zipfR.par("col", bw.mode=bw)
## typeset default label on y-axis, depending on which curves are shown
expected <- sapply(VGCs, function (.VGC) attr(.VGC, "expected"))
if (missing(ylab)) {
if (!is.null(m)) { # 'm' option => V_m(N) / E[V_m(N)]
lab.V <- bquote(V[.(m)](N))
}
else { # default => V(N) / E[V(N)]
lab.V <- bquote(V(N))
}
lab.EV <- bquote(E * group("[", .(lab.V), "]"))
if (all(expected)) {
ylab <- lab.EV
}
else if (all(!expected)) {
ylab <- lab.V
}
else {
ylab <- bquote(.(lab.V) / .(lab.EV))
}
if (!is.null(add.m)) { # 'add.m' option => V(N) / V_1(N) / V_2(N) / ...
for (.m in add.m) {
lab.Vm <- bquote(V[.(.m)](N))
lab.EVm <- bquote(E * group("[", .(lab.Vm), "]"))
if (any(!expected)) {
ylab <- bquote(.(ylab) / .(lab.Vm))
}
if (any(expected)) {
ylab <- bquote(.(ylab) / .(lab.EVm))
}
}
}
}
## choose suitable ranges on the axes, unless specified by user
if (is.null(xlim)) xlim <- if (x.log) c(1, N.max) else c(0, N.max)
if (is.null(ylim)) ylim <- if (y.log) c(1, 2 * V.max) else c(0, 1.05 * V.max)
## set up plotting region and labels
plot(1, 1, type="n", xlim=xlim, ylim=ylim, log=log, xaxs="i", yaxs="i",
xlab=xlab, ylab=ylab, main=main)
for (i in 1:n.vgc) { # go through all specified VGCs
curr.vgc <- VGCs[[i]]
x.values <- N(curr.vgc)
y.values <- if (is.null(m)) V(curr.vgc) else Vm(curr.vgc, m)
thin.lwd <- if (lwd[i] < 1) .5 else lwd[i] / 2 # for thin lines, otherwise matching style of main line
if (x.log) x.values[x.values <= 0] <- xlim[1] / 10
## draw confidence intervals for expected VGC with variances
if (attr(curr.vgc, "hasVariances") && is.numeric(conf.level)) {
variance <- if (is.null(m)) VV(curr.vgc) else VVm(curr.vgc, m)
st.dev <- sqrt(variance)
factor <- - qnorm((1 - conf.level) / 2) # approximate confidence interval
y.minus <- y.values - factor * st.dev
y.plus <- y.values + factor * st.dev
if (y.log) y.minus[y.minus <= 0] <- ylim[1] / 10
if (conf.style == "ticks") {
.l <- length(x.values) # for "ticks" style, may need to reduce number of data points
.idx <- 1:.l
if (.l > 100) {
.thin <- ceiling(.l / 100) # sample at regular intervals so that there are at most 100 data points
.idx <- rev(seq(.l, 1, by=-.thin)) # ensure that last data point is included
}
segments(x.values[.idx], y.minus[.idx], x.values[.idx], y.plus[.idx], lwd=1, col=col[i])
}
else {
lines(x.values, y.plus, lty=lty[i], lwd=thin.lwd, col=col[i])
lines(x.values, y.minus, lty=lty[i], lwd=thin.lwd, col=col[i])
}
}
## draw main VGC (either V(N) or V_m(N))
if (y.log) y.values[y.values <= 0] <- ylim[1] / 10
lines(x.values, y.values, lty=lty[i], lwd=lwd[i], col=col[i])
## add VGCs for various V_m(N) (with option 'add.m')
if (!is.null(add.m)) {
for (.m in add.m) {
y.values <- Vm(curr.vgc, .m)
if (y.log) y.values[y.values <= 0] <- ylim[1] / 10
lines(x.values, y.values, lty=lty[i], lwd=thin.lwd, col=col[i])
}
}
}
if (!is.null(N0)) {
abline(v=N0, lwd=2, col="black", lty="dashed")
}
if (!is.null(legend)) { # add legend if specified by user
legend("bottomright", inset=.02, bg="white", legend=legend, lty=lty, lwd=lwd, col=col)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/plot_vgc.R |
postdlnre <- function (model, x, m, N, ...) UseMethod("postdlnre")
postldlnre <- function (model, x, m, N, base=10, log.x=FALSE, ...) UseMethod("postldlnre")
postplnre <- function (model, q, m, N, lower.tail=FALSE, ...) UseMethod("postplnre")
postqlnre <- function (model, p, m, N, lower.tail=FALSE, ...) UseMethod("postqlnre")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/posterior.R |
postdlnre.lnre <- function (model, x, m, N, ...) {
if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
factor <- exp( m * log(N * x) - N * x - Cgamma(m + 1, log=TRUE) ) # = (Nx)^m * exp(-Nx) / m!
factor * tdlnre(model, x) / EVm(model, m, N)
}
postldlnre.lnre <- function (model, x, m, N, base=10, log.x=FALSE, ...)
{
if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
if (log.x) x <- base ^ x
log(base) * x * postdlnre(model, x, m, N, ...)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/posterior_lnre.R |
# postplnre.lnre.fzm <- function (model, q, m, N, lower.tail=FALSE, ...)
# {
# if (! inherits(model, "lnre.fzm")) stop("argument must be object of class 'lnre.fzm'")
# if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
# if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
# if (!(is.numeric(q) && all(q >= 0))) stop("argument 'q' must be numeric and non-negative")
#
# alpha <- model$param$alpha
# A <- model$param$A
# B <- model$param$B
# C <- model$param2$C
#
# rho <- pmin(pmax(q, A), B) # clamp cutoff point rho to model range, so both integrals are valid
#
# ## ******* much room for optimisation here *********
# # termA <- exp(Igamma(m - alpha, N * A, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# # termA = Igamma(m - alpha, N * A, lower=FALSE) / m!
# # termB <- exp(Igamma(m - alpha, N * B, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# # termB = Igamma(m - alpha, N * B, lower=FALSE) / m!
# # termRho <- exp(Igamma(m - alpha, N * rho, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# # termRho = Igamma(m - alpha, N * rho, lower=FALSE) / m!
#
# ## ****** TODO CHECK: same factor m! in all terms cancels, use Rgamma to avoid overflows
# termA <- Rgamma(m - alpha, N * A, lower=FALSE)
# termB <- Rgamma(m - alpha, N * B, lower=FALSE)
# termRho <- Rgamma(m - alpha, N * rho, lower=FALSE)
#
# part <- if (lower.tail) termA - termRho else termRho - termB
# return(part / (termA - termB)) # factor C * N^alpha / m! should cancel!
# # denom <- C * N^alpha * (termA - termB) }
#
# ## ****** TODO: add similar code for approximate calculation *******
# # else {
# # factor <- exp(Igamma(m - alpha, N * A, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# # # factor = Igamma(m - alpha, N * A, lower=FALSE) / m!
# # C * N^alpha * factor
# # }
# }
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/posterior_lnre_fzm.R |
print.lnre <- function (x, ...)
{
if (! inherits(x, "lnre")) stop("argument must belong to a subclass of 'lnre'")
summary.lnre(x)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/print_lnre.R |
print.spc <- function (x, all=FALSE, ...)
{
if (! inherits(x, "spc")) stop("argument must be object of class 'spc'")
complete <- attr(x, "m.max") == 0
if (!all && nrow(x) > 10) {
x <- x[1:10,]
complete <- FALSE
}
print.data.frame(x)
if (!complete) cat("\t...\n")
cat("\n")
info <- data.frame(N=attr(x,"N"), V=attr(x,"V"))
if (attr(x, "hasVariances")) info$VV <- attr(x, "VV")
rownames(info) <- ""
print(info)
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/print_spc.R |
print.tfl <- function (x, all=FALSE, ...)
{
if (! inherits(x, "tfl")) stop("argument must be object of class 'tfl'")
idx <- order(x$f, decreasing=TRUE)
all.shown <- TRUE
if (!all && length(idx) > 20) {
idx <- idx[1:20]
all.shown <- FALSE
}
print.data.frame(x[idx,])
if (!all.shown) cat("\t...\n")
cat("\n")
info <- data.frame(N=attr(x,"N"), V=attr(x,"V"))
if (attr(x,"incomplete")) {
info$f.min <- attr(x, "f.min")
info$f.max <- attr(x, "f.max")
}
rownames(info) <- ""
print(info)
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/print_tfl.R |
print.vgc <- function (x, all=FALSE, ...)
{
if (! inherits(x, "vgc")) stop("argument must be object of class 'vgc'")
n <- nrow(x)
if (!all && n > 25) {
idx <- sort(sample(n, 25))
print.data.frame(x[idx,])
cat("\t(random subset of 25 entries shown)\n")
}
else {
print.data.frame(x)
}
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/print_vgc.R |
productivity.measures <- function (obj, measures, data.frame=TRUE, ...) UseMethod("productivity.measures")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/productivity_measures.R |
productivity.measures.default <- function (obj, measures, data.frame=TRUE, ...) {
if (!(is.factor(obj) || is.character(obj) || is.numeric(obj))) stop("'obj' must be a factor, character or integer vector")
obj <- vec2spc(factor(obj))
productivity.measures(obj, measures, data.frame=data.frame, ...)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/productivity_measures_default.R |
productivity.measures.spc <- function (obj, measures, data.frame=TRUE, ...)
{
supported <- qw("V TTR R C k U W P Hapax H S alpha2 K D Entropy eta")
if (missing(measures) || is.null(measures)) measures <- supported
measures <- sapply(measures, match.arg, choices=supported)
res <- numeric(length(measures))
m.max <- attr(obj, "m.max") # if m.max > 0, spectrum is incomplete
if (m.max == 0) m.max <- Inf
## check which measures can be computed from the available spectrum
idx.ok <- (
(measures %in% qw("V TTR R C k U W")) |
(measures %in% qw("P Hapax H") & m.max >= 1) |
(measures %in% qw("S alpha2") & m.max >= 2) |
(m.max == Inf))
res <- numeric(length(measures))
res[!idx.ok] <- NA
## now compute all selected productivity measures
res[idx.ok] <- sapply(measures[idx.ok], function (M.) {
switch(M.,
## measures based on V and N
V = V(obj),
TTR = V(obj) / N(obj),
R = V(obj) / sqrt(N(obj)),
C = log( V(obj) ) / log( N(obj) ),
k = log( V(obj) ) / log(log( N(obj) )),
U = log( N(obj) )^2 / ( log(N(obj)) - log(V(obj)) ),
W = N(obj) ^ (V(obj) ^ -0.172),
## measures based on hapax count (V1)
P = Vm(obj, 1) / N(obj),
Hapax = Vm(obj, 1) / V(obj),
H = 100 * log( N(obj) ) / (1 - Vm(obj, 1) / V(obj)),
## measures based on the first two spectrum elements (V1 and V2)
S = Vm(obj, 2) / V(obj),
alpha2 = 1 - 2 * Vm(obj, 2) / Vm(obj, 1),
## Yule K and Simpson D can only be computed from full spectrum
K = {
m <- as.numeric(obj$m)
Vm <- as.numeric(obj$Vm)
10e4 * (sum(m * m * Vm) - N(obj)) / (N(obj) ^ 2)
},
D = {
m <- as.numeric(obj$m)
Vm <- as.numeric(obj$Vm)
sum(Vm * (m / N(obj)) * ((m - 1) / (N(obj) - 1)))
},
## same for Entropy and eta (only included for evaluation purposes)
Entropy = {
m <- as.numeric(obj$m)
Vm <- as.numeric(obj$Vm)
- sum(Vm * (m / N(obj) * log2(m / N(obj))))
},
eta = {
m <- as.numeric(obj$m)
Vm <- as.numeric(obj$Vm)
- sum(Vm * (m / N(obj) * log2(m / N(obj)))) / log2(V(obj))
},
stop("internal error -- measure '", M., "' not implemented yet"))
})
names(res) <- measures
if (data.frame) as.data.frame(t(res), optional=TRUE) else res
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/productivity_measures_spc.R |
productivity.measures.tfl <- function (obj, measures, data.frame=TRUE, ...) {
productivity.measures(tfl2spc(obj), measures, data.frame=data.frame, ...)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/productivity_measures_tfl.R |
productivity.measures.vgc <- function (obj, measures, data.frame=TRUE, ...)
{
supported <- qw("V TTR R C k U W P Hapax H S alpha2")
if (missing(measures)) measures <- supported
measures <- sapply(measures, match.arg, choices=supported)
res <- numeric(length(measures))
m.max <- attr(obj, "m.max")
## check which measures can be computed from the available spectrum elements
idx.ok <- (
(measures %in% qw("V TTR R C k U W")) |
(measures %in% qw("P Hapax H") & m.max >= 1) |
(measures %in% qw("S alpha2") & m.max >= 2))
res <- matrix(0, nrow=length(obj$N), ncol=length(measures))
res[, !idx.ok] <- NA
## now compute all selected productivity measures
res[, idx.ok] <- sapply(measures[idx.ok], function (M.) {
## same code as in productivity.measures.spc (because of accessor methods),
## but encapsulating this in an internal function would only make the code less transparent
switch(M.,
## measures based on V and N
V = V(obj),
TTR = V(obj) / N(obj),
R = V(obj) / sqrt(N(obj)),
C = log( V(obj) ) / log( N(obj) ),
k = log( V(obj) ) / log(log( N(obj) )),
U = log( N(obj) )^2 / ( log(N(obj)) - log(V(obj)) ),
W = N(obj) ^ (V(obj) ^ -0.172),
## measures based on hapax count (V1)
P = Vm(obj, 1) / N(obj),
Hapax = Vm(obj, 1) / V(obj),
H = 100 * log( N(obj) ) / (1 - Vm(obj, 1) / V(obj)),
## measures based on the first two spectrum elements (V1 and V2)
S = Vm(obj, 2) / V(obj),
alpha2 = 1 - 2 * Vm(obj, 2) / Vm(obj, 1)
## Yule K and Simpson D cannot be computed for vocabulary growth curves
)
})
colnames(res) <- measures
rownames(res) <- N(obj)
if (data.frame) as.data.frame(res, optional=TRUE) else res
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/productivity_measures_vgc.R |
read.multiple.objects <- function (directory, prefix, class=c("spc", "vgc", "tfl")) {
## this is the R way of checking an option against a fixed range of values
class <- match.arg(class)
# obtain list of files matching pattern in specified directory and
# complain and stop if there is no file matching pattern
files <- list.files(directory,pattern=paste("^",prefix,"[\\.]",".+","[\\.]",class,"$",sep=""))
file.number = length(files)
if (file.number==0) {
stop("no file matching pattern ",prefix,".*.",class," found")
}
# now, we go through the list of files and read them to a list
index <- 1
results<-list()
while (index <= file.number) {
# extract whatever occurs between the common prefix and the
# common suffix, using it as an id for the current object
id <- sub(paste("^",prefix,"\\.",sep=""),"",files[index])
id <- sub(paste("\\.",class,"$",sep=""),"",id)
# depending on object type, use different read functions
if (class == "spc") {
results[[id]] <- read.spc(paste(directory,files[index],sep="/"))
}
else {
if (class == "vgc") {
results[[id]] <- read.vgc(paste(directory,files[index],sep="/"))
}
else{
results[[id]] <- read.tfl(paste(directory,files[index],sep="/"))
}
}
index <- index + 1
}
return(results)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/read_multiple_objects.R |
read.spc <- function (file)
{
tmp <- read.delim(auto.gzfile(file))
vars <- colnames(tmp)
if (!("m" %in% vars)) stop("required column 'm' missing from .spc file ", file)
if (!("Vm" %in% vars)) stop("required column 'Vm' missing from .spc file ", file)
variances <- ("VVm" %in% vars)
m <- tmp$m
Vm <- tmp$Vm
if (variances) VVm <- tmp$VVm
if (! is.integer(m)) stop("frequency classes 'm' must be integers in .spc file ", file)
if (any(m < 1)) stop("frequency classes 'm' must be >= 1 in .spc file ", file)
if ( (! is.numeric(Vm)) || any(Vm < 0) )
stop("class sizes 'Vm' must be non-negative numbers in .spc file ", file)
if (variances && (! is.numeric(Vm)) || any(Vm <= 0) )
stop("variances 'VVm' must be positive numbers in .spc file ", file)
if (variances)
warning("variance of expected vocabulary size cannot be reconstructed from disk file")
if (variances) spc(m=m, Vm=Vm, VVm=VVm) else spc(m=m, Vm=Vm)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/read_spc.R |
read.tfl <- function (file, encoding=getOption("encoding"))
{
tmp <- read.delim(auto.gzfile(file, encoding=encoding), as.is=TRUE, quote="", comment.char="")
vars <- colnames(tmp)
if (!("f" %in% vars)) stop("required column 'f' missing from .tfl file ", file)
f <- tmp$f
k <- if ("k" %in% vars) tmp$k else 1:nrow(tmp)
if (!is.integer(f) || any(f < 0))
stop("type frequencies 'f' must be non-negative integers in .tfl file ", file)
if (!is.integer(k))
stop("type IDs 'k' must be integer numbers in .tfl file ", file)
if ("type" %in% vars) tfl(f=f, k=k, type=tmp$type) else tfl(f=f, k=k)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/read_tfl.R |
read.vgc <- function (file)
{
tmp <- read.delim(auto.gzfile(file))
vars <- colnames(tmp)
if (!("N" %in% vars)) stop("required column 'N' missing from .vgc file ", file)
if (!("V" %in% vars)) stop("required column 'V' missing from .vgc file ", file)
m <- 1:9
idx <- sapply(m, function (x) if (paste("V", x, sep="") %in% vars) TRUE else FALSE)
m.max <- sum(idx) # = 0 if no spectrum elements are given in file
if (m.max > 0) {
if (any(m[!idx] <= m.max))
stop("spectrum elements must form uninterrupted sequence 'V1', 'V2', ...")
}
variances <- ("VV" %in% vars)
idx.v <- sapply(m, function (x) if (paste("VV", x, sep="") %in% vars) TRUE else FALSE)
m.max.v <- sum(idx.v)
if (m.max.v > 0) {
if (any(m[!idx.v] <= m.max.v))
stop("spectrum variances must form uninterrupted sequence 'VV1', 'VV2', ...")
}
if (!variances && m.max.v > 0)
stop("column 'VV' must also be given if there are variances 'VV1', etc.")
if (variances && (m.max.v != m.max))
stop("variances 'VVm' must be given for exactly the same frequency classes as expectations 'Vm'")
Vm.list <- if (m.max > 0) tmp[ paste("V", 1:m.max, sep="") ] else NULL
## single index -> data.frame interpreted as list -> always returns list, even for m.max=1
if (variances) {
VVm.list <- if (m.max > 0) tmp[ paste("VV", 1:m.max, sep="") ] else NULL
vgc(N=tmp$N, V=tmp$V, VV=tmp$VV, Vm=Vm.list, VVm=VVm.list)
}
else {
vgc(N=tmp$N, V=tmp$V, Vm=Vm.list)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/read_vgc.R |
sample.spc <- function (obj, N, force.list=FALSE) {
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
if (attr(obj, "m.max") > 0) stop("incomplete frequency spectra are not supported")
if (attr(obj, "expected")) stop("expected frequency spectra are not supported")
if (!is.integer(obj$Vm) && any(obj$Vm != floor(obj$Vm)))
stop("all spectrum elements V_m must be integer values")
if (! (is.numeric(N) && all(N >= 0))) stop("N must be vector of non-negative integers")
if (any(N > N(obj))) stop("can't sample ", max(N), " tokens from 'spc' object with N=", N(obj))
result <- sample.tfl(spc2tfl(obj), N, force.list=TRUE)
result <- lapply(result, tfl2spc)
if (length(N) == 1 && !force.list) {
result[[ 1 ]]
}
else {
result
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/sample_spc.R |
sample.tfl <- function (obj, N, force.list=FALSE) {
if (! inherits(obj, "tfl")) stop("first argument must be object of class 'tfl'")
if (attr(obj, "incomplete")) stop("incomplete type frequency lists are not supported")
if (! (is.numeric(N) && all(N >= 0))) stop("N must be vector of non-negative integers")
idx <- order(N)
if (any(diff(idx) != 1)) {
warning("N must be increasing (elements have been reordered!)")
N <- N[idx]
}
if (any(N > N(obj))) stop("can't sample ", max(N), " tokens from 'tfl' object with N=", N(obj))
f <- obj$f
if (! is.integer(f)) { # convert frequency vector to integer mode
if (any(f != floor(f))) stop("type frequencies must be integer values in 'obj'")
f <- as.integer(f)
}
result <- list()
if (length(N) > 0) {
delta.N <- diff(c(0, N)) # sizes of the consecutive differential samples
complement <- f # frequency vector of complement
sample <- integer(length(f)) # frequency vector of sample (incremented iteratively)
for (i in 1:length(N)) {
split <- zipfR.tflsplit(complement, delta.N[i])
sample <- sample + split$sample
complement <- split$complement
result[[ format(N[i], scientific=FALSE) ]] <-
tfl(f=sample, k=obj$k, type=obj$type, delete.zeros=TRUE)
}
}
if (length(N) == 1 && !force.list) {
result[[ 1 ]]
}
else {
result
}
}
## this is the workhorse function: it splits a type frequency vector into two components:
## a) a random sample of specified size N; b) a "complement" list for the remaining tokens
## (no checks for argument types and validity because this function is only used internally)
zipfR.tflsplit <- function (full, N) {
N <- as.integer(N)
N.full <- sum(full)
n.types <- length(full)
if (N > N.full) {
stop("internal error (N > N(full))")
}
else if (N == N.full) {
list(sample=full, complement=integer(n.types))
}
else if (N == 0) {
list(sample=integer(n.types), complement=full)
}
else {
remain.sample <- N # number of tokens that still have to be moved to sample
remain.total <- N.full # remaining number of tokens that will be considered
complement <- full # will become type frequency vector of complement
sample <- integer(n.types) # initialized to 0's
for (k in 1:n.types) {
## at this point, we have remain.total tokens left (type IDs k and higher), of which
## we need to include remain.sample tokens in our sample; we consider the complement[k]
## instances of type ID k and decide
n.select <- rhyper(1, remain.sample, remain.total-remain.sample, complement[k])
remain.total <- remain.total - complement[k]
## move n.select instances of type k from complement to sample
remain.sample <- remain.sample - n.select
sample[k] <- n.select
complement[k] <- complement[k] - n.select
}
if (remain.sample != 0) stop("internal error (", remain.sample, " missing tokens in sample)")
list(sample=sample, complement=complement)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/sample_tfl.R |
spc <- function (Vm, m=1:length(Vm), VVm=NULL, N=NA, V=NA, VV=NA,
m.max=0, expected=!missing(VVm))
{
if (length(m) != length(Vm)) stop("'m' and 'Vm' must have the same length")
if (missing(N) != missing(V)) stop("'N' and 'V' must always be specified together")
if (missing(m.max) && !missing(N)) {
if (sum(Vm) != V || sum(m*Vm) != N) m.max <- max(m) # spectrum seems to be incomplete
}
incomplete <- (m.max > 0)
if (incomplete && missing(N)) stop("'N' and 'V' must be specified for incomplete spectrum")
variances <- !missing(VVm)
if (variances && !expected) stop("'VVm' may only be specified for expected frequency spectrum")
if (variances && length(VVm) != length(Vm)) stop("'VVm' must have same length as 'm' and 'Vm'")
if (variances && missing(VV)) warning("if variances are present, 'VV' should also be specified")
if (! is.integer(m)) {
if (any(m != floor(m))) stop("class sizes 'm' must be integer values")
m <- floor(m)
}
if (any(m < 1)) stop("frequency classes 'm' must be >= 1")
m <- as.double(m) # make sure there are no integer overflows
Vm <- as.double(Vm)
if (variances) VVm <- as.double(VVm)
# remove empty frequency classes for compact storage
idx <- (Vm != 0)
if (any(!idx)) {
m <- m[idx]
Vm <- Vm[idx]
if (variances) VVm <- VVm[idx]
}
# calculate N anv V automatically (for complete spectrum)
if (missing(N)) {
N <- sum(m * Vm)
V <- sum(Vm)
} else {
N <- as.double(N)
V <- as.double(V)
}
# remove any frequency classes above m.max from the spectrum
if (incomplete && max(m) > m.max) {
idx <- (m <= m.max)
m <- m[idx]
Vm <- Vm[idx]
if (variances) VVm <- VVm[idx]
}
# consistency check for incomplete frequency spectrum
if (incomplete) {
miss.N <- N - sum(m * Vm)
miss.V <- V - sum(Vm)
if (miss.V < -1e-12 * V) stop("inconsistent data (V=",V," < sum(Vm)=",sum(Vm),")")
# tolerant check for error condition miss.V * (m.max+1) > miss.N (because of rounding errors in expected frequency spectra)
if (miss.V * (m.max+1) - miss.N > 1e-8 * N) {
stop("inconsistent data (N=",N," should be at least ", sum(m * Vm) + miss.V * (m.max+1),")")
}
}
# make sure that spectrum elements are in increasing order
idx <- order(m)
if (any(diff(m) != 1)) {
m <- m[idx]
Vm <- Vm[idx]
if (variances) VVm <- VVm[idx]
}
spc <- data.frame(m=m, Vm=Vm)
if (variances) spc$VVm <- VVm
attr(spc, "m.max") <- m.max
attr(spc, "N") <- N
attr(spc, "V") <- V
attr(spc, "expected") <- expected
attr(spc, "hasVariances") <- variances
if (variances) attr(spc, "VV") <- as.double(VV)
class(spc) <- c("spc", class(spc))
spc
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/spc.R |
spc2tfl <- function (spc)
{
if (! inherits(spc, "spc")) stop("argument must be object of class 'spc'")
if (attr(spc, "m.max") > 0) stop("incomplete frequency spectra are not supported")
if (attr(spc, "expected")) stop("expected frequency spectra are not supported")
if (!is.integer(spc$m)) stop("frequency classes in 'spc' must be integer values")
if (!is.integer(spc$Vm) && any(spc$Vm != floor(spc$Vm)))
stop("class sizes in 'spc' must be integer values")
x <- list(values=rev(spc$m), lengths=rev(as.integer(spc$Vm)))
class(x) <- "rle"
tfl(inverse.rle(x))
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/spc2tfl.R |
spc.interp <- function (obj, N, m.max=max(obj$m), allow.extrapolation=FALSE)
{
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
if (attr(obj, "m.max") > 0) stop("cannot interpolate from incomplete frequency spectrum")
if (attr(obj, "expected")) stop("cannot interpolate from expected frequency spectrum")
if (! (is.numeric(N) && all(N >= 0) && length(N) == 1))
stop("'N' must be a single non-negative integer")
N0 <- N(obj)
if (any(N > N0) && !allow.extrapolation)
stop("binomial extrapolation to N=", max(N), " from N0=", N0, " not allowed!")
if (m.max < 1) stop("'m.max' must be >= 1")
E.Vm <- EVm(obj, 1:m.max, N, allow.extrapolation=allow.extrapolation)
if (missing(m.max)) { # don't use EV() for full spectrum, may be inconsistent!
spc(Vm=E.Vm, m=1:m.max, expected=TRUE)
}
else {
E.V <- EV(obj, N, allow.extrapolation=allow.extrapolation)
spc(Vm=E.Vm, m=1:m.max, V=E.V, N=N, m.max=m.max, expected=TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/spc_interp.R |
spc.vector <- function (obj, m.min=1, m.max=15, all=FALSE)
{
if (! inherits(obj, "spc")) stop("argument must be object of class 'spc'")
if (all) m.max <- max(obj$m)
if (m.min < 1) stop("'m.min' must be >= 1")
if (m.max < m.min) stop("'m.max' must be >= 'm.min'")
Vm.spc(obj, m.min:m.max)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/spc_vector.R |
summary.lnre <- function (object, ...)
{
if (! inherits(object, "lnre")) stop("argument must belong to a subclass of 'spc'")
object$util$print(object) # name of model + parameters
cat("Population size: S =", object$S, "\n")
cat("Sampling method: "); # type of sampling / approximate calculations
if (object$multinomial) cat("multinomial") else cat("Poisson")
cat(", ");
if (object$exact) cat("with exact calculations.") else cat("approximations are allowed.")
cat("\n")
if ("bootstrap" %in% names(object)) cat("Bootstrapping data available for", length(object$bootstrap), "replicates\n")
cat("\n")
spc <- object$spc
if (!is.null(spc)) { # estimated from observed spectrum -> show comparison & gof
N <- N(spc)
cat("Parameters estimated from sample of size N = ", N, ":\n", sep="")
report <- cbind(c(V(spc), EV(object, N)),
rbind(Vm(spc, 1:5), EVm(object, 1:5, N)))
colnames(report) <- c("V", "V1", "V2", "V3", "V4", "V5")
rownames(report) <- c(" Observed:", " Expected:")
report <- as.data.frame(round(report, digits=2))
report[[" "]] <- c("...", "...")
print(report)
cat("\n")
cat("Goodness-of-fit (multivariate chi-squared test):\n")
gof <- object$gof
rownames(gof) <- " " # should produce nice alignment with other displays
print(gof)
} else {
cat("(Model parameters have not been estimated from observed spectrum.)\n")
}
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/summary_lnre.R |
summary.spc <- function (object, ...)
{
if (! inherits(object, "spc")) stop("argument must be object of class 'spc'")
m.max <- attr(object, "m.max")
K <- 8 # show first K spectrum elements (V_1 ... V_K)
cat("zipfR object for ")
if (attr(object, "expected")) cat("expected ")
cat("frequency spectrum")
if (m.max > 0) cat(", incomplete (m <= ", m.max, ")", sep="")
if (attr(object, "hasVariances")) cat(", with variances")
cat("\n")
cat("Sample size: N =", attr(object, "N"), "\n")
cat("Vocabulary size: V =", attr(object, "V"), "\n")
cat("Class sizes: Vm = ")
if (m.max > 0 && m.max < K) {
Vm <- Vm(object, m=1:m.max)
}
else {
Vm <- Vm(object, m=1:K)
}
cat(Vm)
if (m.max > 0 || max(object$m) > K) cat(" ...")
cat("\n")
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/summary_spc.R |
summary.tfl <- function (object, ...)
{
if (! inherits(object, "tfl")) stop("argument must be object of class 'tfl'")
incomplete <- attr(object, "incomplete")
f.min <- attr(object, "f.min")
f.max <- attr(object, "f.max")
f <- object$f
cat("zipfR object for ")
if (incomplete) cat("incomplete ")
cat("frequency spectrum")
if (incomplete) cat(", restricted to range", f.min, "...", f.max)
cat("\n")
cat("Sample size: N =", attr(object, "N"), "\n")
cat("Vocabulary size: V =", attr(object, "V"), "\n")
if (!incomplete) {
cat("Range of freq's: f =", f.min, "...", f.max, "\n")
cat("Mean / median: mu =", mean(f), ", M =", median(f), "\n")
cat("Hapaxes etc.: V1 =", sum(f==1), ", V2 =", sum(f==2), "\n")
}
if (attr(object, "hasTypes")) {
idx <- order(object$type)
all.shown <- !(length(idx) > 6)
if (!all.shown) idx <- idx[1:6]
cat("Types: ", as.character(object$type[idx]))
if (!all.shown) cat(" ...")
cat("\n")
}
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/summary_tfl.R |
summary.vgc <- function (object, ...)
{
if (! inherits(object, "vgc")) stop("argument must be object of class 'vgc'")
cat("zipfR object for ")
if (attr(object, "expected")) cat("expected ")
cat("vocabulary growth curve")
if (attr(object, "hasVariances")) cat(", with variances")
cat("\n")
m.max <- attr(object, "m.max")
cat(nrow(object), "samples for N =", min(object$N), "...", max(object$N), "\n")
if (m.max > 0) cat("Spectrum elements included up to m =", m.max, "\n")
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/summary_vgc.R |
tfl <- function (f, k=seq_along(f), type=NULL, f.min=min(f), f.max=max(f),
incomplete=!(missing(f.min) && missing(f.max)), N=NA, V=NA,
delete.zeros=FALSE)
{
if (! (is.numeric(f) && all(f >= 0))) stop("'f' must be non-negative integer vector")
if (length(k) != length(f)) stop("'k' and 'f' must have the same length")
hasTypes <- !is.null(type)
if (hasTypes && length(type) != length(k)) stop("'type' must have the same length as 'k' and 'f'")
f <- as.double(f) # make sure there are no integer overflows
if (delete.zeros) {
idx <- f == 0
if (any(idx)) {
f <- f[!idx]
k <- k[!idx]
if (hasTypes) type <- type[!idx]
}
}
if (missing(N) != missing(V)) stop("'N' and 'V' must always be specified together")
if (missing(N)) {
if (incomplete) stop("'N' and 'V' must be specified for incomplete spectrum")
N <- sum(f)
V <- sum(f > 0)
} else {
N <- as.double(N)
V <- as.double(V)
}
## limit frequencies to specified range
if (missing(f.min) & length(f) == 0) f.min <- 0 # avoid warnings for empty TFLs
if (missing(f.max) & length(f) == 0) f.max <- 0
idx <- f.min <= f & f <= f.max
if (any(!idx)) {
k <- k[idx]
f <- f[idx]
if (hasTypes) type <- type[idx]
incomplete <- TRUE # now tfl is known to be incomplete, even if input data wasn't
}
## ensure that rows are sorted properly (IDs 'k' must be in ascending order)
idx <- order(k)
if (any(diff(idx) != 1)) {
k <- k[idx]
f <- f[idx]
if (hasTypes) type <- type[idx]
}
tfl <- data.frame(k=k, f=f)
if (hasTypes) {
tfl$type <- type
rownames(tfl) <- type
}
attr(tfl, "N") <- N
attr(tfl, "V") <- V
attr(tfl, "f.min") <- f.min
attr(tfl, "f.max") <- f.max
attr(tfl, "incomplete") <- incomplete
attr(tfl, "hasTypes") <- hasTypes
class(tfl) <- c("tfl", class(tfl))
tfl
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/tfl.R |
tfl2spc <- function (tfl)
{
if (! inherits(tfl, "tfl")) stop("argument must be object of class 'tfl'")
if (attr(tfl, "incomplete")) stop("incomplete type frequency lists are not supported")
f <- tfl$f
if (!is.integer(f)) {
if (! all(tfl$f == floor(tfl$f))) stop("type frequencies in 'tfl' must be integer values")
f <- as.integer(f)
}
idx <- tfl$f > 0
f <- if (!all(idx)) tfl$f[idx] else tfl$f
x <- rle(sort(f))
spc(Vm=x$lengths, m=x$values)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/tfl2spc.R |
vec2spc <- function (x)
{
tfl2spc(vec2tfl(x)) # could be optimized by calculating spectrum directly: table(table(x))
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/vec2spc.R |
vec2tfl <- function (x)
{
freqs <- table(as.factor(x))
idx <- order(freqs, decreasing=TRUE)
result <- tfl(f=as.vector(freqs)[idx], type=names(freqs)[idx])
if (N(result) != length(x))
stop("internal error (inconsistency between sample size and type frequency list")
result
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/vec2tfl.R |
vec2vgc <- function (x, steps=200, stepsize=NA, m.max=0)
{
x <- as.vector(x) # token vector representing a random or observed sample
.N <- length(x) # size of this sample
if (! (is.numeric(m.max) && length(m.max) == 1 && 0 <= m.max && m.max <= 9))
stop("'m.max' must be an integer in the range 1 ... 9")
if (!missing(steps) && !missing(stepsize))
stop("please specify either 'steps' or 'stepsize', but not both")
if (!missing(stepsize)) {
.N.steps <- rev(seq(.N, 1, -stepsize)) # make sure last entry is for full sample
}
else {
# (more or less) equally spaced integers, first step at N=1, last step at N=full sample
.N.steps <- floor(0:(steps-1) * (.N - .5) / (steps-1)) + 1
.N.steps <- unique(.N.steps) # avoid duplicates if steps >= .N (or close to it)
}
idx.first <- !(duplicated(x)) # idx.first marks first occurrences of types
.V <- cumsum(idx.first)[.N.steps] # vocabulary size = number of first occurrences up to this point
.Vm.list <- list()
if (m.max > 0) {
idx.m <- idx.first
for (m in 1:m.max) {
## idx.m marks m-th occurrences, idx.m.1 marks (m+1)-th occurrences
x[idx.m] <- NA # 1st, 2nd, ..., m-th occurrences now set to NA (cumulatively)
idx.m.1 <- !duplicated(x) # marks (m+1)-th occurrences, except for first NA
idx.m.1[1] <- FALSE # first element is always first a occurrence, so set to NA in first iteration
## every m-th occurrence increases V_m, every (m+1)-th occurrence decreases it
.Vm <- cumsum(idx.m) - cumsum(idx.m.1)
.Vm.list <- c(.Vm.list, list(.Vm[.N.steps]))
idx.m <- idx.m.1 # for next iteration
}
}
vgc(N=.N.steps, V=.V, Vm=.Vm.list)
}
## usage example:
## x <- readLines(choose.file())
## vec2spc(x)
## vec2vgc(x, m.max=5)
## for whitespace-spearated tokens (you don't want to do that):
## x <- scan(file, what=character(0), quote=""))
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/vec2vgc.R |
vgc <- function (N, V, Vm=NULL, VV=NULL, VVm=NULL, expected=FALSE, check=TRUE)
{
if (length(N) != length(V)) stop("'N' and 'V' must have the same length")
if (any(N < 0)) stop("sample sizes 'N' must be non-negative integers")
if (check) {
if (any(diff(N) < 0)) stop("sample sizes 'N' must be increasing")
if (any(V < 0)) stop("vocabulary sizes 'V' must be non-negative")
if (any(diff(V) < 0)) stop("inconsistent decrease in vocabulary size 'V'")
}
N <- as.double(N) # make sure to avoid integer overflows
V <- as.double(V)
if (!missing(Vm)) {
if (!is.list(Vm)) Vm <- as.list(Vm) # allow V1 to be specified as plain vector
for (v.m in Vm) {
if (!(is.numeric(v.m))) stop("elements of 'Vm' must be numeric vectors")
if (length(v.m) != length(N)) stop("vectors in 'Vm' must have the same length as 'N' and 'V'")
if (check) {
if (any(v.m < 0)) stop("spectrum elements in 'Vm' must be non-negative")
}
}
Vm <- lapply(Vm, as.double) # make sure to avoid integer overflows
}
m.max <- length(Vm) # m.max = 0 if Vm is not specified
## -- this limitation seems arbitrary, so it has been disabled
## if (m.max > 9) stop("at most 9 spectrum elements allowed in 'Vm'")
variances <- !missing(VV)
if (variances && !is.list(VVm)) VVm <- list(VVm) # same as above
m.max.var <- length(VVm) # spectrum elements for which variances are specified
if (variances && (m.max.var != m.max))
stop("variances 'VVm' must be specified for the same spectrum elements as in 'Vm'")
if (!variances && m.max.var > 0)
stop("variance 'VV' missing (but variances 'VVm' are specified)")
if (variances) {
for (vv.m in VVm) {
if (!is.numeric(vv.m)) stop("elements of 'VVm' must be numeric vectors")
if (length(vv.m) != length(N)) stop("vectors in 'VVm' must have the same length as 'N' and 'V'")
if (check) {
if (any(vv.m < 0)) stop("variances in 'VVm' must be non-negative")
}
}
VVm <- lapply(VVm, as.double)
}
vgc <- data.frame(N=N, V=V)
if (variances) vgc$VV <- VV
if (m.max > 0) {
for (i in 1:m.max) {
vgc[[ paste("V", i, sep="") ]] <- Vm[[i]]
if (variances) vgc[[ paste("VV", i, sep="") ]] <- VVm[[i]]
}
}
attr(vgc, "m.max") <- m.max
attr(vgc, "expected") <- expected || variances
attr(vgc, "hasVariances") <- variances
class(vgc) <- c("vgc", class(vgc))
vgc
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/vgc.R |
vgc.interp <- function (obj, N, m.max=0, allow.extrapolation=FALSE)
{
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
if (attr(obj, "m.max") > 0) stop("cannot interpolate from incomplete frequency spectrum")
if (attr(obj, "expected")) stop("cannot interpolate from expected frequency spectrum")
if (! (is.numeric(N) && all(N >= 0))) stop("'N' must be a vector of non-negative integers")
if (any(diff(N) < 0)) {
warning("'N' must be increasing (data points have been reordered!)")
N <- sort(N)
}
if (!missing(m.max) && !(length(m.max) == 1 && is.numeric(m.max) && 0 <= m.max && m.max <= 9))
stop("'m.max' must be a single integer in the range 1 ... 9")
N0 <- N(obj)
if (any(N > N0) && !allow.extrapolation)
stop("binomial extrapolation to N=", max(N), " from N0=", N0, " not allowed!")
E.V <- EV(obj, N, allow.extrapolation=allow.extrapolation)
if (m.max > 0) {
E.Vm <- lapply(1:m.max, # make list of growth curves for E[V_m(N)]
function (.m) EVm(obj, .m, N, allow.extrapolation=allow.extrapolation))
vgc(N=N, V=E.V, Vm=E.Vm, expected=TRUE)
}
else {
vgc(N=N, V=E.V, expected=TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/vgc_interp.R |
write.spc <- function (spc, file)
{
if (! inherits(spc, "spc")) stop("'spc' argument must be of class 'spc'")
if ( (length(file) != 1) || (! is.character(file)) )
stop("'file' argument must be a single character string")
if (attr(spc, "m.max") > 0)
warning("saving incomplete frequency spectrum, which cannot be restored from disk file!")
if (attr(spc, "hasVariances"))
warning("variance of expected vocabulary size cannot be saved to disk file!")
write.table(spc, file=auto.gzfile(file), quote=FALSE, sep="\t", row.names=FALSE, col.names=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/write_spc.R |
write.tfl <- function (tfl, file, encoding=getOption("encoding"))
{
if (! inherits(tfl, "tfl")) stop("'tfl' argument must be of class 'tfl'")
if ( (length(file) != 1) || (! is.character(file)) )
stop("'file' argument must be a single character string")
if (attr(tfl, "incomplete"))
warning("saving incomplete type frequency list, which cannot be restored from disk file!")
write.table(tfl, file=auto.gzfile(file, encoding=encoding), quote=FALSE, sep="\t", row.names=FALSE, col.names=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/write_tfl.R |
write.vgc <- function (vgc, file)
{
if (! inherits(vgc, "vgc")) stop("'vgc' argument must be of class 'vgc'")
if ( (length(file) != 1) || (! is.character(file)) )
stop("'file' argument must be a single character string")
write.table(vgc, file=auto.gzfile(file), quote=FALSE, sep="\t", row.names=FALSE, col.names=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/write_vgc.R |
zipfR.par <- function (..., bw.mode=FALSE)
{
args <- list(...)
known.pars <- ls(.PAR)
if (! length(args)) { # --> zipfR.par()
res <- as.list(.PAR)
return(res[order(names(res))])
}
else if (is.null(names(args))) {
if (length(args) == 1 && is.list(args[[1]])) { # --> zipfR.par(par.save)
args <- args[[1]] # then fall through to default case below
} else { # --> zipfR.par("lty", "lwd")
pars <- as.character(unlist(args))
if (bw.mode) { # bw.mode=TRUE -> return corresponding B/W mode parameters if possible
pars.bw <- paste(pars, "bw", sep=".")
idx <- pars.bw %in% known.pars
if (any(idx)) pars[idx] <- pars.bw[idx]
}
return( if (length(pars) == 1) .PAR[[ pars[1] ]] else as.list(.PAR)[pars] )
}
}
invalid <- !(names(args) %in% known.pars) # --> zipfR.par(lwd.bw=2, bw=TRUE, ...)
if (any(invalid)) {
warning("invalid zipfR graphics parameter(s) ", paste(names(args)[invalid], collapse=", "), " ignored")
args <- args[! invalid]
}
old <- as.list(.PAR)[names(args)] # make sure we get a list (can't call zipfR.arg(names))
for (key in names(args)) { .PAR[[ key ]] <- check.par(key, args[[ key ]]) }
return(invisible(old))
}
## private environment for graphics parameter data
## (I wonder whether this is the way it's supposed to work, but at least it works ...)
.PAR <- new.env()
## styles for colour plots
.PAR$lty <- c(rep("solid", 7), rep("dashed", 7))
.PAR$lwd <- rep(c(3,3,3,3,3,3,3), 2)
.PAR$col <- rep(c("#808080", "#D65F5F", "#6ACC65", "#4878CF", "#C4AD66", "#77BEDB", "#B47CC7"), 2) # seaborn muted
.PAR$pch <- rep(c(1, 3, 15, 2, 20), 3)
.PAR$barcol <- rep(c("#666666", "#C44E52", "#55A868", "#4C72B0", "#CCB974", "#64B5CD", "#8172B2"), 2) # seaborn normal
## styles for b/w plots
.PAR$lty.bw <- rep(c("solid", "dashed", "12", "solid", "dashed"), 2)
.PAR$lwd.bw <- rep(c(2,2,3,1,2), 2)
.PAR$col.bw <- rep(c("grey30", "black", "black", "black", "grey30"), 2)
.PAR$pch.bw <- rep(c(1, 3, 15, 2, 20), 2)
.PAR$barcol.bw <- rep(c("black", "grey50", "white", "grey70", "grey20"), 2)
## whether to produce b/w graphics by default
.PAR$bw <- FALSE
## for the zipfR plotutils functions
.PAR$device <- if (capabilities()["aqua"]) "quartz" else "x11"
.PAR$init.par <- list()
.PAR$width <- 6
.PAR$height <- 6
.PAR$bg <- "white"
.PAR$pointsize <- 12
## interal helper function to check validity of graphics parameters
check.par <- function (name, value) {
if (name %in% c("bw")) { # Boolean parameters
value <- as.logical(value)
if (is.na(value) || length(value) != 1) stop("parameter '",name,"' must be a Boolean value (logical)")
}
else if (name == "device") {
supported <- c("x11", "png", "eps", "pdf")
if (capabilities()["aqua"]) supported <- c("quartz", supported)
value <- match.arg(value, supported)
}
else if (name == "init.par") {
if (is.null(value)) value <- list() # init.par=NULL translates to empty list
if (! is.list(value)) stop("parameter 'init.par' must be a list of name=value pairs")
}
else if (name %in% c("lwd", "lwd.bw")) {
if (! is.numeric(value)) stop("parameter '",name,"' must be a numeric vector")
if (length(value) > 10) warning("extra style options for parameter '",name,"' ignored")
value <- rep(value, length.out=10)
}
else if (name %in% c("lty", "col", "lty.bw", "col.bw")) {
if (length(value) > 10) warning("extra style options for parameter '",name,"' ignored")
value <- rep(value, length.out=10)
}
value
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/zipfR_par.R |
zipfR.begin.plot <- function (device=zipfR.par("device"), filename="",
width=zipfR.par("width"), height=zipfR.par("height"),
bg=zipfR.par("bg"), pointsize=zipfR.par("pointsize"))
{
on.screen <- device %in% c("x11", "quartz") # whether this is an on-screen device
if (!on.screen) {
if (device %in% c("png", "eps", "pdf")) {
if (missing(filename) || filename=="") stop("filename= is required for ",device," plot device")
}
else {
stop("unsupported plot device '",device,"'")
}
}
already.open <- FALSE # on-screen device may already be open
if (.PLOT$id > 0 && .PLOT$id %in% dev.list()) {
if (on.screen) {
if (device == .PLOT$config$device # we can reuse open screen device unless parameters have changed
&& width == .PLOT$config$width
&& height == .PLOT$config$height
&& bg == .PLOT$config$bg
&& pointsize == .PLOT$config$pointsize) {
dev.set(.PLOT$id) # in case user has switched to a different device
.PLOT$device <- device # indicate device is open
already.open <- TRUE
}
} else {
zipfR.end.plot() # close active file plot before starting new device
}
}
if (!already.open) {
## open new device of specified type with specified parameters
png.res <- 150 # default resolution for PNG files is 150 dpi
switch(device,
x11 = dev.new(width=width, height=height, bg=bg, pointsize=pointsize),
quartz = dev.new(width=width, height=height, bg=bg, pointsize=pointsize),
png = png(filename=paste(filename, "png", sep="."), width=width*png.res, height=height*png.res, res=png.res, bg=bg, pointsize=pointsize),
eps = postscript(file=paste(filename, "eps", sep="."), width=width, height=height, bg=bg, pointsize=pointsize, onefile=FALSE, horizontal=FALSE, paper="special"),
pdf = pdf(file=paste(filename, "pdf", sep="."), width=width, height=height, bg=bg, pointsize=pointsize, onefile=FALSE, paper="special")
)
## record information about active device in private .PLOT environment
.PLOT$device <- device
.PLOT$id <- dev.cur()
.PLOT$config <- list(device=device, width=width, height=height, bg=bg, pointsize=pointsize)
}
## initialize graphics parameters
init.par <- zipfR.par("init.par")
if (!is.null(init.par) && length(init.par) > 0) do.call(par, init.par)
invisible(.PLOT$id)
}
zipfR.end.plot <- function (shutdown=FALSE)
{
if (.PLOT$id <= 0 || .PLOT$device == "") stop("no graphics device active at the moment")
if (.PLOT$device %in% c("x11", "quartz") && !shutdown) {
## don't close screen device when plot is finished (only when starting new plot with different geometry)
.PLOT$device <- ""
}
else {
dev.off(.PLOT$id)
.PLOT$id <- 0
.PLOT$device <- ""
.PLOT$config <- list(device="", width=0, height=0, bg="", pointsize=0)
}
}
zipfR.pick.device <- function(args=commandArgs())
{
known.devices <- c("x11", "quartz", "eps", "pdf", "png")
flags <- c(paste("-", known.devices, sep=""), paste("--", known.devices, sep=""))
devices <- rep(known.devices, 2)
found <- match(args, flags) # either pointer to recognized flag or NA
idx <- !is.na(found) # these are the recognized flags
if (sum(idx) > 1)
stop("multiple graphics devices specified (", paste(flags[found[idx]], collapse=", "),")")
if (sum(idx) > 0)
zipfR.par(device=devices[found[idx]])
}
## private environment for information about current plot device
.PLOT <- new.env()
.PLOT$id <- 0
.PLOT$device <- ""
.PLOT$config <- list(device="", width=0, height=0, bg="", pointsize=0)
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/zipfR_plotutils.R |
## package initialization
.onLoad <- function (libname, pkgname)
{
## this used to switch to "quartz" as default plotting device in the R.app GUI on Mac OS X,
## which is now used by default whenever available (and selected directly in zipfR_par.R)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/zzz_INIT.R |
## some internal utility functions
qw <- function (x) unlist(strsplit(x, "\\s+", perl=TRUE))
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/zzz_UTIL.R |
### R code from vignette source 'zipfr-tutorial.Rnw'
###################################################
### code chunk number 1: zipfr-tutorial.Rnw:48-49
###################################################
options(useFancyQuotes=FALSE)
###################################################
### code chunk number 2: zipfr-tutorial.Rnw:80-81 (eval = FALSE)
###################################################
## install.packages("zipfR")
###################################################
### code chunk number 3: zipfr-tutorial.Rnw:93-94
###################################################
library(zipfR)
###################################################
### code chunk number 4: zipfr-tutorial.Rnw:98-99 (eval = FALSE)
###################################################
## ?zipfR
###################################################
### code chunk number 5: zipfr-tutorial.Rnw:146-147
###################################################
ItaRi.spc
###################################################
### code chunk number 6: zipfr-tutorial.Rnw:171-172
###################################################
summary(ItaRi.spc)
###################################################
### code chunk number 7: zipfr-tutorial.Rnw:180-182
###################################################
N(ItaRi.spc)
V(ItaRi.spc)
###################################################
### code chunk number 8: zipfr-tutorial.Rnw:193-195
###################################################
Vm(ItaRi.spc, 1)
Vm(ItaRi.spc, 1:5)
###################################################
### code chunk number 9: zipfr-tutorial.Rnw:203-204
###################################################
Vm(ItaRi.spc, 1) / N(ItaRi.spc)
###################################################
### code chunk number 10: zipfr-tutorial.Rnw:211-213 (eval = FALSE)
###################################################
## plot(ItaRi.spc)
## plot(ItaRi.spc, log="x")
###################################################
### code chunk number 11: zipfr-tutorial.Rnw:218-219
###################################################
plot(ItaRi.spc)
###################################################
### code chunk number 12: zipfr-tutorial.Rnw:222-223
###################################################
plot(ItaRi.spc, log="x")
###################################################
### code chunk number 13: zipfr-tutorial.Rnw:239-240
###################################################
with(ItaRi.spc, plot(m, Vm, main="Frequency Spectrum"))
###################################################
### code chunk number 14: zipfr-tutorial.Rnw:309-310
###################################################
head(ItaRi.emp.vgc)
###################################################
### code chunk number 15: zipfr-tutorial.Rnw:324-325
###################################################
ItaRi.emp.vgc
###################################################
### code chunk number 16: zipfr-tutorial.Rnw:329-330
###################################################
summary(ItaRi.emp.vgc)
###################################################
### code chunk number 17: zipfr-tutorial.Rnw:339-340
###################################################
plot(ItaRi.emp.vgc, add.m=1)
###################################################
### code chunk number 18: zipfr-tutorial.Rnw:369-371
###################################################
ItaRi.bin.vgc <- vgc.interp(ItaRi.spc, N(ItaRi.emp.vgc), m.max=1)
head(ItaRi.bin.vgc)
###################################################
### code chunk number 19: zipfr-tutorial.Rnw:395-397
###################################################
plot(ItaRi.emp.vgc, ItaRi.bin.vgc,
legend=c("observed", "interpolated"))
###################################################
### code chunk number 20: zipfr-tutorial.Rnw:428-430
###################################################
V(ItaRi.emp.vgc)[N(ItaRi.emp.vgc) == 50000]
V(ItaRi.spc)
###################################################
### code chunk number 21: zipfr-tutorial.Rnw:478-479
###################################################
ItaRi.fzm <- lnre("fzm", ItaRi.spc, exact=FALSE)
###################################################
### code chunk number 22: zipfr-tutorial.Rnw:494-495
###################################################
summary(ItaRi.fzm)
###################################################
### code chunk number 23: zipfr-tutorial.Rnw:513-514
###################################################
ItaRi.fzm.spc <- lnre.spc(ItaRi.fzm, N(ItaRi.fzm))
###################################################
### code chunk number 24: zipfr-tutorial.Rnw:519-520
###################################################
plot(ItaRi.spc, ItaRi.fzm.spc, legend=c("observed", "fZM"))
###################################################
### code chunk number 25: zipfr-tutorial.Rnw:531-532
###################################################
ItaRi.fzm.vgc <- lnre.vgc(ItaRi.fzm, (1:100) * 28e3)
###################################################
### code chunk number 26: zipfr-tutorial.Rnw:549-551
###################################################
plot(ItaRi.emp.vgc, ItaRi.fzm.vgc, N0=N(ItaRi.fzm),
legend=c("observed", "fZM"))
###################################################
### code chunk number 27: zipfr-tutorial.Rnw:612-614
###################################################
set.seed(42)
ItaRi.sub.spc <- sample.spc(ItaRi.spc, N=700000)
###################################################
### code chunk number 28: zipfr-tutorial.Rnw:621-623
###################################################
ItaRi.sub.fzm <- lnre("fzm", ItaRi.sub.spc, exact=FALSE)
ItaRi.sub.fzm
###################################################
### code chunk number 29: zipfr-tutorial.Rnw:633-634
###################################################
ItaRi.sub.fzm.vgc <- lnre.vgc(ItaRi.sub.fzm, N=N(ItaRi.emp.vgc))
###################################################
### code chunk number 30: zipfr-tutorial.Rnw:644-646
###################################################
plot(ItaRi.bin.vgc, ItaRi.sub.fzm.vgc, N0=N(ItaRi.sub.fzm),
legend=c("interpolated", "fZM"))
###################################################
### code chunk number 31: zipfr-tutorial.Rnw:685-687
###################################################
V(ItaUltra.spc)
V(ItaRi.spc)
###################################################
### code chunk number 32: zipfr-tutorial.Rnw:693-695
###################################################
N(ItaUltra.spc)
N(ItaRi.spc)
###################################################
### code chunk number 33: zipfr-tutorial.Rnw:702-704
###################################################
ItaUltra.fzm <- lnre("fzm", ItaUltra.spc, exact=FALSE)
ItaUltra.ext.vgc <- lnre.vgc(ItaUltra.fzm, N(ItaRi.emp.vgc))
###################################################
### code chunk number 34: zipfr-tutorial.Rnw:709-710
###################################################
plot(ItaUltra.ext.vgc, ItaRi.bin.vgc, legend=c("ultra-", "ri-"))
###################################################
### code chunk number 35: zipfr-tutorial.Rnw:724-725 (eval = FALSE)
###################################################
## data(package="zipfR")
###################################################
### code chunk number 36: zipfr-tutorial.Rnw:729-730 (eval = FALSE)
###################################################
## ?ItaRi.spc
###################################################
### code chunk number 37: zipfr-tutorial.Rnw:787-788
###################################################
V(Brown100k.spc)
###################################################
### code chunk number 38: zipfr-tutorial.Rnw:797-799
###################################################
Vseen <- V(Brown100k.spc) - Vm(Brown100k.spc, 1)
Vseen
###################################################
### code chunk number 39: zipfr-tutorial.Rnw:805-806
###################################################
Vseen / V(Brown100k.spc)
###################################################
### code chunk number 40: zipfr-tutorial.Rnw:812-813
###################################################
Vm(Brown100k.spc, 1) / N(Brown100k.spc)
###################################################
### code chunk number 41: zipfr-tutorial.Rnw:843-845
###################################################
Brown100k.zm <- lnre("zm", Brown100k.spc)
Brown100k.zm
###################################################
### code chunk number 42: zipfr-tutorial.Rnw:862-863
###################################################
EV(Brown100k.zm, c(1e6, 10e6, 100e6))
###################################################
### code chunk number 43: zipfr-tutorial.Rnw:870-871
###################################################
Vseen / EV(Brown100k.zm, c(1e6, 10e6, 100e6))
###################################################
### code chunk number 44: zipfr-tutorial.Rnw:876-877
###################################################
1 - (Vseen / EV(Brown100k.zm, c(1e6, 10e6, 100e6)))
###################################################
### code chunk number 45: zipfr-tutorial.Rnw:885-887
###################################################
N(Brown.spc)
V(Brown.spc)
###################################################
### code chunk number 46: zipfr-tutorial.Rnw:891-892
###################################################
EV(Brown100k.zm, N(Brown.spc))
###################################################
### code chunk number 47: zipfr-tutorial.Rnw:899-901
###################################################
1 - (Vseen / V(Brown.spc))
1 - (Vseen / EV(Brown100k.zm, N(Brown.spc)))
###################################################
### code chunk number 48: zipfr-tutorial.Rnw:927-928
###################################################
Brown.zm.spc <- lnre.spc(Brown100k.zm, N(Brown.spc))
###################################################
### code chunk number 49: zipfr-tutorial.Rnw:939-940
###################################################
EV(Brown100k.zm, N(Brown.spc)) - Vseen
###################################################
### code chunk number 50: zipfr-tutorial.Rnw:946-948
###################################################
sum(Vm(Brown.zm.spc, 1))
sum(Vm(Brown.zm.spc, 1:2))
###################################################
### code chunk number 51: zipfr-tutorial.Rnw:951-952
###################################################
sum(Vm(Brown.zm.spc, 1:6))
###################################################
### code chunk number 52: zipfr-tutorial.Rnw:961-963
###################################################
Noov.zm <- sum(Vm(Brown.zm.spc, 1:6) * (1:6))
Noov.zm
###################################################
### code chunk number 53: zipfr-tutorial.Rnw:967-968
###################################################
Noov.zm / N(Brown.spc)
###################################################
### code chunk number 54: zipfr-tutorial.Rnw:977-978
###################################################
V(Brown.spc) - Vseen
###################################################
### code chunk number 55: zipfr-tutorial.Rnw:983-984
###################################################
sum(Vm(Brown.spc, 1:13))
###################################################
### code chunk number 56: zipfr-tutorial.Rnw:989-992
###################################################
Noov.emp <- sum(Vm(Brown.spc, 1:13) * (1:13))
Noov.emp
Noov.emp / N(Brown.spc)
###################################################
### code chunk number 57: zipfr-tutorial.Rnw:1014-1015
###################################################
Brown10M.zm.spc <- lnre.spc(Brown100k.zm, 10e6)
###################################################
### code chunk number 58: zipfr-tutorial.Rnw:1026-1027
###################################################
sum(Vm(Brown10M.zm.spc, 1:18) * (1:18))
###################################################
### code chunk number 59: zipfr-tutorial.Rnw:1032-1033
###################################################
sum(Vm(Brown10M.zm.spc, 1:18))
###################################################
### code chunk number 60: zipfr-tutorial.Rnw:1039-1040
###################################################
EV(Brown100k.zm, 10e6) - sum(Vm(Brown10M.zm.spc, 1:18))
| /scratch/gouwar.j/cran-all/cranData/zipfR/inst/doc/zipfr-tutorial.R |
.zpssAlphaHat <- function(x, value){
(VGAM::zeta(x)-value)^2
}
#' Calculates initial values for the parameters of the models.
#'
#' The selection of appropiate initial values to compute the maximum likelihood estimations
#' reduces the number of iterations which in turn, reduces the computation time.
#' The initial values proposed by this function are computed using the first two empirical
#' frequencies.
#'
#' @param data Matrix of count data.
#' @param model Specify the model that requests the initial values (default='zipf').
#'
#' @details
#'
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies. The argument \code{model} refers to the selected model of those
#' implemented in the package. The possible values are: \emph{zipf}, \emph{moezipf}, \emph{zipfpe},
#' \emph{zipfpss} or its zero truncated version \emph{zt_zipfpss}. By default, the selected model is the Zipf one.
#'
#' For the MOEZipf, the Zipf-PE and the zero truncated Zipf-PSS models that contain the Zipf model as
#' a particular case, the \eqn{\beta} value will correspond to the one of the Zipf model (i.e. \eqn{\beta = 1} for the MOEZipf,
#' \eqn{\beta = 0} for the Zipf-PE and \eqn{\lambda = 0} for the zero truncated Zipf-PSS model) and the initial value for \eqn{\alpha}
#' is set to be equal to:
#' \deqn{\alpha_0 = log_2 \big (\frac{f_r(1)}{f_r(2)} \big),}
#' where \eqn{f_r(1)} and \eqn{f_r(2)} are the empirical relative frequencies of one and two.
#' This value is obtained equating the two empirical probabilities to their theoritical ones.
#'
#' For the case of the Zipf-PSS the proposed initial values are obtained equating the empirical probability of zero
#' to the theoretical one which gives:
#' \deqn{\lambda_0 = -log(f_r(0)),}
#' where \eqn{f_r(0)} is the empirical relative frequency of zero. The initial value of \eqn{\alpha} is obtained
#' equating the ratio of the theoretical probabilities at zero and one to the empirical ones. This gives place to:
#' \deqn{\alpha_0 = \zeta^{-1}(\lambda_0 * f_r(0)/f_r(1)),}
#' where \eqn{f_r(0)} and \eqn{f_r(1)} are the empirical relative frequencies associated to the values 0 and 1 respectively.
#' The inverse of the Riemman Zeta function is obtained using the \code{optim} routine.
#'
#' @return Returns the initial values of the parameters for a given distribution.
#' @examples
#' data <- rmoezipf(100, 2.5, 1.3)
#' data <- as.data.frame(table(data))
#' data[,1] <- as.numeric(levels(data[,1])[data[,1]])
#' initials <- getInitialValues(data, model='zipf')
#' @references{ Güney, Y., Tuaç, Y., & Arslan, O. (2016). Marshall–Olkin distribution: parameter estimation and
#' application to cancer data. Journal of Applied Statistics, 1-13.}
#' @export
getInitialValues <- function(data, model='zipf'){
freq1 <- data[which(data[,1] == 1),][2][[1]]
freq2 <- data[which(data[,1] == 2),][2][[1]]
if(length(freq1) == 0 || length(freq2) == 0){
alpha0 <- 1.001
} else{
alpha0 <- max(log2(freq1/freq2), 1.001, na.rm = TRUE)
}
if(model=='zipf'){
return(list(init_alpha = round(alpha0, 4)))
} else if(model=='moezipf'){
return(list(init_alpha = round(alpha0, 4), init_beta = 1.001))
} else if(model == 'zipfpe'){
return(list(init_alpha = round(alpha0, 4), init_beta = 0.001))
} else if(model == 'zt_zipfpss'){
return(list(init_alpha = round(alpha0, 4), init_lambda = 1.001))
} else if(model=='zipfpss'){
if(length(freq1) == 0 || length(freq2) == 0){
# lambda0 <- 1.001
# alpha0 <- 1.001
return(list(init_alpha = 1.001, init_lambda = 1.001))
} else{
return(list(init_alpha = alpha0, init_lambda = 1.001))
# lambda0 <- max(-log(freq1/sum(data[,2])), 0.001)
# value <- lambda0*freq1/freq2
# est <- stats::optim(1.01,
# .zpssAlphaHat,
# value = value,
# method = 'L-BFGS-B',
# lower=1.001,
# upper = 30)
# alpha0 <- max(1.001, round(est$par, 4))
}
# return(list(init_alpha = alpha0, init_lambda = round(lambda0, 4)))
} else{
stop('You should introduced a valid model')
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/getInitialValues.R |
#' The Marshal-Olkin Extended Zipf Distribution (MOEZipf).
#'
#' Probability mass function, cumulative distribution function, quantile function and random number
#' generation for the MOEZipf distribution with parameters \eqn{\alpha} and \eqn{\beta}. The support of the MOEZipf
#' distribution are the strictly positive integer numbers large or equal than one.
#'
#' @name moezipf
#' @aliases dmoezipf
#' @aliases pmoezipf
#' @aliases qmoezipf
#' @aliases rmoezipf
#'
#' @param x,q Vector of positive integer values.
#' @param p Vector of probabilities.
#' @param n Number of random values to return.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 1} ).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta > 0} ).
#' @param log,log.p Logical; if TRUE, probabilities p are given as log(p).
#' @param lower.tail Logical; if TRUE (default), probabilities are \eqn{P[X \leq x]}, otherwise, \eqn{P[X > x]}.
#' @details The \emph{probability mass function} at a positive integer value \eqn{x} of the MOEZipf distribution with
#' parameters \eqn{\alpha} and \eqn{\beta} is computed as follows:
#'
#' \deqn{p(x | \alpha, \beta) = \frac{x^{-\alpha} \beta \zeta(\alpha) }{[\zeta(\alpha) - \bar{\beta} \zeta (\alpha, x)] [\zeta (\alpha) - \bar{\beta} \zeta (\alpha, x + 1)]},\, x = 1,2,...,\, \alpha > 1, \beta > 0, }
#'
#' where \eqn{\zeta(\alpha)} is the Riemann-zeta function at \eqn{\alpha}, \eqn{\zeta(\alpha, x)}
#' is the Hurtwitz zeta function with arguments \eqn{\alpha} and x, and \eqn{\bar{\beta} = 1 - \beta}.
#'
#' The \emph{cumulative distribution function}, at a given positive integer value \eqn{x},
#' is computed as \eqn{F(x) = 1 - S(x)}, where the survival function \eqn{S(x)} is equal to:
#' \deqn{S(x) = \frac{\beta\, \zeta(\alpha, x + 1)}{\zeta(\alpha) - \bar{\beta}\,\zeta(\alpha, x + 1)},\, x = 1, 2, .. }
#'
#' The quantile of the MOEZipf\eqn{(\alpha, \beta)} distribution of a given probability value p
#' is equal to the quantile of the Zipf\eqn{(\alpha)} distribution at the value:
#' \deqn{p\prime = \frac{p\,\beta}{1 + p\,(\beta - 1)}}
#'
#' The quantiles of the Zipf\eqn{(\alpha)} distribution are computed by means of the \emph{tolerance}
#' package.
#'
#' To generate random data from a MOEZipf one applies the \emph{quantile} function over \emph{n} values randomly generated
#' from an Uniform distribution in the interval (0, 1).
#'
#' @return {
#' \code{dmoezipf} gives the probability mass function,
#' \code{pmoezipf} gives the cumulative distribution function,
#' \code{qmoezipf} gives the quantile function, and
#' \code{rmoezipf} generates random values from a MOEZipf distribution.}
#'
#' @references {
#' Casellas, A. (2013) \emph{La distribució Zipf Estesa segons la transformació Marshall-Olkin}. Universitat Politécnica de Catalunya.
#'
#' Devroye L. (1986) Non-Uniform Random Variate Generation. Springer, New York, NY.
#'
#' Duarte-López, A., Prat-Pérez, A., & Pérez-Casany, M. (2015). \emph{Using the Marshall-Olkin Extended Zipf Distribution in Graph Generation}. European Conference on Parallel Processing, pp. 493-502, Springer International Publishing.
#'
#' Pérez-Casany, M. and Casellas, A. (2013) \emph{Marshall-Olkin Extended Zipf Distribution}. arXiv preprint arXiv:1304.4540.
#'
#' Young, D. S. (2010). \emph{Tolerance: an R package for estimating tolerance intervals}. Journal of Statistical Software, 36(5), 1-39.
#' }
#'
#' @examples
#' dmoezipf(1:10, 2.5, 1.3)
#' pmoezipf(1:10, 2.5, 1.3)
#' qmoezipf(0.56, 2.5, 1.3)
#' rmoezipf(10, 2.5, 1.3)
#'
NULL
#> NULL
.prec.moezipf.checkXvalue <- function(x){
if(!is.numeric(x) | any(x < 1) | any(x%%1 != 0)) {
stop('The x value is not included into the support of the distribution.')
}
}
.prec.moezipf.checkparams <- function(alpha, beta){
if(!is.numeric(alpha) | alpha <= 1){
stop('Incorrect alpha parameter. This parameter should be greater than one.')
}
if(!is.numeric(beta) | beta < 0){
stop('Incorrect beta parameter. You should provide a numeric value.')
}
}
.dmoezipf.default <- function(x, alpha, beta, z){
.prec.moezipf.checkXvalue(x)
num <- beta * z * x^(-alpha)
den <- (z - (1 - beta)*.zeta_x(alpha, x))*(z - (1 - beta) * .zeta_x(alpha, x + 1))
return(num/den)
}
#' @rdname moezipf
#' @export
dmoezipf <- function(x, alpha, beta, log = FALSE){
.prec.moezipf.checkparams(alpha, beta)
z <- VGAM::zeta(alpha)
values <- sapply(x, .dmoezipf.default, alpha = alpha, beta = beta, z = z)
if(log){
return(log(values))
}
return(values)
}
.survival.default <- function(x, alpha, beta, z){
.prec.moezipf.checkXvalue(x)
zetaX <- .zeta_x(alpha, x + 1)
num <- beta * (zetaX)
den <- (z - (1 - beta)*(zetaX))
return(num/den)
}
#' @rdname moezipf
#' @export
pmoezipf <- function(q, alpha, beta, log.p = FALSE, lower.tail = TRUE){
.prec.moezipf.checkparams(alpha, beta)
z <- VGAM::zeta(alpha)
srvvl <- sapply(q, .survival.default, alpha = alpha, beta = beta, z = z, simplify = TRUE)
if(!log.p & lower.tail){
return(1 - srvvl)
} else{
if(!log.p & !lower.tail){
return(srvvl)
} else{
if(log.p & !lower.tail){
return(log(srvvl))
}
return(log(1-srvvl))
}
}
}
.qmoezipf.default <- function(x, beta){
if(any(x > 1) | any(x < 0)){
stop('Wrong values for the p parameter.')
}
return((x*beta)/(1 + x*(beta-1)))
}
#' @rdname moezipf
#' @export
qmoezipf <- function(p, alpha, beta, log.p = FALSE, lower.tail = TRUE){
.prec.moezipf.checkparams(alpha, beta)
if(length(p) < 1){
stop('Wrong values for the p parameter.')
}
if(log.p & lower.tail){
p <- exp(p)
} else{
if(log.p & !lower.tail){
p <- 1-exp(p)
} else{
if(!log.p & !lower.tail){
p <- 1-p
}
}
}
u <- sapply(p, .qmoezipf.default, beta = beta)
data <- tolerance::qzipfman(u, s = alpha, b = NULL, N = Inf)
return(data)
}
#' @rdname moezipf
#' @export
rmoezipf <- function(n, alpha, beta){
.prec.moezipf.checkXvalue(n)
.prec.moezipf.checkparams(alpha, beta)
uValues <- stats::runif(n, 0, 1)
data <- qmoezipf(uValues, alpha, beta)
# print(data)
# lvl <- names(sort(table(data), decreasing = TRUE))
# uniqVal <- 1:length(unique(data))
# data <- uniqVal[match(data, lvl)]
return(data)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/moezipf.R |
#' MOEZipf parameters estimation.
#'
#' For a given sample of strictly positive integer numbers, usually of the type of ranking data or
#' frequencies of frequencies data, estimates the parameters of the MOEZipf distribution by means of
#' the maximum likelihood method. The input data should be provided as a frequency matrix.
#'
#' @param data Matrix of count data in form of a table of frequencies.
#' @param init_alpha Initial value of \eqn{\alpha} parameter (\eqn{\alpha > 1}).
#' @param init_beta Initial value of \eqn{\beta} parameter (\eqn{\beta > 0}).
#' @param level Confidence level used to calculate the confidence intervals (default 0.95).
#' @param object An object from class "moezipfR" (output of \emph{moezipfFit} function).
#' @param x An object from class "moezipfR" (output of \emph{moezipfFit} function).
#' @param ... Further arguments to the generic functions. The extra arguments are passing to the \emph{\link{optim}} function.
#' @details
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies.
#'
#' The log-likelihood function is equal to:
#'
#' \deqn{l(\alpha, \beta; x) = -\alpha \sum_{i = 1} ^m f_{a}(x_{i}) log(x_{i}) + N (log(\beta) + \log(\zeta(\alpha)))}
#' \deqn{ - \sum_{i = 1} ^m f_a(x_i) log[(\zeta(\alpha) - \bar{\beta}\zeta(\alpha, x_i)(\zeta(\alpha) - \bar{\beta}\zeta(\alpha, x_i + 1)))], }
#' where \eqn{f_{a}(x_i)} is the absolute frequency of \eqn{x_i}, \eqn{m} is the number of different values in the sample and \eqn{N} is the sample size,
#' i.e. \eqn{N = \sum_{i = 1} ^m x_i f_a(x_i)}.
#'
#' By default the initial values of the parameters are computed using the function \code{getInitialValues}.
#'
#' The function \emph{\link{optim}} is used to estimate the parameters.
#' @return Returns a \emph{moezipfR} object composed by the maximum likelihood parameter estimations
#' jointly with their standard deviation and confidence intervals. It also contains
#' the value of the log-likelihood at the maximum likelihood estimator.
#'
#' @examples
#' data <- rmoezipf(100, 2.5, 1.3)
#' data <- as.data.frame(table(data))
#' data[,1] <- as.numeric(as.character(data[,1]))
#' data[,2] <- as.numeric(as.character(data[,2]))
#' initValues <- getInitialValues(data, model='moezipf')
#' obj <- moezipfFit(data, init_alpha = initValues$init_alpha, init_beta = initValues$init_beta)
#' @seealso \code{\link{getInitialValues}}.
#' @importFrom stats AIC BIC coef fitted logLik
#' @export
moezipfFit <- function(data, init_alpha = NULL, init_beta = NULL, level = 0.95, ...){
Call <- match.call()
if(is.null(init_alpha) || is.null(init_beta)){
initValues <- getInitialValues(data, model = 'moezipf')
init_alpha <- initValues$init_alpha
init_beta <- initValues$init_beta
}
if(!is.numeric(init_alpha) || !is.numeric(init_beta)){
stop('Wrong intial values for the parameters.')
}
tryCatch(
{
estResults <- .paramEstimationBase(data, c(init_alpha, init_beta), .mloglikelihood, ...)
estAlpha <- as.numeric(estResults$results$par[1])
estBeta <- as.numeric(estResults$results$par[2])
paramSD <- sqrt(diag(solve(estResults$results$hessian)))
paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estBeta, level)
structure(class = "moezipfR", list(alphaHat = estAlpha,
betaHat = estBeta,
alphaSD = paramSD[1],
betaSD = paramSD[2],
alphaCI = c(paramsCI[1,1],paramsCI[1,2]),
betaCI = c(paramsCI[2,1],paramsCI[2,2]),
logLikelihood = -estResults$results$value,
hessian = estResults$results$hessian,
call = Call))
},
error=function(cond) {
print(cond)
return(NA)
})
}
#' @rdname moezipfFit
#' @export
residuals.moezipfR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
residual.values <- dataMatrix[, 2] - fitted(object)
return(residual.values)
}
#' @rdname moezipfFit
#' @export
fitted.moezipfR <- function(object, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], dmoezipf, alpha = object[['alphaHat']],
beta = object[['betaHat']])
return(fitted.values)
}
#' @rdname moezipfFit
#' @export
coef.moezipfR <- function(object, ...){
estimation <- matrix(nrow = 2, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['betaHat']], object[['betaSD']], object[['betaCI']][1], object[['betaCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "beta")
estimation
}
#' @rdname moezipfFit
#' @export
plot.moezipfR <- function(x, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting MOEZipf Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x), col="blue")
graphics::legend("topright", legend = c('Observations', 'MOEZipf Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
#' @rdname moezipfFit
#' @export
print.moezipfR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('Beta: %s\n', format(eval(x[['call']]$init_beta), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
#' @rdname moezipfFit
#' @export
summary.moezipfR <- function(object, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object))
}
#' @rdname moezipfFit
#' @export
logLik.moezipfR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
#' @rdname moezipfFit
#' @export
AIC.moezipfR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 2)
return(aic)
}
#' @rdname moezipfFit
#' @export
BIC.moezipfR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2]))
return(bic)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/moezipfFit.R |
#' Expected value.
#'
#' Computes the expected value of the MOEZipf distribution for given values of parameters
#' \eqn{\alpha} and \eqn{\beta}.
#'
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 2}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta > 0}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the mean value of the distribution.
#'
#' @details
#' The mean of the distribution only exists for \eqn{\alpha} strictly greater than 2.
#' It is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' moezipfMean(2.5, 1.3)
#' moezipfMean(2.5, 1.3, 10^(-3))
#' @export
moezipfMean <- function(alpha, beta, tolerance = 10^(-4)){
return(moezipfMoments(1, alpha, beta, tolerance = tolerance))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/moezipfMean.R |
.moment <- function(x, k, zeta_alpha, alpha, beta){
(zeta_alpha * beta * x^(-alpha + k))/((zeta_alpha - (1 - beta) * .zeta_x(alpha, x)) * (zeta_alpha - (1 - beta) * .zeta_x(alpha, x + 1)))
}
#' Distribution Moments.
#'
#' General function to compute the k-th moment of the MOEZipf distribution for any integer value \eqn{k \geq 1},
#' when it exists. The k-th moment exists if and only if \eqn{\alpha > k + 1}.
#' For k = 1, this function returns the same value as the \link{moezipfMean} function.
#'
#' @param k Order of the moment to compute.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > k + 1}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta > 0}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the k-th moment of the distribution.
#'
#' @details
#' The k-th moment is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' moezipfMoments(3, 4.5, 1.3)
#' moezipfMoments(3, 4.5, 1.3, 1*10^(-3))
#' @export
moezipfMoments <- function(k, alpha, beta, tolerance = 10^(-4)){
if(!is.numeric(k) || !is.numeric(alpha) || !is.numeric(beta) || !is.numeric(tolerance)){
stop("Wrong input parameters!!")
}
if(alpha < k + 1){
stop(sprintf('Alpha value must be greater than %s.', k + 1))
}
if(!k%%1 == 0 || k < 1){
stop('Wrong moment value!!. You have to provide a possitive and integer value.')
}
aux <- 1
x <- 1
result <- 0
zeta_alpha <- VGAM::zeta(alpha)
while(aux > tolerance) {
aux <- sapply(x, .moment, k = k, zeta_alpha = zeta_alpha, alpha = alpha, beta = beta)
result <- result + aux
x <- x + 1
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/moezipfMoments.R |
#' Variance of the MOEZipf distribution.
#'
#' Computes the variance of the MOEZipf distribution for given values of \eqn{\alpha} and \eqn{\beta}.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 3}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta > 0}).
#' @param tolerance Tolerance used in the calculations. (default = \eqn{10^{-4}})
#' @return A positive real value corresponding to the variance of the distribution.
#'
#' @details
#' The variance of the distribution only exists for \eqn{\alpha} strictly greater than 3.
#'
#' @examples
#' moezipfVariance(3.5, 1.3)
#' @seealso \code{\link{moezipfMoments}}, \code{\link{moezipfMean}}.
#' @export
moezipfVariance <- function(alpha, beta, tolerance = 10^(-4)){
moment1 <- moezipfMoments(1, alpha, beta, tolerance)
moment2 <- moezipfMoments(2, alpha, beta, tolerance)
return(moment2 - (moment1^2))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/moezipfVariance.R |
# Hurwitz Zeta function ------------------------------
.zeta_x<-function(alpha, x) {
if(!is.numeric(alpha) || !is.numeric(x)){
stop("Wrong input values!")
}
if(x < 1){
stop("Error!! The 'x' have to be greater or iqual than one.")
}
aux <- 0
if(x == 1) {
VGAM::zeta(alpha)
}
else {
VGAM::zeta(alpha) - sum((1:(x-1))^(-alpha))
}
}
# Likelihood functions -----------------------------
.QValue <- function(alpha, beta, x){
log(VGAM::zeta(alpha) - (1-beta)*.zeta_x(alpha, x))
}
.mloglikelihood <- function(param, nSize, freq, values){
a <- param[1]
b <- param[2]
-(nSize*log(b) + nSize * log(VGAM::zeta(a)) - a * sum(freq * log(values))
- sum(freq * sapply(values, .QValue, alpha = a, beta = b))
- sum(freq * sapply(values + 1, .QValue, alpha = a, beta = b)))
}
.zipf_pmf <- function(k, alpha){
(k^(-alpha))/VGAM::zeta(alpha)
}
.zeta_Distribution <- function(alpha, nSize, freq, values){
-( -alpha*sum(freq * log(values)) - nSize*log(VGAM::zeta(alpha)))
}
.getSpectrumValues <- function(data){
frequencies <- as.numeric(data[, 2])
values <- as.numeric(data[, 1])
nSize <- sum(frequencies)
return(list(values = values, frequencies = frequencies,
nSize = nSize))
}
.paramEstimationBase <- function(x, initValues, likelihoodFunc, ...){
result <- NULL
tryCatch({
statistics <- list(nSize = sum(as.numeric(x[, 2])),
values = as.numeric(x[, 1]), frequencies = as.numeric(x[, 2]))
result <- stats::optim(par = initValues, likelihoodFunc,
nSize = statistics$nSize, freq = statistics$frequencies,
values = statistics$values, hessian = TRUE, ...)
return(list(results = result, stats=statistics))
},
error = function(e) {
print(e$message)
})
}
# Metrics --------------------
.get_AIC <- function(loglike, K) {
-2*loglike + 2*K
}
.get_BIC <- function(loglike, K, N) {
-2*loglike + K*log(N)
}
# Kolmogorov - Smirnov Test ---------------------
# Utils ----------------
.getConfidenceIntervals <- function(paramSD, alpha, beta, level){
result <- matrix(nrow=2, ncol=2)
levelCoef <- round(stats::qnorm(1-((1-level)/2)), 2)
offset <- levelCoef * paramSD
result[1, ] <- c(alpha - offset[1], alpha + offset[1])
result[2, ] <- c(beta - offset[2], beta + offset[2])
colnames(result) <- c('Inf. CI', 'Sup. CI')
rownames(result) <- c('alpha', 'beta')
return(result)
}
.getConfidenceIntervalsForZeroInflated <- function(paramSD, alpha, beta, w, level){
result <- matrix(nrow=3, ncol=2)
levelCoef <- round(stats::qnorm(1-((1-level)/2)), 2)
offset <- levelCoef * paramSD
result[1, ] <- c(alpha - offset[1], alpha + offset[1])
result[2, ] <- c(beta - offset[2], beta + offset[2])
result[3, ] <- c(w - offset[3], w + offset[3])
colnames(result) <- c('Inf. CI', 'Sup. CI')
rownames(result) <- c('alpha', 'beta', 'w')
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/utils.R |
#' The Zero Inflated Zipf-Poisson Stop Sum Distribution (ZI Zipf-PSS).
#'
#' Probability mass function for the zero inflated Zipf-PSS distribution with parameters \eqn{\alpha}, \eqn{\lambda} and \eqn{w}.
#' The support of thezero inflated Zipf-PSS distribution are the positive integer numbers including the zero value.
#'
#' @name zi_zipfpss
#' @aliases d_zi_zipfpss
#'
#' @param x Vector of positive integer values.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 1} ).
#' @param lambda Value of the \eqn{\lambda} parameter (\eqn{\lambda > 0} ).
#' @param w Value of the \eqn{w} parameter (0 < \eqn{w < 1} ).
#' @param log Logical; if TRUE, probabilities p are given as log(p).
#'
#' @details
#' The support of the \eqn{\lambda} parameter increases when the distribution is truncated at zero being
#' \eqn{\lambda \geq 0}. It has been proved that when \eqn{\lambda = 0} one has the degenerated version of the distribution at one.
#'
#' @references {
#' Panjer, H. H. (1981). Recursive evaluation of a family of compound
#' distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 22-26.
#'
#' Sundt, B., & Jewell, W. S. (1981). Further results on recursive evaluation of
#' compound distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 27-39.
#' }
NULL
#> NULL
.prec.zi_zipfpss.checkparams <- function(alpha, lambda, w){
if(!is.numeric(alpha) | alpha <= 1){
stop('Incorrect alpha parameter. This parameter should be greater than one.')
}
if(!is.numeric(lambda) | lambda < 0){
stop('Incorrect lambda parameter. You should provide a numeric value.')
}
if(!is.numeric(w) | any(w <= 0) | any(w > 1)){
stop('Incorrect w parameter. You should provide a numeric value.')
}
}
#' @rdname zi_zipfpss
#' @export
d_zi_zipfpss <- function(x, alpha, lambda, w, log = FALSE){
.prec.zipfpss.checkXvalue(x)
.prec.zi_zipfpss.checkparams(alpha, lambda, w)
values <- sapply(x, function(i, alpha, lambda, w, log){
if(i == 0){
return(w + (1 - w)*dzipfpss(i, alpha, lambda, log))
} else {
return((1-w)*dzipfpss(i, alpha, lambda, log))
}
}, alpha = alpha, lambda = lambda, w = w, log = log)
return(values)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zi_zipfpss.R |
.log_lik_zi_ZipfPSS <-function(values, freq, w, alpha, lambda){
f_0 <- freq[values == 0]
t1 <- f_0 * log(w + (1 - w) * exp(-lambda))
t2 <- log(1 - w) * (sum(freq) - f_0)
t3 <- sum(freq * dzipfpss(values, alpha, lambda, log = TRUE))
-(t1 + t2 + t3)
}
.zi_zpss_mle <- function(par, values, freq) {
alpha <- as.numeric(par[1])
lambda <- as.numeric(par[2])
w <- as.numeric(par[3])
# print(c(w, alpha, lambda))
return(.log_lik_zi_ZipfPSS(values, freq, w, alpha, lambda))
}
#' Zero Inflated Zipf-PSS parameters estimation.
#'
#' For a given sample of strictly positive integer numbers, usually of the type of ranking data or
#' frequencies of frequencies data, estimates the parameters of the zero inflated Zipf-PSS distribution by means of
#' the maximum likelihood method. The input data should be provided as a frequency matrix.
#'
#' @param data Matrix of count data in form of table of frequencies.
#' @param init_alpha Initial value of \eqn{\alpha} parameter (\eqn{\alpha > 1}).
#' @param init_lambda Initial value of \eqn{\lambda} parameter (\eqn{\lambda > 0}).
#' @param init_w Initial value of \eqn{w} parameter (\eqn{0 < w < 1}).
#' @param level Confidence level used to calculate the confidence intervals (default 0.95).
#' @param object An object from class "zpssR" (output of \emph{zipfpssFit} function).
#' @param x An object from class "zpssR" (output of \emph{zipfpssFit} function).
#' @param ... Further arguments to the generic functions. The extra arguments are passing
#' to the \emph{\link{optim}} function.
#'
#' @details
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies.
#'
#' @references {
#' Panjer, H. H. (1981). Recursive evaluation of a family of compound
#' distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 22-26.
#'
#' Sundt, B., & Jewell, W. S. (1981). Further results on recursive evaluation of
#' compound distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 27-39.
#' }
#'
#' @examples
#' data <- rzipfpss(100, 2.5, 1.3)
#' data <- as.data.frame(table(data))
#' data[,1] <- as.numeric(as.character(data[,1]))
#' data[,2] <- as.numeric(as.character(data[,2]))
#' obj <- zipfpssFit(data, init_alpha = 1.5, init_lambda = 1.5)
#' @seealso \code{\link{getInitialValues}}.
#' @export
zi_zipfpssFit <- function(data, init_alpha = 1.5, init_lambda = 1.5, init_w = 0.1, level=0.95, ...){
Call <- match.call()
if(!is.numeric(init_alpha) || !is.numeric(init_lambda) || !is.numeric(init_w)){
stop('Wrong intial values for the parameters.')
}
tryCatch({
res <- stats::optim(par = c(init_alpha, init_lambda, init_w), .zi_zpss_mle,
values = data[, 1],
freq = data[, 2],
method = "L-BFGS-B",
lower = c(1, 1, 0.0001),
upper = c(Inf, Inf, 0.9999),
hessian = TRUE)
estAlpha <- as.numeric(res$par[1])
estLambda <- as.numeric(res$par[2])
estW <- as.numeric(res$par[3])
paramSD <- sqrt(diag(solve(res$hessian)))
paramsCI <- .getConfidenceIntervalsForZeroInflated(paramSD, estAlpha, estLambda, estW, level)
structure(class = "zi_zipfpssR", list(alphaHat = estAlpha,
lambdaHat = estLambda,
wHat = estW,
alphaSD = paramSD[1],
lambdaSD = paramSD[2],
wSD = paramSD[3],
alphaCI = c(paramsCI[1,1], paramsCI[1,2]),
lambdaCI = c(paramsCI[2,1], paramsCI[2,2]),
wCI = c(paramsCI[3,1], paramsCI[3,2]),
logLikelihood = -res$value,
hessian = res$hessian,
call = Call))
}, error = function(e){
print(c('Error', e))
})
}
#' @rdname zi_zipfpssFit
#' @export
residuals.zi_zipfpssR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
fitted.values <- fitted(object)
residual.values <- dataMatrix[, 2] - fitted.values
return(residual.values)
}
#' @rdname zi_zipfpssFit
#' @export
fitted.zi_zipfpssR <- function(object, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], d_zi_zipfpss,
alpha = object[['alphaHat']], lambda = object[['lambdaHat']],
w = object[['wHat']])
return(fitted.values)
}
#' @rdname zi_zipfpssFit
#' @export
coef.zi_zipfpssR <- function(object, ...){
estimation <- matrix(nrow = 3, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['lambdaHat']], object[['lambdaSD']], object[['lambdaCI']][1], object[['lambdaCI']][2])
estimation[3, ] <- c(object[['wHat']], object[['wSD']], object[['wCI']][1], object[['wCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "lambda", "w")
estimation
}
#' @rdname zi_zipfpssFit
#' @export
plot.zi_zipfpssR <- function(x, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting Zipf-PSS Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x), col="blue")
graphics::legend("topright", legend = c('Observations', 'Zipf-PSS Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
#' @rdname zi_zipfpssFit
#' @export
print.zi_zipfpssR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('lambda: %s\n', format(eval(x[['call']]$init_lambda), digits = 3)))
cat(sprintf('w: %s\n', format(eval(x[['call']]$init_w), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
#' @rdname zi_zipfpssFit
#' @export
summary.zi_zipfpssR <- function(object, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object))
}
#' @rdname zi_zipfpssFit
#' @export
logLik.zi_zipfpssR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
#' @rdname zi_zipfpssFit
#' @export
AIC.zi_zipfpssR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 3)
return(aic)
}
#' @rdname zi_zipfpssFit
#' @export
BIC.zi_zipfpssR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 3, sum(dataMatrix[, 2]))
return(bic)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zi_zipfpssFit.R |
# Hurwitz Zeta function ------------------------------
.zeta_x<-function(alpha, x) {
if(!is.numeric(alpha) || !is.numeric(x)){
stop("Wrong input values!")
}
if(x < 1){
stop("Error!! The 'x' have to be greater or iqual than one.")
}
aux <- 0
if(x == 1) {
VGAM::zeta(alpha)
}
else {
VGAM::zeta(alpha) - sum((1:(x-1))^(-alpha))
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfExtUtils.R |
#' The Zipf-Polylog Distribution (Zipf-Polylog).
#'
#' Probability mass function of the Zipf-Polylog distribution with parameters \eqn{\alpha} and \eqn{\beta}.
#' The support of the Zipf-Polylog distribution are the strictly positive integer numbers large or equal
#' than one.
#'
#' @name zipfPolylog
#' @aliases dzipfpolylog
#' @aliases pzipfpolylog
#' @aliases qzipfpolylog
#' @aliases rzipfpolylog
#'
#' @param x Vector of positive integer values.
#' @param p Vector of probabilities.
#' @param n Number of random values to return.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 1} ).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta > 0} ).
#' @param nSum The number of terms used for computing the Polylogarithm function (Default = 1000).
#' @param log,log.p Logical; if TRUE, probabilities p are given as log(p).
#' @param lower.tail Logical; if TRUE (default), probabilities are \eqn{P[X \leq x]}, otherwise, \eqn{P[X > x]}.
#' @details The \emph{probability mass function} at a positive integer value \eqn{x} of the Zipf-Polylog distribution with
#' parameters \eqn{\alpha} and \eqn{\beta} is computed as follows:
#'
#' @return {
#' \code{dzipfpolylog} gives the probability mass function
#' }
#' @importFrom copula polylog
#' @examples
#' dzipfpolylog(1:10, 1.61, 0.98)
#' pzipfpolylog(1:10, 1.61, 0.98)
#' qzipfpolylog(0.8, 1.61, 0.98)
NULL
#> NULL
.prec.zipfpolylog.checkXvalue <- function(x){
if(!is.numeric(x) || any(x < 1) || any(x%%1 != 0)) {
stop('The x value is not included into the support of the distribution.')
}
}
.prec.zipfpolylog.checkparams <- function(alpha, beta){
if(!is.numeric(beta) | beta < 0 | beta > 1){
stop('Incorrect beta parameter. You should provide a numeric value.')
}
# if(!is.numeric(alpha) || (beta == 1 && alpha < 1) || (beta < 1 && alpha < 0)){
# stop('Incorrect alpha parameter. This parameter should be greater than one.')
# }
}
.dzipfPolylog.default <- function(x, alpha, beta, nSum){
return((beta^x * x^(-alpha))/copula::polylog(z = beta, s = alpha, method = 'sum', n.sum = nSum))
}
#' @rdname zipfPolylog
#' @export
dzipfpolylog <- function(x, alpha, beta, log = FALSE, nSum = 1000){
.prec.zipfpolylog.checkXvalue(x)
.prec.zipfpolylog.checkparams(alpha, beta)
values <- sapply(x, .dzipfPolylog.default, alpha = alpha, beta = beta, nSum = nSum)
if(log){
return(log(values))
}
return(values)
}
.pzipfpoly <- function(x, alpha, beta, nSum = 1000){
liValue <- copula::polylog(z = beta, s = alpha, method = 'sum', n.sum = nSum)
sumValues <- sum(sapply(1:x, function(i, alpha, beta){
return(beta^(i) * i^(-alpha))
}, alpha = alpha, beta = beta))
cumProb <- (1/liValue) * sumValues
return(cumProb)
}
#' @rdname zipfPolylog
#' @export
pzipfpolylog <- function(x, alpha, beta, log.p = FALSE, lower.tail = TRUE, nSum = 1000){
.prec.zipfpolylog.checkXvalue(x)
.prec.zipfpolylog.checkparams(alpha, beta)
finalProbs <-sapply(x, .pzipfpoly, alpha = alpha, beta = beta, nSum = nSum)
if(!log.p & lower.tail){
return(finalProbs)
} else{
if(!log.p & !lower.tail){
return(1 - finalProbs)
} else{
if(log.p & !lower.tail){
return(log(1 - finalProbs))
}
return(log(finalProbs))
}
}
}
#' @rdname zipfPolylog
#' @export
qzipfpolylog <- function(p, alpha, beta, log.p = FALSE, lower.tail = TRUE, nSum = 1000){
.prec.zipfpolylog.checkparams(alpha, beta)
if(length(p) < 1){
stop('Wrong value(s) for the p parameter.')
}
if(log.p & lower.tail){
p <- exp(p)
} else{
if(log.p & !lower.tail){
p <- 1-exp(p)
} else{
if(!log.p & !lower.tail){
p <- 1-p
}
}
}
# if(length(which(p > 1 || p < 0 )) > 0){
if(any(p > 1) | any(p < 0 )){
stop('There is a wrong value(s) in the p parameter.')
}
# liValue <- copula::polylog(z = -log(beta), s = alpha, method = 'sum', n.sum = nSum)
# uprime <- p*liValue
i <- 1
p_i <- pzipfpolylog(i, alpha = alpha, beta = beta)
repeat{
if(p <= p_i){
# print(i)
return(i)
}
i <- i + 1
p_i <- pzipfpolylog(i, alpha = alpha, beta = beta)
}
# x <- 1
# # print((uprime <= ((beta^x)*(x^(-alpha)))))
# cumValue <- exp(-alpha*log(x)-(-log(beta)*x)) #((beta^x)*(x^(-alpha)))
# while(uprime <= cumValue){
# print(c(sprintf('x = %s, uprime = %s, cumulative = %s', x, uprime,cumValue)))
# x <- x + 1
# # print(cumValue)
# # print(((beta^x)*(x^(-alpha))))
# # print(beta^x)
# # print(beta)
# # print(x^-alpha)
# print(exp(-alpha*log(x)-(-log(beta)*x)))
# cumValue <- cumValue + exp(-alpha*log(x)-(-log(beta)*x))#((beta^x)*(x^(-alpha)))
# print(cumValue)
# }
# return(x)
}
#' @rdname zipfPolylog
#' @export
rzipfpolylog <- function(n, alpha, beta, nSum = 1000){
.prec.zipfpolylog.checkXvalue(n)
.prec.zipfpolylog.checkparams(alpha, beta)
uValues <- stats::runif(n, 0, 1)
# print(uValues)
data <- sapply(uValues, qzipfpolylog, alpha = alpha, beta = beta, nSum = nSum)
# data <- qzipfpolylog(uValues, alpha, beta, nSum = nSum)
return(data)
}
#
# data <- rzipfpolylog(100, -0.05, 0.95)
# data1 <- table(data)
# data1 <- data.frame(data1)
# data1[,1] <- as.numeric(data1[,1])
# data1[,2] <- as.numeric(data1[,2])
# plot(data1[,1], data1[,2], log = 'xy')
# zipfPolylogFit(data1, init_alpha = -0.08, init_beta = -0.02)
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfPolylog.R |
.zpolyloglikelihood <- function(alpha, betaNew, values, freq, nSize){
poly <- copula::polylog(z = exp(betaNew), s = alpha, method = 'sum', n.sum = 1000)
alpha*sum(freq*log(values)) +nSize*log(poly) - betaNew*sum(freq*values)
}
.zPoly <- function(params, values, freq, nSize){
beta <- min(0, params[2])
alpha <- params[1]
# print(c(alpha, beta))
.zpolyloglikelihood(alpha, beta, values, freq, nSize)
}
#' ZipfPolylog parameters estimation.
#'
#' For a given sample of strictly positive integer numbers, usually of the type of ranking data or
#' frequencies of frequencies data, estimates the parameters of the ZipfPolylog distribution by means of
#' the maximum likelihood method. The input data should be provided as a frequency matrix.
#'
#' @param data Matrix of count data in form of a table of frequencies.
#' @param init_alpha Initial value of \eqn{\alpha} parameter (\eqn{\alpha > 1}).
#' @param init_beta Initial value of \eqn{\beta} parameter (\eqn{\beta > 0}).
#' @param level Confidence level used to calculate the confidence intervals (default 0.95).
#' @param object An object from class "zipfPolyR" (output of \emph{zipfPolylogFit} function).
#' @param x An object from class "zipfPolyR" (output of \emph{zipfPolylogFit} function).
#' @param ... Further arguments to the generic functions. The extra arguments are passing to the \emph{\link{optim}} function.
#' @details
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies.
#'
#' The log-likelihood function is equal to:
#'
#' The function \emph{\link{optim}} is used to estimate the parameters.
#' @return Returns a \emph{zipfPolyR} object composed by the maximum likelihood parameter estimations
#' jointly with their standard deviation and confidence intervals. It also contains
#' the value of the log-likelihood at the maximum likelihood estimator.
#'
#' @importFrom stats AIC BIC coef fitted logLik
#' @importFrom copula polylog
#' @export
zipfPolylogFit <- function(data, init_alpha, init_beta, level = 0.95, ...){
Call <- match.call()
if(!is.numeric(init_alpha) || !is.numeric(init_beta)){
stop('Wrong intial values for the parameters.')
}
tryCatch(
{
estResults <- .paramEstimationBase(data, c(init_alpha, init_beta), .zPoly, ...)
estAlpha <- as.numeric(estResults$results$par[1])
estBeta <- exp(as.numeric(estResults$results$par[2]))
paramSD <- sqrt(diag(solve(estResults$results$hessian)))
paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estBeta, level)
structure(class = "zipfPolyR", list(alphaHat = estAlpha,
betaHat = estBeta,
alphaSD = paramSD[1],
betaSD = paramSD[2],
alphaCI = c(paramsCI[1,1],paramsCI[1,2]),
betaCI = c(paramsCI[2,1],paramsCI[2,2]),
logLikelihood = -estResults$results$value,
hessian = estResults$results$hessian,
call = Call))
},
error=function(cond) {
print(cond)
return(NA)
})
}
#' @rdname zipfPolylogFit
#' @export
residuals.zipfPolyR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
residual.values <- dataMatrix[, 2] - fitted(object)
return(residual.values)
}
#' @rdname zipfPolylogFit
#' @export
fitted.zipfPolyR <- function(object, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], dzipfpolylog, alpha = object[['alphaHat']],
beta = object[['betaHat']])
return(fitted.values)
}
#' @rdname zipfPolylogFit
#' @export
coef.zipfPolyR <- function(object, ...){
estimation <- matrix(nrow = 2, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['betaHat']], object[['betaSD']], object[['betaCI']][1], object[['betaCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "beta")
estimation
}
#' @rdname zipfPolylogFit
#' @export
plot.zipfPolyR <- function(x, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting ZipfPolylog Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x), col="blue")
graphics::legend("topright", legend = c('Observations', 'ZipfPolylog Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
#' @rdname zipfPolylogFit
#' @export
print.zipfPolyR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('Beta: %s\n', format(eval(x[['call']]$init_beta), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
#' @rdname zipfPolylogFit
#' @export
summary.zipfPolyR <- function(object, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object))
}
#' @rdname zipfPolylogFit
#' @export
logLik.zipfPolyR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
#' @rdname zipfPolylogFit
#' @export
AIC.zipfPolyR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 2)
return(aic)
}
#' @rdname zipfPolylogFit
#' @export
BIC.zipfPolyR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2]))
return(bic)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfPolylogFit.R |
#' The Zipf-Poisson Extreme Distribution (Zipf-PE).
#'
#' Probability mass function, cumulative distribution function, quantile function and random number
#' generation for the Zipf-PE distribution with parameters \eqn{\alpha} and \eqn{\beta}. The support of the Zipf-PE
#' distribution are the strictly positive integer numbers large or equal than one.
#'
#' @name zipfpe
#' @aliases dzipfpe
#' @aliases pzipfpe
#' @aliases qzipfpe
#' @aliases rzipfpe
#'
#' @param x,q Vector of positive integer values.
#' @param p Vector of probabilities.
#' @param n Number of random values to return.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 1} ).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta\in (-\infty, +\infty)} ).
#' @param log,log.p Logical; if TRUE, probabilities p are given as log(p).
#' @param lower.tail Logical; if TRUE (default), probabilities are \eqn{P[X \leq x]}, otherwise, \eqn{P[X > x]}.
#' @details The \emph{probability mass function} of the Zipf-PE distribution with parameters \eqn{\alpha} and \eqn{\beta}
#' at a positive integer value \eqn{x} is computed as follows:
#'
#' \deqn{p(x | \alpha, \beta) = \frac{e^{\beta (1 - \frac{\zeta(\alpha, x)}{\zeta(\alpha)})} (e^{\beta \frac{x^{-\alpha}}{\zeta(\alpha)}} - 1)}
#' {e^{\beta} - 1},\, x= 1,2,...,\, \alpha > 1,\, -\infty < \beta < +\infty,}
#'
#' where \eqn{\zeta(\alpha)} is the Riemann-zeta function at \eqn{\alpha}, and \eqn{\zeta(\alpha, x)}
#' is the Hurtwitz zeta function with arguments \eqn{\alpha} and x.
#'
#' The \emph{cumulative distribution function} at a given positive
#' integer value \eqn{x}, \eqn{F(x)}, is equal to:
#' \deqn{F(x) = \frac{e^{\beta (1 - \frac{\zeta(\alpha, x + 1)}{\zeta(\alpha)})} - 1}{e^{\beta} -1}}
#'
#' The quantile of the Zipf-PE\eqn{(\alpha, \beta)} distribution of a given probability value p
#' is equal to the quantile of the Zipf\eqn{(\alpha)} distribution at the value:
#'
#' \deqn{p\prime = \frac{log(p\, (e^{\beta} - 1) + 1)}{\beta}}
#' The quantiles of the Zipf\eqn{(\alpha)} distribution are computed by means of the \emph{tolerance}
#' package.
#'
#' To generate random data from a Zipf-PE one applies the \emph{quantile} function over \emph{n} values randomly generated
#' from an Uniform distribution in the interval (0, 1).
#'
#' @return {
#' \code{dzipfpe} gives the probability mass function,
#' \code{pzipfpe} gives the cumulative function,
#' \code{qzipfpe} gives the quantile function, and
#' \code{rzipfpe} generates random values from a Zipf-PE distribution. }
#'
#' @references {
#' Young, D. S. (2010). \emph{Tolerance: an R package for estimating tolerance intervals}. Journal of Statistical Software, 36(5), 1-39.
#' }
#'
#' @examples
#' dzipfpe(1:10, 2.5, -1.5)
#' pzipfpe(1:10, 2.5, -1.5)
#' qzipfpe(0.56, 2.5, 1.3)
#' rzipfpe(10, 2.5, 1.3)
#'
NULL
#> NULL
.prec.zipfpe.checkXvalue <- function(x){
if(!is.numeric(x) || any(x < 1) || any(x%%1 != 0)) {
stop('The x value is not included into the support of the distribution.')
}
}
.prec.zipfpe.checkparams <- function(alpha, beta){
if(!is.numeric(alpha) | alpha <= 1){
stop('Incorrect alpha parameter. This parameter should be greater than one.')
}
if(!is.numeric(beta)){
stop('Incorrect beta parameter. You should provide a numeric value.')
}
}
.dzpe.default <- function(x, alpha, beta, z){
.prec.zipfpe.checkXvalue(x)
if(beta == 0){
return(x^(-alpha)/z)
}
zetaX <-.zeta_x(alpha, x)
return((exp(beta*(1 - (zetaX/z)))*(exp(beta*(x^(-alpha)/z)) - 1))/(exp(beta) -1))
}
#' @rdname zipfpe
#' @export
dzipfpe <- function(x, alpha, beta, log = FALSE){
.prec.zipfpe.checkparams(alpha, beta)
z <- VGAM::zeta(alpha)
probs <- sapply(x, .dzpe.default, alpha = alpha, beta = beta, z = z)
if(log) {
return(log(probs))
}
return(probs)
}
.pzpe.default <- function(v, alpha, beta, z){
.prec.zipfpe.checkXvalue(v)
zetaX <- .zeta_x(alpha, v + 1)
return((exp(beta * (1 - (zetaX/z))) - 1)/(exp(beta) - 1))
}
#' @rdname zipfpe
#' @export
pzipfpe <- function(q, alpha, beta, log.p = FALSE, lower.tail = TRUE){
.prec.zipfpe.checkparams(alpha, beta)
z <- VGAM::zeta(alpha)
probs <- sapply(q, .pzpe.default, alpha = alpha, beta = beta, z = z)
if(!log.p & lower.tail){
return(probs)
} else{
if(!log.p & !lower.tail){
return(1 - probs)
} else{
if(log.p & !lower.tail){
return(log(1 - probs))
}
return(log(probs))
}
}
}
.getUprime <- function(u, beta){
p <- log(u*(exp(beta) - 1) + 1)/beta
return(p)
}
#' @rdname zipfpe
#' @export
qzipfpe <- function(p, alpha, beta, log.p = FALSE, lower.tail = TRUE){
.prec.zipfpe.checkparams(alpha, beta)
if(length(p) < 1){
stop('Wrong value(s) for the p parameter.')
}
if(log.p & lower.tail){
p <- exp(p)
} else{
if(log.p & !lower.tail){
p <- 1-exp(p)
} else{
if(!log.p & !lower.tail){
p <- 1-p
}
}
}
# if(length(which(p > 1 || p < 0 )) > 0){
if(any(p > 1) | any(p < 0 )){
stop('There is a wrong value(s) in the p parameter.')
}
u <- sapply(p, .getUprime, beta = beta)
data <- tolerance::qzipfman(u, s = alpha, b = NULL, N = Inf)
return(data)
}
#' @rdname zipfpe
#' @export
rzipfpe <- function(n, alpha, beta){
.prec.zipfpe.checkXvalue(n)
.prec.zipfpe.checkparams(alpha, beta)
uValues <- stats::runif(n, 0, 1)
data <- qzipfpe(uValues, alpha, beta)
return(data)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpe.R |
.loglikexzp <- function(param, N, values, freq) {
alpha <- param[1]
beta <- param[2]
# print(c(alpha, beta))
zeta_a <- VGAM::zeta(alpha)
val1 <-
sum(sapply(base::seq_along(values), function(i, alpha, values, freq) {
# sum(sapply(1:length(values), function(i, alpha, values, freq) {
freq[i] * .zeta_x(alpha, values[i])
}, alpha = alpha, values = values, freq = freq))
# val2 <- sum(sapply(1:length(values),
val2 <- sum(sapply(base::seq_along(values),
function(i, alpha, beta, values, freq) {
freq[i] * log(exp((beta * values[i] ^ (-alpha)) / (zeta_a)) - 1)
},
alpha = alpha, beta = beta, values = values, freq = freq))
- ((beta * (N - zeta_a ^ (-1) * val1) + val2) - (N * log(exp(beta) - 1)))
}
.loglik3 <- function(param, N, values, freq){
alpha <- param[1]
beta <- param[2]
-sum(sapply(base::seq_along(values),
function(i, alpha, beta, values, freq) {
freq[i] * log(dzipfpe(values[i], alpha, beta))
}, alpha = alpha, beta = beta, values = values, freq = freq))
}
.loglik4 <- function(param, N, values, freq) {
alpha <- param[1]
beta <- param[2]
val <- sum(sapply(base::seq_along(values),
function(i, alpha, beta, values, freq){
freq[i] * log((exp((beta*values[i]^(-alpha))/VGAM::zeta(alpha)) -1)/(exp(beta) - 1))
}, alpha = alpha, beta = beta, values = values, freq = freq))
val1 <- sum(sapply(base::seq_along(values),function(i, alpha, values, freq){
freq[i] * .zeta_x(alpha, values[i])
}, alpha = alpha, values = values, freq = freq))
-(beta*(N - VGAM::zeta(alpha)^(-1)*val1) + val)
}
#' Zipf-PE parameters estimation.
#'
#' For a given sample of strictly positive integer values, usually of the type of ranking data or
#' frequencies of frequencies data, estimates the parameters of the Zipf-PE
#' distribution by means of the maximum likelihood method. The input data should be provided as a frequency matrix.
#'
#' @param data Matrix of count data in form of table of frequencies.
#' @param init_alpha Initial value of \eqn{\alpha} parameter (\eqn{\alpha > 1}).
#' @param init_beta Initial value of \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param level Confidence level used to calculate the confidence intervals (default 0.95).
#' @param object An object from class "zpeR" (output of \emph{zipfpeFit} function).
#' @param x An object from class "zpeR" (output of \emph{zipfpeFit} function).
#' @param ... Further arguments to the generic functions.The extra arguments are passing
#' to the \emph{\link{optim}} function.
#' @details
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies.
#'
#' The log-likelihood function is equal to:
#'
#' \deqn{l(\alpha, \beta; x) = \beta\, (N - \zeta(\alpha)^{-1}\, \sum_{i = 1} ^m f_{a}(x_{i})\, \zeta(\alpha, x_i)) +
#' \sum_{i = 1} ^m f_{a}(x_{i})\, log \left( \frac{e^{\frac{\beta\, x_{i}^{-\alpha}}{\zeta(\alpha)}} - 1}{e^{\beta} - 1} \right), }
#' where \eqn{f_{a}(x_i)} is the absolute frequency of \eqn{x_i}, \eqn{m} is the number of different values in the sample and \eqn{N} is the sample size,
#' i.e. \eqn{N = \sum_{i = 1} ^m x_i f_a(x_i)}.
#'
#' By default the initial values of the parameters are computed using the function \code{getInitialValues}.
#'
#' The function \emph{\link{optim}} is used to estimate the parameters.
#' @return Returns an object composed by the maximum likelihood parameter estimations
#' jointly with their standard deviation and confidence intervals. It also contains
#' the value of the log-likelihood at the maximum likelihood estimator.
#' @examples
#' data <- rzipfpe(100, 2.5, 1.3)
#' data <- as.data.frame(table(data))
#' data[,1] <- as.numeric(as.character(data[,1]))
#' data[,2] <- as.numeric(as.character(data[,2]))
#' initValues <- getInitialValues(data, model='zipfpe')
#' obj <- zipfpeFit(data, init_alpha = initValues$init_alpha, init_beta = initValues$init_beta)
#' @seealso \code{\link{getInitialValues}}.
#' @export
zipfpeFit <- function(data, init_alpha = NULL, init_beta = NULL, level = 0.95, ...){
Call <- match.call()
if(is.null(init_alpha) || is.null(init_beta)){
initValues <- getInitialValues(data, model = 'zipfpe')
init_alpha <- initValues$init_alpha
init_beta <- initValues$init_beta
}
if(!is.numeric(init_alpha) || !is.numeric(init_beta)){
stop('Wrong intial values for the parameters.')
}
tryCatch({
res <- stats::optim(par = c(init_alpha, init_beta), .loglik4, N = sum(as.numeric(data[,2])),
values = as.numeric(as.character(data[, 1])), freq = data[, 2],
hessian = TRUE, ...)
estAlpha <- as.numeric(res$par[1])
estBeta <- as.numeric(res$par[2])
paramSD <- sqrt(diag(solve(res$hessian)))
paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estBeta, level)
structure(class = "zipfpeR", list(alphaHat = estAlpha,
betaHat = estBeta,
alphaSD = paramSD[1],
betaSD = paramSD[2],
alphaCI = c(paramsCI[1,1],paramsCI[1,2]),
betaCI = c(paramsCI[2,1],paramsCI[2,2]),
logLikelihood = -res$value,
hessian=res$hessian,
call = Call))
}, error = function(e) {
print(c("Error", e))
})
}
#' @rdname zipfpeFit
#' @export
residuals.zipfpeR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
residual.values <- dataMatrix[, 2] - fitted(object)
return(residual.values)
}
#' @rdname zipfpeFit
#' @export
fitted.zipfpeR <- function(object, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], dzipfpe, alpha = object[['alphaHat']],
beta = object[['betaHat']])
return(fitted.values)
}
#' @rdname zipfpeFit
#' @export
coef.zipfpeR <- function(object, ...){
estimation <- matrix(nrow = 2, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['betaHat']], object[['betaSD']], object[['betaCI']][1], object[['betaCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "beta")
estimation
}
#' @rdname zipfpeFit
#' @export
plot.zipfpeR <- function(x, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting Zipf-PE Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x), col="blue")
graphics::legend("topright", legend = c('Observations', 'Zipf-PE Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
#' @rdname zipfpeFit
#' @export
print.zipfpeR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('Beta: %s\n', format(eval(x[['call']]$init_beta), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
#' @rdname zipfpeFit
#' @export
summary.zipfpeR <- function(object, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object))
}
#' @rdname zipfpeFit
#' @export
logLik.zipfpeR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
#' @rdname zipfpeFit
#' @export
AIC.zipfpeR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 2)
return(aic)
}
#' @rdname zipfpeFit
#' @export
BIC.zipfpeR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2]))
return(bic)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpeFit.R |
#' Expected value of the Zipf-PE distribution.
#'
#' Computes the expected value of the Zipf-PE distribution for given values of parameters
#' \eqn{\alpha} and \eqn{\beta}.
#'
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 2}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the mean value of the Zipf-PE distribution.
#'
#' @details
#' The mean of the distribution only exists for \eqn{\alpha} strictly greater than 2.
#' It is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' zipfpeMean(2.5, 1.3)
#' zipfpeMean(2.5, 1.3, 10^(-3))
#' @export
zipfpeMean <- function(alpha, beta, tolerance = 10^(-4)){
return(zipfpeMoments(1, alpha, beta, tolerance = tolerance))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpeMean.R |
#' Distribution Moments.
#'
#' General function to compute the k-th moment of the Zipf-PE distribution for any integer value \eqn{k \geq 1},
#' when it exists. The k-th moment exists if and only if \eqn{\alpha > k + 1}.
#' For k = 1, this function returns the same value as the \link{zipfpeMean} function.
#'
#' @param k Order of the moment to compute.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > k + 1}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the k-th moment of the distribution.
#'
#' @details
#' The k-th moment of the Zipf-PE distribution is finite for \eqn{\alpha} values strictly greater than \eqn{k + 1}.
#' It is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' zipfpeMoments(3, 4.5, 1.3)
#' zipfpeMoments(3, 4.5, 1.3, 1*10^(-3))
#' @export
zipfpeMoments <- function(k, alpha, beta, tolerance = 10^(-4)){
if(!is.numeric(k) || !is.numeric(alpha) || !is.numeric(beta) || !is.numeric(tolerance)){
stop("Wrong input parameters!!")
}
if(alpha < k + 1){
stop(sprintf('Alpha value must be greater than %s.', k + 1))
}
if(!k%%1 == 0 || k < 1){
stop('Wrong moment value!!. You have to provide a possitive and integer value.')
}
aux <- 1
x <- 1
result <- 0
while(aux > tolerance) {
pk <- dzipfpe(x, alpha, beta)
aux <- x^k * pk
result <- result + aux
x <- x + 1
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpeMoments.R |
#' Variance of the Zipf-PE distribution.
#'
#' Computes the variance of the Zipf-PE distribution for given values of \eqn{\alpha} and \eqn{\beta}.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 3}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations. (default = \eqn{10^{-4}})
#' @return A positive real value corresponding to the variance of the distribution.
#'
#' @details
#' The variance of the distribution only exists for \eqn{\alpha} strictly greater than 3.
#'
#' @examples
#' zipfpeVariance(3.5, 1.3)
#' @seealso \code{\link{zipfpeMoments}}, \code{\link{zipfpeMean}}.
#' @export
zipfpeVariance <- function(alpha, beta, tolerance = 10^(-4)){
moment1 <- zipfpeMoments(1, alpha, beta, tolerance)
moment2 <- zipfpeMoments(2, alpha, beta, tolerance)
return(moment2 - (moment1^2))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpeVariance.R |
#' Expected value of the ZipfPolylog distribution.
#'
#' Computes the expected value of the ZipfPolylog distribution for given values of parameters
#' \eqn{\alpha} and \eqn{\beta}.
#'
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 2}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the mean value of the ZipfPolylog distribution.
#'
#' @examples
#' zipfpolylogMean(0.5, 0.8)
#' zipfpolylogMean(2.5, 0.8, 10^(-3))
#' @export
zipfpolylogMean <- function(alpha, beta, tolerance = 10^(-4)){
return(zipfpolylogMoments(1, alpha, beta, tolerance = tolerance))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpolylogMean.R |
#' Moments of the Zipf-Polylog Distribution.
#'
#' General function to compute the k-th moment of the ZipfPolylog distribution for any integer value \eqn{k \geq 1},
#' when it exists. #'
#' For k = 1, this function returns the same value as the \link{zipfpolylogMean} function.
#'
#' @param k Order of the moment to compute.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > k + 1}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#' @param nSum The number of terms used for computing the Polylogarithm function (default = 1000).
#'
#' @return A positive real value corresponding to the k-th moment of the distribution.
#'
#' @details
#' The k-th moment of the Zipf-Polylog distribution is always finite, but,
#' for \eqn{\alpha >1} and \eqn{\beta = 0} the k-th moment is only finite for all \eqn{\alpha > k + 1}.
#' It is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' zipfpolylogMoments(1, 0.2, 0.90)
#' zipfpolylogMoments(3, 4.5, 0.90, 1*10^(-3))
#' @export
zipfpolylogMoments <- function(k, alpha, beta, tolerance = 10^(-4), nSum = 1000){
if(!is.numeric(k) || !is.numeric(alpha) || !is.numeric(beta) || !is.numeric(tolerance)){
stop("Wrong input parameters!!")
}
if(alpha > 1 && beta == 0 && alpha < k + 1){
stop(sprintf('Alpha value must be greater than %s.', k + 1))
}
if(!k%%1 == 0 || k < 1){
stop('Wrong moment value!!. You have to provide a positive and integer value.')
}
aux <- 1
x <- 1
result <- 0
while(aux > tolerance) {
pk <- dzipfpolylog(x, alpha, beta, nSum = nSum)
aux <- x^k * pk
#aux <- copula::polylog(z = beta, s = (alpha-k), method = 'sum', n.sum = nSum)/ copula::polylog(z = beta, s = (alpha), method = 'sum', n.sum = nSum)
result <- result + aux
# print(c(x, pk, aux, result))
x <- x + 1
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpolylogMoments.R |
#' Variance of the ZipfPolylog distribution.
#'
#' Computes the variance of the ZipfPolylog distribution for given values of \eqn{\alpha} and \eqn{\beta}.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 3}).
#' @param beta Value of the \eqn{\beta} parameter (\eqn{\beta \in (-\infty, +\infty)}).
#' @param tolerance Tolerance used in the calculations. (default = \eqn{10^{-4}})
#' @return A positive real value corresponding to the variance of the distribution.
#'
#' @details
#' The variance of the distribution only exists for \eqn{\alpha} strictly greater than 3.
#'
#' @examples
#' zipfpoylogVariance(0.5, 0.75)
#' @seealso \code{\link{zipfpolylogMoments}}, \code{\link{zipfpolylogMean}}.
#' @export
zipfpoylogVariance <- function(alpha, beta, tolerance = 10^(-4)){
moment1 <- zipfpolylogMoments(1, alpha, beta, tolerance)
moment2 <- zipfpolylogMoments(2, alpha, beta, tolerance)
return(moment2 - (moment1^2))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpoylogVariance.R |
#' The Zipf-Poisson Stop Sum Distribution (Zipf-PSS).
#'
#' Probability mass function, cumulative distribution function, quantile function and random number
#' generation for the Zipf-PSS distribution with parameters \eqn{\alpha} and \eqn{\lambda}. The support of the Zipf-PSS
#' distribution are the positive integer numbers including the zero value. In order to work with its zero-truncated version
#' the parameter \code{isTruncated} should be equal to True.
#'
#' @name zipfpss
#' @aliases dzipfpss
#' @aliases pzipfpss
#' @aliases rzipfpss
#'
#' @param x,q Vector of positive integer values.
#' @param p Vector of probabilities.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 1} ).
#' @param lambda Value of the \eqn{\lambda} parameter (\eqn{\lambda > 0} ).
#' @param n Number of random values to return.
#' @param log,log.p Logical; if TRUE, probabilities p are given as log(p).
#' @param lower.tail Logical; if TRUE (default), probabilities are \eqn{P[X \leq x]}, otherwise, \eqn{P[X > x]}.
#' @param isTruncated Logical; if TRUE, the zero truncated version of the distribution is returned.
#'
#' @details
#' The support of the \eqn{\lambda} parameter increases when the distribution is truncated at zero being
#' \eqn{\lambda \geq 0}. It has been proved that when \eqn{\lambda = 0} one has the degenerated version of the distribution at one.
#'
#' @references {
#' Panjer, H. H. (1981). Recursive evaluation of a family of compound
#' distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 22-26.
#'
#' Sundt, B., & Jewell, W. S. (1981). Further results on recursive evaluation of
#' compound distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 27-39.
#' }
NULL
#> NULL
.prec.zipfpss.checkXvalue <- function(x){
if(!is.numeric(x) | any(x < 0) | any(x%%1 != 0)) {
stop('The x value is not included into the support of the distribution.')
}
}
.prec.zipfpss.checkparams <- function(alpha, lambda){
if(!is.numeric(alpha) | alpha <= 1){
stop('Incorrect alpha parameter. This parameter should be greater than one.')
}
if(!is.numeric(lambda) | lambda < 0){
stop('Incorrect lambda parameter. You should provide a numeric value.')
}
}
# .panjerRecursion <- function(k, alpha, lambda, previousProb = NULL){
# p0 <- exp(-lambda)
# if(k == 0){
# return(p0)
# }
#
# z_a <- VGAM::zeta(alpha)
# probs <- NULL
#
# if(is.null(previousProb)) {
# probs <- array(0, k + 1)
# probs[1] <- p0
#
# for(i in 1:k){
# probs[i+1] <- (lambda/(i*z_a)) * sum((1:i)^(-alpha + 1) * probs[i:1])
# }
# } else{
# probs <- array(0, k + 1)
# lastProbLength <- length(previousProb)
# probs[1:lastProbLength] <- previousProb[1:lastProbLength]
# for(i in lastProbLength:k){
# probs[i+1] <- (lambda/(i*z_a)) * sum((1:i)^(-alpha + 1) * probs[i:1])
# }
# }
# return(probs)
# }
.getPanjerProbs <- function(startIndex, finalIndex, probs, alpha, lambda){
z_a <- VGAM::zeta(alpha)
for(i in startIndex:finalIndex){
probs[i+1] <- (lambda/(i*z_a)) * sum((1:i)^(-alpha + 1) * probs[i:1])
}
return(probs)
}
.panjerRecursion <- function(k, alpha, lambda, previousProb = NULL){
p0 <- exp(-lambda)
if(k == 0){
return(p0)
}
probs <- NULL
if(is.null(previousProb)) {
probs <- array(0, k + 1)
probs[1] <- p0
probs <- .getPanjerProbs(1, k, probs, alpha, lambda)
} else{
probs <- array(0, k + 1)
lastProbLength <- length(previousProb)
probs[1:lastProbLength] <- previousProb[1:lastProbLength]
probs <- .getPanjerProbs(lastProbLength, k, probs, alpha, lambda)
}
return(probs)
}
.getProbs <- function(x, alpha, lambda, isTruncated = FALSE, previousProb = NULL){
k <- max(x)
.prec.zipfpss.checkXvalue(k)
.prec.zipfpss.checkparams(alpha, lambda)
probs <- .panjerRecursion(k, alpha, lambda, previousProb)
if(isTruncated){
probs <- (probs)/(1 - probs[1])
probs <- probs[-1]
}
return(probs)
}
#' @rdname zipfpss
#' @export
dzipfpss <- function(x, alpha, lambda, log = FALSE, isTruncated = FALSE){
if(lambda == 0){
return(.999999)
} else {
probs <- .getProbs(x, alpha, lambda, isTruncated = isTruncated)
finalProbs <- probs[if(isTruncated) x else (x+1)]#probs[x]#
if(log){
return(log(finalProbs))
}
return(finalProbs)
}
}
#' @rdname zipfpss
#' @export
pzipfpss <- function(q, alpha, lambda, log.p = FALSE, lower.tail = TRUE, isTruncated = FALSE){
probs <- .getProbs(q, alpha, lambda)
finalProbs <- array(0, length(q))
for(i in seq_along(q)){
finalProbs[i] <- sum(probs[1:if(isTruncated) q[i] else (q[i]+1)])
}
if(!log.p & lower.tail){
return(finalProbs)
} else{
if(!log.p & !lower.tail){
return(1 - finalProbs)
} else{
if(log.p & !lower.tail){
return(log(1 - finalProbs))
}
return(log(finalProbs))
}
}
}
#' @rdname zipfpss
#' @export
rzipfpss <- function(n, alpha, lambda, log.p = FALSE, lower.tail = TRUE, isTruncated = FALSE){
.prec.zipfpss.checkparams(alpha, lambda)
# data <- array(0, n)
# for(i in 1:n){
# nPois <- stats::rpois(1, lambda = lambda)
# if(nPois == 0){
# data[i] <- 0
# print(c(i, 0))
# } else{
# xZipfs <- tolerance::rzipfman(nPois, s = alpha, b = NULL, N = Inf)
# data[i] <- sum(xZipfs)
# print(c(i, nPois, sum(xZipfs)))
# }
# }
u <- stats::runif(n)
data <- sapply(u, qzipfpss, alpha, lambda, log.p, lower.tail, isTruncated)
#data <- tolerance::qzipfman(u, s = alpha, b = NULL, N = Inf)
return(data)
}
.invertMethod <- function(p, alpha, lambda, log.p, lower.tail, isTruncated) {
i <- if(isTruncated) 1 else 0
p_i <- pzipfpss(i, alpha = alpha, lambda = lambda, log.p, lower.tail, isTruncated)
repeat{
if(p <= p_i){
return(i)
}
i <- i + 1
p_i <- pzipfpss(i, alpha = alpha, lambda = lambda, log.p, lower.tail, isTruncated)
}
}
#' @rdname zipfpss
#' @export
qzipfpss <- function(p, alpha, lambda, log.p = FALSE, lower.tail = TRUE, isTruncated = FALSE){
.prec.zipfpss.checkparams(alpha, lambda)
if(length(p) < 1){
stop('Wrong value(s) for the p parameter.')
}
if(log.p & lower.tail){
p <- exp(p)
} else{
if(log.p & !lower.tail){
p <- 1-exp(p)
} else{
if(!log.p & !lower.tail){
p <- 1-p
}
}
}
if(any(p > 1) | any(p < 0 )){
stop('There is a wrong value(s) in the p parameter.')
}
data <- sapply(p, .invertMethod, alpha, lambda, log.p, lower.tail, isTruncated)
return(data)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpss.R |
.zpss_mle <- function(par, values, freq, truncated = TRUE) {
alpha <- par[1]
lambda <- par[2]
probs <- .panjerRecursion(max(values), alpha, lambda)
# probs <- getProbsFaster(alpha, lambda, max(values))
if (truncated) {
probs <- (probs) / (1 - probs[1])
probs <- probs[-1]
return(- (sum(freq * log(probs[values]))))
}
return(- (sum(freq * log(probs[values+1]))))
}
#' Zipf-PSS parameters estimation.
#'
#' For a given sample of strictly positive integer numbers, usually of the type of ranking data or
#' frequencies of frequencies data, estimates the parameters of the Zipf-PSS distribution by means of
#' the maximum likelihood method. The input data should be provided as a frequency matrix.
#'
#' @param data Matrix of count data in form of table of frequencies.
#' @param init_alpha Initial value of \eqn{\alpha} parameter (\eqn{\alpha > 1}).
#' @param init_lambda Initial value of \eqn{\lambda} parameter (\eqn{\lambda > 0}).
#' @param level Confidence level used to calculate the confidence intervals (default 0.95).
#' @param isTruncated Logical; if TRUE, the truncated version of the distribution is returned.(default = FALSE)
#' @param object An object from class "zpssR" (output of \emph{zipfpssFit} function).
#' @param x An object from class "zpssR" (output of \emph{zipfpssFit} function).
#' @param ... Further arguments to the generic functions. The extra arguments are passing
#' to the \emph{\link{optim}} function.
#'
#' @details
#' The argument \code{data} is a two column matrix with the first column containing the observations and
#' the second column containing their frequencies.
#'
#' The log-likelihood function is equal to:
#' \deqn{l(\alpha, \lambda, x) = \sum_{i =1} ^{m} f_a(x_i)\, log(P(Y = x_i)),}
#' where \eqn{m} is the number of different values in the sample, being \eqn{f_{a}(x_i)} is the absolute
#' frequency of \eqn{x_i}.The probabilities are calculated applying the Panjer recursion.
#' By default the initial values of the parameters are computed using the function \code{getInitialValues}.
#' The function \emph{\link{optim}} is used to estimate the parameters.
#' @return Returns a \emph{zpssR} object composed by the maximum likelihood parameter estimations jointly
#' with their standard deviation and confidence intervals and the value of the log-likelihood at the
#' maximum likelihood estimator.
#' @references {
#' Panjer, H. H. (1981). Recursive evaluation of a family of compound
#' distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 22-26.
#'
#' Sundt, B., & Jewell, W. S. (1981). Further results on recursive evaluation of
#' compound distributions. ASTIN Bulletin: The Journal of the IAA, 12(1), 27-39.
#' }
#'
#' @examples
#' data <- rzipfpss(100, 2.5, 1.3)
#' data <- as.data.frame(table(data))
#' data[,1] <- as.numeric(as.character(data[,1]))
#' data[,2] <- as.numeric(as.character(data[,2]))
#' initValues <- getInitialValues(data, model='zipfpss')
#' obj <- zipfpssFit(data, init_alpha = initValues$init_alpha, init_lambda = initValues$init_lambda)
#' @seealso \code{\link{getInitialValues}}.
#' @export
zipfpssFit <- function(data, init_alpha = NULL, init_lambda = NULL, level=0.95, isTruncated = FALSE, ...){
Call <- match.call()
if(is.null(init_alpha) || is.null(init_lambda)){
if(isTruncated){
model <- 'zt_zipfpss'
} else {
model <- 'zipfpss'
}
initValues <- getInitialValues(data, model = model)
init_alpha <- initValues$init_alpha
init_lambda <- initValues$init_lambda
}
if(!is.numeric(init_alpha) || !is.numeric(init_lambda)){
stop('Wrong intial values for the parameters.')
}
tryCatch({
res <- stats::optim(par = c(init_alpha, init_lambda), .zpss_mle,
values = as.numeric(as.character(data[, 1])),
freq = as.numeric(data[, 2]),
truncated = isTruncated, hessian = TRUE, ...)
estAlpha <- as.numeric(res$par[1])
estLambda <- as.numeric(res$par[2])
paramSD <- sqrt(diag(solve(res$hessian)))
paramsCI <- .getConfidenceIntervals(paramSD, estAlpha, estLambda, level)
structure(class = "zipfpssR", list(alphaHat = estAlpha,
lambdaHat = estLambda,
alphaSD = paramSD[1],
lambdaSD = paramSD[2],
alphaCI = c(paramsCI[1,1],paramsCI[1,2]),
lambdaCI = c(paramsCI[2,1],paramsCI[2,2]),
logLikelihood = -res$value,
hessian = res$hessian,
call = Call))
}, error = function(e){
print(c('Error', e))
})
}
#' @rdname zipfpssFit
#' @export
residuals.zipfpssR <- function(object, isTruncated = FALSE, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
fitted.values <- fitted(object, isTruncated)
residual.values <- dataMatrix[, 2] - fitted.values
return(residual.values)
}
#' @rdname zipfpssFit
#' @export
fitted.zipfpssR <- function(object, isTruncated = FALSE, ...) {
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
N <- sum(dataMatrix[, 2])
fitted.values <- N*sapply(dataMatrix[,1], dzipfpss,
alpha = object[['alphaHat']], lambda = object[['lambdaHat']],
isTruncated = isTruncated)
return(fitted.values)
}
#' @rdname zipfpssFit
#' @export
coef.zipfpssR <- function(object, ...){
estimation <- matrix(nrow = 2, ncol = 4)
estimation[1, ] <- c(object[['alphaHat']], object[['alphaSD']], object[['alphaCI']][1], object[['alphaCI']][2])
estimation[2, ] <- c(object[['lambdaHat']], object[['lambdaSD']], object[['lambdaCI']][1], object[['lambdaCI']][2])
colnames(estimation) <- c("MLE", "Std. Dev.", paste0("Inf. ", "95% CI"),
paste0("Sup. ", "95% CI"))
rownames(estimation) <- c("alpha", "lambda")
estimation
}
#' @rdname zipfpssFit
#' @export
plot.zipfpssR <- function(x, isTruncated = FALSE, ...){
dataMatrix <- get(as.character(x[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
graphics::plot(dataMatrix[,1], dataMatrix[,2], log="xy",
xlab="Observation", ylab="Frequency",
main="Fitting Zipf-PSS Distribution", ...)
graphics::lines(dataMatrix[,1], fitted(x, isTruncated), col="blue")
graphics::legend("topright", legend = c('Observations', 'Zipf-PSS Distribution'),
col=c('black', 'blue'), pch=c(21,NA),
lty=c(NA, 1), lwd=c(NA, 2))
}
#' @rdname zipfpssFit
#' @export
print.zipfpssR <- function(x, ...){
cat('Call:\n')
print(x[['call']])
cat('\n')
cat('Initial Values:\n')
cat(sprintf('Alpha: %s\n', format(eval(x[['call']]$init_alpha), digits = 3)))
cat(sprintf('Lambda: %s\n', format(eval(x[['call']]$init_lambda), digits = 3)))
cat('\n')
cat('Coefficients:\n')
print(coef(x))
cat('\n')
cat('Metrics:\n')
cat(sprintf('Log-likelihood: %s\n', logLik(x)))
cat(sprintf('AIC: %s\n', AIC(x)))
cat(sprintf('BIC: %s\n', BIC(x)))
}
#' @rdname zipfpssFit
#' @export
summary.zipfpssR <- function(object, isTruncated = FALSE, ...){
print(object)
cat('\n')
cat('Fitted values:\n')
print(fitted(object, isTruncated))
}
#' @rdname zipfpssFit
#' @export
logLik.zipfpssR <- function(object, ...){
if(!is.na(object[['logLikelihood']]) || !is.null(object[['logLikelihood']])){
return(object[['logLikelihood']])
}
return(NA)
}
#' @rdname zipfpssFit
#' @export
AIC.zipfpssR <- function(object, ...){
aic <- .get_AIC(object[['logLikelihood']], 2)
return(aic)
}
#' @rdname zipfpssFit
#' @export
BIC.zipfpssR <- function(object, ...){
dataMatrix <- get(as.character(object[['call']]$data))
dataMatrix[,1] <- as.numeric(as.character(dataMatrix[,1]))
dataMatrix[,2] <-as.numeric(as.character(dataMatrix[,2]))
bic <- .get_BIC(object[['logLikelihood']], 2, sum(dataMatrix[, 2]))
return(bic)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpssFit.R |
#' Expected value of the Zipf-PSS distribution.
#'
#' Computes the expected value of the Zipf-PSS distribution for given values of parameters
#' \eqn{\alpha} and \eqn{\lambda}.
#'
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 2}).
#' @param lambda Value of the \eqn{\lambda} parameter (\eqn{\lambda > 0}).
#' @param isTruncated Logical; if TRUE Use the zero-truncated version of the distribution to calculate the expected value (default = FALSE).
#'
#' @return A positive real value corresponding to the mean value of the distribution.
#'
#' @details
#' The expected value of the Zipf-PSS distribution only exists for \eqn{\alpha} values strictly
#' greater than 2. The value is obtained from the \emph{law of total expectation} that says that: \deqn{E[Y] = E[N]\, E[X],}
#' where E[X] is the mean value of the Zipf distribution and E[N] is the expected value of a Poisson one.
#' From where one has that:
#' \deqn{E[Y] = \lambda\, \frac{\zeta(\alpha - 1)}{\zeta(\alpha)}}
#'
#' Particularlly, if one is working with the zero-truncated version of the Zipf-PSS distribution.
#' This values is computed as:
#' \deqn{E[Y^{ZT}] = \frac{\lambda\, \zeta(\alpha - 1)}{\zeta(\alpha)\, (1 - e^{-\lambda})}}
#'
#' @references {
#' Sarabia Alegría, J. M., Gómez Déniz, E. M. I. L. I. O., & Vázquez Polo, F. (2007).
#' Estadística actuarial: teoría y aplicaciones. Pearson Prentice Hall.
#' }
#' @examples
#' zipfpssMean(2.5, 1.3)
#' zipfpssMean(2.5, 1.3, TRUE)
#' @export
zipfpssMean <- function(alpha, lambda, isTruncated = FALSE){
if(!is.numeric(alpha) || !is.numeric(lambda)){
stop("Wrong input parameters!!")
}
if(alpha < 2){
stop('The alpha parameter must be greater than 2.')
}
meanVal <-lambda * VGAM::zeta(alpha - 1)/VGAM::zeta(alpha)
if(!isTruncated){
return(meanVal)
}
return(meanVal/(1 - exp(-lambda)))
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpssMean.R |
#' Distribution Moments.
#'
#' General function to compute the k-th moment of the Zipf-PSS distribution for any integer value \eqn{k \geq 1},
#' when it exists. The k-th moment exists if and only if \eqn{\alpha > k + 1}.
#'
#' @param k Order of the moment to compute.
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > k + 1}).
#' @param lambda Value of the \eqn{\lambda} parameter (\eqn{\lambda > 0}).
#' @param isTruncated Logical; if TRUE, the truncated version of the distribution is returned.
#' @param tolerance Tolerance used in the calculations (default = \eqn{10^{-4}}).
#'
#' @return A positive real value corresponding to the k-th moment of the distribution.
#'
#' @details
#' The k-th moment of the Zipf-PSS distribution is finite for \eqn{\alpha} values
#' strictly greater than \eqn{k + 1}.
#' It is computed by calculating the partial sums of the serie, and stopping when two
#' consecutive partial sums differ less than the \code{tolerance} value.
#' The value of the last partial sum is returned.
#'
#' @examples
#' zipfpssMoments(1, 2.5, 2.3)
#' zipfpssMoments(1, 2.5, 2.3, TRUE)
#' @export
zipfpssMoments <- function(k, alpha, lambda, isTruncated = FALSE, tolerance = 10^(-4)){
if(!is.numeric(k) || !is.numeric(alpha) || !is.numeric(lambda) || !is.numeric(tolerance) || !is.logical(isTruncated)){
stop("Wrong input parameters!!")
}
if(alpha < k + 1){
stop(sprintf('Alpha value must be greater than %s.', k + 1))
}
if(!k%%1 == 0 || k < 1){
stop('Wrong moment value!!. You have to provide a possitive and integer value.')
}
probs <- dzipfpss(1:1000, alpha, lambda, isTruncated = isTruncated)
result <- sum(((1:1000)^k)*probs)
aux <- 1000*probs[length(probs)]
x <- 1001
while(aux > tolerance) {
probs <- .getProbs(x, alpha, lambda, isTruncated=isTruncated, probs)
aux <- x^k * probs[if(isTruncated) x else (x+1)]
result <- result + aux
x <- x + 1
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpssMoments.R |
#' Variance of the Zipf-PSS distribution.
#'
#' Computes the variance of the Zipf-PSS distribution for given values of parameters
#' \eqn{\alpha} and \eqn{\lambda}.
#'
#' @param alpha Value of the \eqn{\alpha} parameter (\eqn{\alpha > 3}).
#' @param lambda Value of the \eqn{\lambda} parameter (\eqn{\lambda > 0}).
#' @param isTruncated Logical; if TRUE Use the zero-truncated version of the distribution to calculate the expected value (default = FALSE).
#'
#' @return A positive real value corresponding to the variance of the distribution.
#'
#' @details
#' The variance of the Zipf-PSS distribution only exists for \eqn{\alpha} values strictly greater than 3.
#' The value is obtained from the \emph{law of total variance} that says that: \deqn{Var[Y] = E[N]\, Var[X] + E[X]^2 \, Var[N],}
#' where X follows a Zipf distribution with parameter \eqn{\alpha}, and N follows a Poisson distribution with
#' parameter \eqn{\lambda}. From where one has that:
#'
#' \deqn{Var[Y] = \lambda\, \frac{\zeta(\alpha - 2)}{\zeta(\alpha)}}
#' Particularlly, if one is working with the zero-truncated version of the Zipf-PSS distribution.
#' This values is computed as:
#' \deqn{Var[Y^{ZT}] = \frac{\lambda\, \zeta(\alpha)\, \zeta(\alpha - 2)\, (1 - e^{-\lambda}) - \lambda^2 \, \zeta(\alpha - 1)^2 \, e^{-\lambda}}{\zeta(\alpha)^2 \, (1 - e^{-\lambda})^2}}
#'
#' @references {
#' Sarabia Alegría, JM. and Gómez Déniz, E. and Vázquez Polo, F. Estadística actuarial: teoría y aplicaciones. Pearson Prentice Hall.
#' }
#' @examples
#' zipfpssVariance(4.5, 2.3)
#' zipfpssVariance(4.5, 2.3, TRUE)
#' @export
zipfpssVariance <- function(alpha, lambda, isTruncated = FALSE){
if(!is.numeric(alpha) || !is.numeric(lambda)){
stop("Wrong input parameters!!")
}
if(alpha < 3){
stop('The alpha parameter must be greater than 2.')
}
zeta_a <- VGAM::zeta(alpha)
if(!isTruncated){
return(lambda*VGAM::zeta(alpha - 2)/zeta_a)
}
fc <- lambda/(zeta_a*(1 - exp(-lambda)))
term1 <- (lambda * (VGAM::zeta(alpha - 1)^2) * exp(-lambda))/(zeta_a * (1 - exp(-lambda)))
(fc * (VGAM::zeta(alpha - 2) - term1))
# (lambda*zeta_a*VGAM::zeta(alpha - 2)*(1-exp(-lambda)) - lambda^2 * VGAM::zeta(alpha - 1)^2 * exp(-lambda))/(zeta_a^2 * (1 - exp(-lambda))^2)
}
| /scratch/gouwar.j/cran-all/cranData/zipfextR/R/zipfpssVariance.R |
#' @title Sample Data for Small Area Estimation with Zero-Inflated Poisson model
#'
#' @description A Dataset which is generate with Zero-Inflated Poisson method for Small Area Estimation purpose
#'
#' This data is generated based on Zero-Inflated Poisson with EBLUP based model
#'
#' @format A data frame with 300 rows and 3 variables:
#' \describe{
#' \item{y}{Direct Estimation of y}
#' \item{x1}{Auxiliary variable of x1}
#' \item{vardir}{Sampling Variance of y}
#' }
#'
"dataSAEZIP"
| /scratch/gouwar.j/cran-all/cranData/zipsae/R/dataSAEZIP.R |
#' @title EBLUPs under Zero-Inflated Poisson Model
#' @description This function produces empirical best linier unbiased predictions (EBLUPs) for Zero-Inflated data and its Relative Standard Error. Small Area Estimation with Zero-Inflated Model (SAE-ZIP) is a model developed for Zero-Inflated data that can lead us to overdispersion situation. To handle this kind of situation, this model is created. The model in this package is based on Small Area Estimation with Zero-Inflated Poisson model proposed by Dian Christien Arisona (2018)<https://repository.ipb.ac.id/handle/123456789/92308>. For the data sample itself, we use combination method between Roberto Benavent and Domingo Morales (2015)<doi:10.1016/j.csda.2015.07.013> and Sabine Krieg, Harm Jan Boonstra and Marc Smeets (2016)<doi:10.1515/jos-2016-0051>.
#' @param data The data frame with vardir, response, and explanatory variables included with Zero-Inflated situation also.
#' @param vardir Sampling variances of direct estimations, if it is included in data frame so it is the vector with the name of sampling variances.if it is not, it is a data frame of sampling variance in order : \code{var1, cov12,.,cov1r,var2,cov23,.,cov2r,.,cov(r-1)(r),var(r)}
#' @param formula List of formula that describe the fitted model
#' @param PRECISION Limit of Fisher-scoring convergence tolerance. We set the default in \code{1e-4}
#' @param MAXITER Maximum number of iterations in Fisher-scoring algorithm. We set the default in \code{100}
#' @return This function returns a list of the following objects:
#' \item{estimate}{A Vector with a list of EBLUP with Zero-Inflated Poisson model}
#' \item{dispersion}{A list containing the following objects:}
#' \itemize{
#' \item rse : A dataframe with the values of relative square errors of estimation
#' }
#' \item{coefficient}{A list containing the following objects:}
#' \itemize{
#' \item lambda : The estimator of model based on Non-Zero data
#' \item omega : The estimator of model based Complete Data
#' }
#' @examples
#' ##load the dataset in package
#' data(dataSAEZIP)
#'
#' ##Extract the vardir (sampling error)
#' dataSAEZIP$vardir -> sError
#'
#' ##Compute the data with SAE ZIP model
#' formula = (y~x1)
#' zipsae(data = dataSAEZIP, vardir = sError, formula) -> saezip
#'
#' saezip$estimate #to see the result of Small Area Estimation with Zero-Inflated Model
#' saezip$dispersion$rse #to see the relative standard error from the estimation
#' saezip$coefficient$lambda #to see the estimator which is gained from the non-zero compilation data
#' saezip$coefficient$omega #to see the estimator which is gained from the complete compilation data.
#'
#' head(saezip)
#'
#' @export zipsae
#' @import stats
zipsae <- function(data, vardir, formula, PRECISION = 1e-04, MAXITER = 100 ){
if(missing(data)){
stop("Data argument is missing")
}
if (length(formula)==0){
stop("Please insert your formula for fitted model")
}
if (missing(vardir)){
stop("vardir argument is missing")
}
hasil <- list(estimate = NA,
dispersion = list(rse = NA),
coefficient = list(lambda = NA,
omega = NA
)
)
reml <- function(X, Y, vardir, MAXITER){
PRECISION = 1e-04
REML_tmp <- 0
REML_tmp[1] <- mean(vardir)
k <- 0
acc <- PRECISION + 1
while ((acc > PRECISION) & (k < MAXITER)) {
k <- k + 1
Psi <- 1/(REML_tmp[k] + vardir)
PsiXt <- t(Psi * X)
Q <- solve(PsiXt %*% X)
P <- diag(Psi) - t(PsiXt) %*% Q %*% PsiXt
Py <- P %*% Y
s <- (-0.5) * sum(diag(P)) + 0.5 * (t(Py) %*% Py)
Fis <- 0.5 * sum(diag(P %*% P))
REML_tmp[k + 1] <- REML_tmp[k] + s/Fis
acc <- abs((REML_tmp[k + 1] - REML_tmp[k])/REML_tmp[k])
}
REML <- max(REML_tmp[k + 1], 0)
return(REML)
}
m_data = model.frame(formula, na.action = na.omit ,data)
Xz <- model.matrix(formula, m_data)
Xz <- as.numeric(Xz[,-1])
Xnz <- Xz
Y <- m_data[, 1]
ToOmit <- c()
dataLength <- nrow(data)
for (i in 1:dataLength) {
if (Y[i] == 0) {
ToOmit <- c(ToOmit, i)
}
}
if (length(ToOmit) != 0) {
Xnz <- Xz[-ToOmit]
Ynz <- Y[-ToOmit]
vardirNz <- vardir[-ToOmit]
}else{
Xnz <- Xz
Ynz <- Y
vardirNz <- vardir
}
b.REMLz <- reml(Xz, Y, vardir, MAXITER)
a.REMLnz <- reml(Xnz, Ynz, vardirNz, MAXITER)
Vnz <- 1/(a.REMLnz + vardirNz)
Vz <- 1/(b.REMLz + vardir)
Xnz_tmp <- t(Vnz*Xnz)
Xz_tmp <- t(Vz*Xz)
Qnz <- solve(Xnz_tmp%*%Xnz)
Qz <- solve(Xz_tmp%*%Xz)
beta.nz <- Qnz%*%Xnz_tmp%*%Ynz
beta.z <- Qz%*%Xz_tmp%*%Y
X_beta.nz <- Xnz%*%beta.nz
X_beta.z <- Xz%*%beta.z
residNz <- Ynz - X_beta.nz
residZ <- Y - X_beta.z
lamda = exp((Xz%*%beta.nz) + as.vector(a.REMLnz*(Vnz%*%residNz)))
logit = exp(X_beta.z + as.vector(b.REMLz*(Vz%*%residZ)))
omega = (logit/(1 + logit))
delta = 1-omega
est <- lamda*delta
est - mean(est) -> diff_tmp
(diff_tmp)^2 -> diff_tmp_squared
sqrt(diff_tmp_squared)/est -> rse_tmp
hasil$estimate <- est
hasil$dispersion$rse <- rse_tmp
hasil$coefficient$lambda <- lamda
hasil$coefficient$omega <- omega
return(hasil)
}
| /scratch/gouwar.j/cran-all/cranData/zipsae/R/zipsae.R |
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#' Create a new compressor object
#'
#' Initialize a new compressor object for zlib-based compression with specified settings.
#' @param level Compression level, integer between 0 and 9, or -1 for default.
#' @param method Compression method.
#' @param wbits Window size bits.
#' @param memLevel Memory level for internal compression state.
#' @param strategy Compression strategy.
#' @param zdict Optional predefined compression dictionary as a raw vector.
#' @return A SEXP pointer to the new compressor object.
#' @examples
#' compressor <- create_compressor(level = 6, memLevel = 8)
#' @export
create_compressor <- function(level = -1L, method = 8L, wbits = 15L, memLevel = 8L, strategy = 0L, zdict = NULL) {
.Call(`_zlib_create_compressor`, level, method, wbits, memLevel, strategy, zdict)
}
#' @title Compress a Chunk of Data
#'
#' @description Compresses a given chunk of raw binary data using a pre-existing compressor object.
#'
#' @param compressorPtr An external pointer to an existing compressor object.
#' This object is usually initialized by calling a different function like `create_compressor()`.
#'
#' @param input_chunk A raw vector containing the uncompressed data that needs to be compressed.
#'
#' @return A raw vector containing the compressed data.
#'
#' @details
#' This function is primarily designed for use with a compressor object created by `create_compressor()`.
#' It takes a chunk of raw data and compresses it, returning a raw vector of the compressed data.
#'
#' @examples
#' # Create a new compressor object for zlib -> wbts = 15
#' zlib_compressor <- create_compressor(wbits=31)
#' compressed_data <- compress_chunk(zlib_compressor, charToRaw("Hello, World"))
#' compressed_data <- c(compressed_data, flush_compressor_buffer(zlib_compressor))
#' decompressed_data <- memDecompress(compressed_data, type = "gzip")
#' cat(rawToChar(decompressed_data))
#' @export
compress_chunk <- function(compressorPtr, input_chunk) {
.Call(`_zlib_compress_chunk`, compressorPtr, input_chunk)
}
#' Flush the internal buffer of the compressor object.
#'
#' This function flushes the internal buffer according to the specified mode.
#' @param compressorPtr A SEXP pointer to an existing compressor object.
#' @param mode A compression flush mode. Default is Z_FINISH.
#' Available modes are Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_BLOCK, and Z_FINISH.
#' @return A raw vector containing the flushed output.
#' @examples
#' compressor <- create_compressor()
#' # ... (some compression actions)
#' flushed_data <- flush_compressor_buffer(compressor)
#' @export
flush_compressor_buffer <- function(compressorPtr, mode = 4L) {
.Call(`_zlib_flush_compressor_buffer`, compressorPtr, mode)
}
#' Retrieve zlib Constants
#'
#' This function returns a list of constants from the zlib C library.
#'
#' The constants are defined as follows:
#' \itemize{
#' \item \code{DEFLATED}: The compression method, set to 8.
#' \item \code{DEF_BUF_SIZE}: The default buffer size, set to 16384.
#' \item \code{DEF_MEM_LEVEL}: Default memory level, set to 8.
#' \item \code{MAX_WBITS}: Maximum size of the history buffer, set to 15.
#' \item \code{Z_BEST_COMPRESSION}: Best compression level, set to 9.
#' \item \code{Z_BEST_SPEED}: Best speed for compression, set to 1.
#' \item \code{Z_BLOCK}: Block compression mode, set to 5.
#' \item \code{Z_DEFAULT_COMPRESSION}: Default compression level, set to -1.
#' \item \code{Z_DEFAULT_STRATEGY}: Default compression strategy, set to 0.
#' \item \code{Z_FILTERED}: Filtered compression mode, set to 1.
#' \item \code{Z_FINISH}: Finish compression mode, set to 4.
#' \item \code{Z_FULL_FLUSH}: Full flush mode, set to 3.
#' \item \code{Z_HUFFMAN_ONLY}: Huffman-only compression mode, set to 2.
#' \item \code{Z_NO_COMPRESSION}: No compression, set to 0.
#' \item \code{Z_NO_FLUSH}: No flush mode, set to 0.
#' \item \code{Z_PARTIAL_FLUSH}: Partial flush mode, set to 1.
#' \item \code{Z_RLE}: Run-length encoding compression mode, set to 3.
#' \item \code{Z_SYNC_FLUSH}: Synchronized flush mode, set to 2.
#' \item \code{Z_TREES}: Tree block compression mode, set to 6.
#' }
#'
#' @return A named list of zlib constants.
#' @examples
#' constants <- zlib_constants()
#' @keywords internal
zlib_constants <- function() {
.Call(`_zlib_zlib_constants`)
}
#' Create a new decompressor object
#'
#' Initialize a new decompressor object for zlib-based decompression.
#' @param wbits The window size bits parameter. Default is 0.
#' @return A SEXP pointer to the new decompressor object.
#' @examples
#' decompressor <- create_decompressor()
#' @export
create_decompressor <- function(wbits = 0L) {
.Call(`_zlib_create_decompressor`, wbits)
}
#' Decompress a chunk of data
#'
#' Perform chunk-wise decompression on a given raw vector using a decompressor object.
#' @param decompressorPtr An external pointer to an initialized decompressor object.
#' @param input_chunk A raw vector containing the compressed data chunk.
#' @return A raw vector containing the decompressed data.
#' @examples
#' rawToChar(decompress_chunk(create_decompressor(), memCompress(charToRaw("Hello, World"))))
#' @export
decompress_chunk <- function(decompressorPtr, input_chunk) {
.Call(`_zlib_decompress_chunk`, decompressorPtr, input_chunk)
}
#' Flush the internal buffer of the decompressor object.
#'
#' This function processes all pending input and returns the remaining uncompressed output.
#' The function uses the provided initial buffer size and dynamically expands it as necessary
#' to ensure all remaining data is decompressed. After calling this function, the
#' decompress_chunk() method cannot be called again on the same object.
#' @param decompressorPtr A SEXP pointer to an existing decompressor object.
#' @param length An optional parameter that sets the initial size of the output buffer. Default is 256.
#' @return A raw vector containing the remaining uncompressed output.
#' @examples
#' decompressor <- create_decompressor()
#' # ... (some decompression actions)
#' flushed_data <- flush_decompressor_buffer(decompressor)
#' @export
flush_decompressor_buffer <- function(decompressorPtr, length = 256L) {
.Call(`_zlib_flush_decompressor_buffer`, decompressorPtr, length)
}
#' Validate if a File is a Valid Gzip File
#'
#' This function takes a file path as input and checks if it's a valid gzip-compressed file.
#' It reads the file in chunks and tries to decompress it using the zlib library.
#' If any step fails, the function returns \code{FALSE}. Otherwise, it returns \code{TRUE}.
#'
#' @param file_path A string representing the path of the file to validate.
#' @return A boolean value indicating whether the file is a valid gzip file.
#' \code{TRUE} if the file is valid, \code{FALSE} otherwise.
#' @examples
#' validate_gzip_file("path/to/your/file.gz")
#' @export
validate_gzip_file <- function(file_path) {
.Call(`_zlib_validate_gzip_file`, file_path)
}
| /scratch/gouwar.j/cran-all/cranData/zlib/R/RcppExports.R |
# Placeholder for the zlib enrionment
zlib <- NULL
#' The following 'zlib' enrivonment is generated by the .onLoad Behavior for R packages.
#'
#' The .onLoad function is automatically called when the package is loaded using
#' `library()` or `require()`. It initializes the an environment,
#' which can be reached from anywhere and is unique (i.e. cannot be ovwerwritten),
#' including defining a variety of constants / methods related to the zlib compression
#' library.
#'
#' Specifically, the function assigns a new environment named "zlib" containing
#' constants such as `DEFLATED`, `DEF_BUF_SIZE`, `MAX_WBITS`,
#' and various flush and compression strategies like `Z_FINISH`,
#' `Z_BEST_COMPRESSION`, etc.
#'
#' @seealso [publicEval()] for the method used to set up the public environment.
#' @seealso [zlib_constants()] for the method used to set up the constants in the environment. https://www.zlib.net/manual.html#Constants
#' @name zlib
#' @title zlib
#' @return No return value, called for side effect. An environment containing the zlib constants created onLoad.
#' @examples
#' # Load the package
#' library(zlib)
#' # Create a temporary file
#' temp_file <- tempfile(fileext = ".txt")
#'
#' # Generate example data and write to the temp file
#' example_data <- "This is an example string. It contains more than just 'hello, world!'"
#' writeBin(charToRaw(example_data), temp_file)
#'
#' # Read data from the temp file into a raw vector
#' file_con <- file(temp_file, "rb")
#' raw_data <- readBin(file_con, "raw", file.info(temp_file)$size)
#' close(file_con)
#' # Create a Compressor object gzip
#' compressor <- zlib$compressobj(zlib$Z_DEFAULT_COMPRESSION, zlib$DEFLATED, zlib$MAX_WBITS + 16)
#'
#' # Initialize variables for chunked compression
#' chunk_size <- 1024
#' compressed_data <- raw(0)
#'
#' # Compress the data in chunks
#' for (i in seq(1, length(raw_data), by = chunk_size)) {
#' chunk <- raw_data[i:min(i + chunk_size - 1, length(raw_data))]
#' compressed_chunk <- compressor$compress(chunk)
#' compressed_data <- c(compressed_data, compressed_chunk)
#' }
#'
#' # Flush the compressor buffer
#' compressed_data <- c(compressed_data, compressor$flush())
#'
#'
#' # Create a Decompressor object for gzip
#' decompressor <- zlib$decompressobj(zlib$MAX_WBITS + 16)
#'
#' # Initialize variable for decompressed data
#' decompressed_data <- raw(0)
#'
#' # Decompress the data in chunks
#' for (i in seq(1, length(compressed_data), by = chunk_size)) {
#' chunk <- compressed_data[i:min(i + chunk_size - 1, length(compressed_data))]
#' decompressed_chunk <- decompressor$decompress(chunk)
#' decompressed_data <- c(decompressed_data, decompressed_chunk)
#' }
#'
#' # Flush the decompressor buffer
#' decompressed_data <- c(decompressed_data, decompressor$flush())
#'
#' # Comporess / Decompress data in a single step
#'
#' original_data <- charToRaw("some data")
#' compressed_data <- zlib$compress(original_data,
#' zlib$Z_DEFAULT_COMPRESSION,
#' zlib$DEFLATED,
#' zlib$MAX_WBITS + 16)
#' decompressed_data <- zlib$decompress(compressed_data, zlib$MAX_WBITS + 16)
#'
#' @details
#' @title What My Package Offers
#'
#' @section Methods:
#' * `compressobj(...)`: Create a compression object.
#' * `decompressobj(...)`: Create a decompression object.
#' * `compress(data, ...)`: Compress data in a single step.
#' * `decompress(data, ...)`: Decompress data in a single step.
#'
#' @section Constants:
#' * `DEFLATED`: The compression method, set to 8.
#' * `DEF_BUF_SIZE`: The default buffer size, set to 16384.
#' * `DEF_MEM_LEVEL`: Default memory level, set to 8.
#' * `MAX_WBITS`: Maximum size of the history buffer, set to 15.
#' * `Z_BEST_COMPRESSION`: Best compression level, set to 9.
#' * `Z_BEST_SPEED`: Best speed for compression, set to 1.
#' * `Z_BLOCK`: Block compression mode, set to 5.
#' * `Z_DEFAULT_COMPRESSION`: Default compression level, set to -1.
#' * `Z_DEFAULT_STRATEGY`: Default compression strategy, set to 0.
#' * `Z_FILTERED`: Filtered compression mode, set to 1.
#' * `Z_FINISH`: Finish compression mode, set to 4.
#' * `Z_FULL_FLUSH`: Full flush mode, set to 3.
#' * `Z_HUFFMAN_ONLY`: Huffman-only compression mode, set to 2.
#' * `Z_NO_COMPRESSION`: No compression, set to 0.
#' * `Z_NO_FLUSH`: No flush mode, set to 0.
#' * `Z_PARTIAL_FLUSH`: Partial flush mode, set to 1.
#' * `Z_RLE`: Run-length encoding compression mode, set to 3.
#' * `Z_SYNC_FLUSH`: Synchronized flush mode, set to 2.
#' * `Z_TREES`: Tree block compression mode, set to 6.
#'
#' @description
#' What My Package Offers
#'
#' This package provides several key features:
#'
#' \describe{
#' \item{\strong{Robustness:}}{Built to handle even corrupted or incomplete gzip data efficiently without causing system failures.}
#' \item{Demonstration:}{
#' \preformatted{
#' compressed_data <- memCompress(charToRaw(paste0(rep("This is an example string. It contains more than just 'hello, world!'", 1000), collapse = ", ")))
#' decompressor <- zlib$decompressobj(zlib$MAX_WBITS)
#' rawToChar(c(decompressor$decompress(compressed_data[1:300]), decompressor$flush())) # Still working
#' }}
#' \item{\strong{Compliance:}}{Strict adherence to the GZIP File Format Specification, ensuring compatibility across systems.}
#' \item{Demonstration:}{
#' \preformatted{
#' compressor <- zlib$compressobj(zlib$Z_DEFAULT_COMPRESSION, zlib$DEFLATED, zlib$MAX_WBITS + 16)
#' c(compressor$compress(charToRaw("Hello World")), compressor$flush()) # Correct 31 wbits (or custom wbits you provide)
#' # [1] 1f 8b 08 00 00 00 00 00 00 03 f3 48 cd c9 c9 57 08 cf 2f ca 49 01 00 56 b1 17 4a 0b 00 00 00
#' }}
#' \item{\strong{Flexibility:}}{Ability to manage Gzip streams from REST APIs without the need for temporary files or other workarounds.}
#' \item{Demonstration:}{
#' \preformatted{
#' # Byte-Range Request and decompression in chunks
#'
#' # Initialize the decompressor
#' decompressor <- zlib$decompressobj(zlib$MAX_WBITS + 16)
#'
#' # Define the URL and initial byte ranges
#' url <- "https://example.com/api/data.gz"
#' range_start <- 0
#' range_increment <- 5000 # Adjust based on desired chunk size
#'
#' # Placeholder for the decompressed content
#' decompressed_content <- character(0)
#'
#' # Loop to make multiple requests and decompress chunk by chunk
#' for (i in 1:5) { # Adjust the loop count based on the number of chunks you want to retrieve
#' range_end <- range_start + range_increment
#'
#' # Make a byte-range request
#' response <- httr::GET(url, httr::add_headers(`Range` = paste0("bytes=", range_start, "-", range_end)))
#'
#' # Check if the request was successful
#' if (httr::http_type(response) != "application/octet-stream" || httr::http_status(response)$category != "Success") {
#' stop("Failed to retrieve data.")
#' }
#'
#' # Decompress the received chunk
#' compressed_data <- httr::content(response, "raw")
#' decompressed_chunk <- decompressor$decompress(compressed_data)
#' decompressed_content <- c(decompressed_content, rawToChar(decompressed_chunk))
#'
#' # Update the byte range for the next request
#' range_start <- range_end + 1
#' }
#'
#' # Flush the decompressor after all chunks have been processed
#' final_data <- decompressor$flush()
#' decompressed_content <- c(decompressed_content, rawToChar(final_data))
#' }}
#' }
#'
#' In summary, while R’s built-in methods could someday catch up in functionality, the zlib package for now fills an important gap by providing a more robust and flexible way to handle compression and decompression tasks.
#' @keywords internal
.onLoad <- function(libname, pkgname) {
assign("zlib", publicEval({
# constants
list2env(zlib_constants(), envir=environment())
compressobj <- compressobj
decompressobj <- decompressobj
compress <- compress
decompress <- decompress
}, name="zlib"), envir = getNamespace(pkgname))
}
#' Evaluate Expression with Public and Private Environments
#'
#' `publicEval` creates an environment hierarchy consisting of
#' public, self, and private environments. The expression `expr` is
#' evaluated within these nested environments, allowing for controlled
#' variable scope and encapsulation.
#'
#' @section Environments:
#' * Public: Variables in this environment are externally accessible.
#' * Self: Inherits from Public and also contains Private and Public as children.
#' * Private: Variables are encapsulated and are not externally accessible.
#'
#' @param expr An expression to evaluate within the constructed environment hierarchy.
#' @param parentEnv The parent environment for the new 'public' environment. Default is the parent frame.
#' @param name Optional name attribute to set for the public environment.
#'
#' @return Returns an invisible reference to the public environment.
#'
#' @usage publicEval(expr, parentEnv = parent.frame(), name = NULL)
#'
#' @keywords internal
#'
#' @examples
#' publicEnv <- publicEval({
#' private$hidden_var <- "I am hidden"
#' public_var <- "I am public"
#' }, parentEnv = parent.frame(), name = "MyEnvironment")
#'
#' print(exists("public_var", envir = publicEnv)) # Should return TRUE
#' print(exists("hidden_var", envir = publicEnv)) # Should return FALSE
#'
#' @rdname publicEval
#' @name publicEval
publicEval <- function(expr, parentEnv = parent.frame(), name=NULL){
public <- new.env(parent = parentEnv)
self <- new.env(parent = public)
private <- new.env(parent = self)
self$self <- self
self$public <- public
self$private <- private
eval(substitute(expr), envir = self, enclos = .Primitive('baseenv')())
object_names <- names(self)
object_names <- object_names[!(object_names %in% c("public","private","self"))]
if(length(object_names))
invisible(
mapply(assign, object_names, mget(object_names, self), list(public),
SIMPLIFY = FALSE, USE.NAMES = FALSE) )
if(!is.null(name)&&is.character(name)) attr(public, "name") <- name
return(invisible(public))
}
#' Create a Compression Object
#'
#' `compressobj` initializes a new compression object with specified parameters
#' and methods. The function makes use of `publicEval` to manage scope and encapsulation.
#'
#' @section Methods:
#' * `compress(data)`: Compresses a chunk of data.
#' * `flush()`: Flushes the compression buffer.
#'
#' @param level Compression level, default is -1.
#' @param method Compression method, default is `zlib$DEFLATED`.
#' @param wbits Window bits, default is `zlib$MAX_WBITS`.
#' @param memLevel Memory level, default is `zlib$DEF_MEM_LEVEL`.
#' @param strategy Compression strategy, default is `zlib$Z_DEFAULT_STRATEGY`.
#' @param zdict Optional predefined compression dictionary as a raw vector.
#'
#' @return Returns an environment containing the public methods `compress` and `flush`.
#'
#' @usage compressobj(
#' level = -1,
#' method = zlib$DEFLATED,
#' wbits = zlib$MAX_WBITS,
#' memLevel = zlib$DEF_MEM_LEVEL,
#' strategy = zlib$Z_DEFAULT_STRATEGY,
#' zdict = NULL
#' )
#'
#' @examples
#' compressor <- compressobj(level = 6)
#' compressed_data <- compressor$compress(charToRaw("some data"))
#' compressed_data <- c(compressed_data, compressor$flush())
#'
#' @rdname compressobj
#' @name compressobj
#' @export
compressobj <- function(level=-1, method=zlib$DEFLATED, wbits=zlib$MAX_WBITS, memLevel=zlib$DEF_MEM_LEVEL, strategy=zlib$Z_DEFAULT_STRATEGY, zdict=NULL){
return(publicEval({
private$pointer <- create_compressor(level = level, method = method, wbits = wbits, memLevel = memLevel, strategy = strategy, zdict=zdict)
compress <- function(data){
return(compress_chunk(private$pointer, data))
}
flush <- function(mode = zlib$Z_FINISH){
return(flush_compressor_buffer(private$pointer, mode = mode))
}
}))
}
#' Create a new decompressor object
#'
#' Initializes a new decompressor object for zlib-based decompression.
#'
#' @section Methods:
#' * `decompress(data)`: Compresses a chunk of data.
#' * `flush()`: Flushes the compression buffer.
#'
#' @param wbits The window size bits parameter. Default is 0.
#' @return A decompressor object with methods for decompression.
#'
#' @details
#' The returned decompressor object has methods for performing chunk-wise
#' decompression on compressed data using the zlib library.
#'
#' @examples
#' compressor <- zlib$compressobj(zlib$Z_DEFAULT_COMPRESSION, zlib$DEFLATED, zlib$MAX_WBITS + 16)
#' compressed_data <- compressor$compress(charToRaw("some data"))
#' compressed_data <- c(compressed_data, compressor$flush())
#' decompressor <- decompressobj(zlib$MAX_WBITS + 16)
#' decompressed_data <- c(decompressor$decompress(compressed_data), decompressor$flush())
#'
#' @export
decompressobj <- function(wbits = 0) {
return(publicEval({
private$pointer <- create_decompressor(wbits = wbits)
decompress <- function(data) {
return(decompress_chunk(private$pointer, data))
}
flush <- function(length = 256L) {
return(flush_decompressor_buffer(private$pointer, length = length))
}
}))
}
#' Single-step compression of raw data
#'
#' Compresses the provided raw data in a single step.
#'
#' @param data Raw data to be compressed.
#' @param level Compression level, default is -1.
#' @param method Compression method, default is `zlib$DEFLATED`.
#' @param wbits Window bits, default is `zlib$MAX_WBITS`.
#' @param memLevel Memory level, default is `zlib$DEF_MEM_LEVEL`.
#' @param strategy Compression strategy, default is `zlib$Z_DEFAULT_STRATEGY`.
#' @param zdict Optional predefined compression dictionary as a raw vector.
#'
#' @return A raw vector containing the compressed data.
#'
#' @details
#' The `compress` function simplifies the compression process by encapsulating
#' the creation of a compression object, compressing the data, and flushing the buffer
#' all within a single call. This is particularly useful for scenarios where the user
#' wants to quickly compress data without dealing with the intricacies of compression
#' objects and buffer management. The function leverages the `compressobj` function
#' to handle the underlying compression mechanics.
#'
#' @examples
#' compressed_data <- compress(charToRaw("some data"))
#'
#' @export
compress <- function(data, level=-1, method=zlib$DEFLATED, wbits=zlib$MAX_WBITS, memLevel=zlib$DEF_MEM_LEVEL, strategy=zlib$Z_DEFAULT_STRATEGY, zdict=NULL) {
compressor <- compressobj(level, method, wbits, memLevel, strategy, zdict)
compressed_data <- compressor$compress(data)
compressed_data <- c(compressed_data, compressor$flush())
return(compressed_data)
}
#' Single-step decompression of raw data
#'
#' Decompresses the provided compressed raw data in a single step.
#'
#' @param data Compressed raw data to be decompressed.
#' @param wbits The window size bits parameter. Default is 0.
#'
#' @return A raw vector containing the decompressed data.
#'
#' @details
#' The `decompress` function offers a streamlined approach to decompressing
#' raw data. By abstracting the creation of a decompression object, decompressing
#' the data, and flushing the buffer into one function call, it provides a hassle-free
#' way to retrieve original data from its compressed form. This function is designed
#' to work seamlessly with data compressed using the `compress` function or
#' any other zlib-based compression method.
#'
#' @examples
#' original_data <- charToRaw("some data")
#' compressed_data <- compress(original_data)
#' decompressed_data <- decompress(compressed_data)
#'
#' @export
decompress <- function(data, wbits = 0) {
decompressor <- decompressobj(wbits)
decompressed_data <- decompressor$decompress(data)
decompressed_data <- c(decompressed_data, decompressor$flush())
return(decompressed_data)
}
| /scratch/gouwar.j/cran-all/cranData/zlib/R/zlib.R |
#' Imputation
#'
#' Impute `NA` values with the logmean, mean, minimal or maximum reference value.
#'
#' @param x `data.frame`, with the columns: "age", `numeric`, "sex", `factor`
#' and more user defined `numeric` columns that should be imputed.
#' @param limits `data.frame`, reference table, has to have the columns:
#' "age", `numeric` (same units as in `age`, e.g. days or years, age of `0`
#' matches all ages),
#' "sex", `factor` (same levels for male and female as `sex` and a special level
#' `"both"`), "param", `character` with the laboratory parameter name that have
#' to match the column name in `x`, "lower" and "upper", `numeric` for the
#' lower and upper reference limits.
#' @param method `character`, imputation method. `method = "logmean"` (default)
#' replaces all `NA` with its corresponding logged mean values for the reference
#' table `limits` (for subsequent use of the *zlog* score,
#' use `method = "mean" for *z* score calculation).
#' For `method = "min"` or `method = "max"` the lower or the upper limits are
#' used.
#'
#' @note
#' Imputation should be done prior to [`z()`]/[`zlog()`] transformation.
#' Afterwards the `NA` could replaced by zero (for mean-imputation) via
#' `d[is.na(d)] <- 0`.
#' @return `data.frame`, the same as `x` but missing values are replaced by
#' the corresponding logmean, mean, minimal or maximal reference values
#' depending on the chosen `method`.
#'
#' @author Sebastian Gibb
#' @export
#' @examples
#' l <- data.frame(
#' param = c("alb", "bili"),
#' age = c(0, 0),
#' sex = c("both", "both"),
#' units = c("mg/l", "µmol/l"),
#' lower = c(35, 2),
#' upper = c(52, 21)
#' )
#' x <- data.frame(
#' age = 40:48,
#' sex = rep(c("female", "male"), c(5, 4)),
#' # from Hoffmann et al. 2017
#' alb = c(42, NA, 38, NA, 50, 42, 27, 31, 24),
#' bili = c(11, 9, NA, NA, 22, 42, NA, 200, 20)
#' )
#' impute_df(x, l)
#' impute_df(x, l, method = "min")
#' zlog_df(impute_df(x, l), l)
impute_df <- function(x, limits, method = c("logmean", "mean", "min", "max")) {
limits <- .lookup_limits_df(x, limits)
prms <- unique(rownames(limits))
v <- switch(
match.arg(method),
"min" = limits[, "lower"],
"max" = limits[, "upper"],
"mean" = (limits[, "lower"] + limits[, "upper"]) / 2L,
"logmean" = exp(log(limits[, "lower"] * limits[, "upper"]) / 2L)
)
na <- is.na(x[prms])
x[prms][na] <- v[na]
x
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/impute.R |
#' Calculate Laboratory Measurements from z/zlog Values
#'
#' Inverse function to z or z(log) for laboratory measurement standardisation
#' as proposed in Hoffmann 2017 et al.
#'
#' @param x `numeric`, z/zlog values.
#' @param limits `numeric` or `matrix`, lower and upper reference limits. Has to
#' be of length 2 for `numeric` or a two-column `matrix` with as many rows as
#' elements in `x`.
#' @param probs `numeric`, probabilities of the lower and upper reference limit,
#' default: `c(0.025, 0.975)` (spanning 95 %). Has to be of length 2 for
#' `numeric` or a two-column `matrix` with as many rows as elements in `x`.
#'
#' @details
#' The inverse z value is calculated as follows (assuming that the limits where
#' 0.025 and 0.975 quantiles):
#' \eqn{x = z * (limits_2 - limits_1)/3.92 + (limits_1 + limits_2)/2}
#'
#' The inverse z(log) value is calculated as follows (assuming that the limits
#' where 0.025 and 0.975 quantiles):
#' \eqn{x = \exp(z * (\log(limits_2) - \log(limits_1))/3.92 + (\log(limits_1) + \log(limits_2))/2)}
#'
#' @return `numeric`, laboratory measurements.
#' @rdname izlog
#' @author Sebastian Gibb
#' @references
#' Georg Hoffmann, Frank Klawonn, Ralf Lichtinghagen, and Matthias Orth.
#' 2017.
#' "The Zlog-Value as Basis for the Standardization of Laboratory Results."
#' LaboratoriumsMedizin 41 (1): 23–32.
#' \doi{10.1515/labmed-2016-0087}.
#' @seealso [`zlog()`]
#'
#' @importFrom stats qnorm
#' @export
#' @examples
#' iz(z(1:10, limits = c(2, 8)), limits = c(2, 8))
#'
iz <- function(x, limits, probs = c(0.025, 0.975)) {
if (!(is.numeric(limits) && length(limits) == 2L) &&
!(is.matrix(limits) && mode(limits) == "numeric" &&
nrow(limits) == length(x) && ncol(limits) == 2L))
stop("'limits' has to be a numeric of length 2, or a ",
"matrix with 2 columns (lower and upper limit) where ",
"the number of rows equals the length of 'x'.")
if (!is.matrix(limits))
limits <- t(limits)
if (!(is.numeric(probs) && length(probs) == 2L) &&
!(is.matrix(probs) && mode(probs) == "numeric" &&
nrow(probs) == length(x) && ncol(probs) == 2L))
stop("'probs' has to be a numeric of length 2, or a ",
"matrix with 2 columns (lower and upper limit) where ",
"the number of rows equals the length of 'x'.")
if (!is.matrix(probs))
probs <- t(probs)
m <- (limits[, 1L] + limits[, 2L]) / 2L
s <- abs(limits[, 2L] - limits[, 1L]) / rowSums(abs(qnorm(probs)))
x * s + m
}
#' @rdname izlog
#' @export
#' @examples
#' # from Hoffmann et al. 2017
#' albuminzlog <- c(-0.15, -2.25, -1.15, 0.08, 1.57, -0.15, -4.53, -3.16, -5.70)
#' izlog(albuminzlog, limits = c(35, 52))
#'
#' bilirubinzlog <- c(0.85, 0.57, -1.96, -0.43, 2.04, 3.12, 2.90, 5.72, 1.88)
#'
#' limits <- cbind(
#' lower = rep(c(35, 2), c(length(albuminzlog), length(bilirubinzlog))),
#' upper = rep(c(52, 21), c(length(albuminzlog), length(bilirubinzlog)))
#' )
#' izlog(c(albuminzlog, bilirubinzlog), limits = limits)
izlog <- function(x, limits, probs = c(0.025, 0.975)) {
if (missing(limits))
stop("argument \"limits\" is missing, with no default")
exp(iz(x, log(limits), probs))
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/izlog.R |
#' Lookup Limits in Reference Tables
#'
#' Reference limits are specific for age and sex. Each laboratory institute has
#' its own reference limits. This function is useful to query a dataset against
#' this database.
#'
#' @param age `numeric`, patient age.
#' @param sex `character`/`factor`, patient sex, has to be the same length as
#' `age`.
#' @param table `data.frame`, reference table, has to have the columns:
#' "age", `numeric` (same units as in `age`, e.g. days or years, age of `0`
#' matches all ages),
#' "sex", `factor` (same levels for male and female as `sex` and a special level
#' `"both"`), "lower" and "upper", `numeric` for the lower and upper reference
#' limits. If an "param" column is given the "lower" and "upper" limits for all
#' different values in "param" is returned. Additional columns are allowed (and
#' ignored).
#'
#' @return `matrix`, with 2 columns ("lower", "upper") and as many rows as
#' `length(age)`.
#' @author Sebastian Gibb
#' @importFrom stats setNames quantile
#' @export
#' @examples
#' reference <- data.frame(
#' param = c("albumin", rep("bilirubin", 4)),
#' age = c(0, 1, 2, 3, 7), # days
#' sex = "both",
#' units = c("g/l", rep("µmol/l", 4)), # ignored
#' lower = c(35, rep(NA, 4)), # no real reference values
#' upper = c(52, 5, 8, 13, 18) # no real reference values
#' )
#'
#' # lookup albumin reference values for 18 year old woman
#' lookup_limits(
#' age = 18 * 365.25,
#' sex = "female",
#' table = reference[reference$param == "albumin",]
#' )
#'
#' # lookup albumin and bilirubin values for 18 year old woman
#' lookup_limits(
#' age = 18 * 365.25,
#' sex = "female",
#' table = reference
#' )
#'
#' # lookup bilirubin referenc values for infants
#' lookup_limits(
#' age = 0:8,
#' sex = rep(c("female", "male"), 5:4),
#' table = reference[reference$param == "bilirubin",]
#' )
lookup_limits <- function(age, sex, table) {
if (!is.numeric(age))
stop("'age' has to be a numeric value.")
if (length(age) != length(sex))
stop("'age' and 'sex' have to be of the same length.")
sex <- as.factor(sex)
if (nlevels(sex) > 2)
stop("'sex' has to be a factor of at most 2 levels ",
"(male, female).")
cn <- colnames(table) <- tolower(colnames(table))
if (!all(c("age", "sex", "lower", "upper") %in% cn))
stop("'table' has to have the columns: ",
"\"age\", \"sex\", \"upper\", \"lower\".")
table$sex <- as.factor(table$sex)
if (nlevels(table$sex) > 3)
stop("'table$sex' has to be a factor of at most 3 levels ",
"(male, female, both).")
if (!"param" %in% cn)
table$param <- "param"
params <- unique(table$param)
nparam <- length(params)
nage <- length(age)
table <- table[order(table$age, decreasing = TRUE),]
limits <- matrix(
NA_real_, nrow = nage * nparam, ncol = 2L,
dimnames = list(
if (nparam > 1L || params != "param")
rep(params, each = nage)
else
NULL,
c("lower", "upper")
)
)
for (i in seq(along = params)) {
for (j in seq(along = age)) {
k <- which(
(sex[j] == table$sex | table$sex == "both") &
age[j] >= table$age & params[i] == table$param
)[1L]
if (length(k))
limits[(i - 1) * nage + j, ] <-
c(table$lower[k], table$upper[k])
}
}
limits
}
#' Lookup Limits in Reference Tables for a Whole data.frame
#'
#' internal function
#'
#' @param x `data.frame`
#' @param table `data.frame`, reference table, format see above
#' @return see above
#'
#' @noRd
.lookup_limits_df <- function(x, limits) {
if (!is.data.frame(x)) {
stop("'x' has to be a data.frame.")
}
cnx <- colnames(x)
cnxl <- tolower(cnx)
if (!"age" %in% cnxl)
stop("Column \"age\" is missing in 'x'.")
if (!"sex" %in% cnxl)
stop("Column \"sex\" is missing in 'x'.")
if (!is.data.frame(limits))
stop("'limits' has to be a data.frame.")
cnl <- colnames(limits) <- tolower(colnames(limits))
if (!all(c("age", "sex", "param", "lower", "upper") %in% cnl))
stop("'limits' has to be a data.frame with the following columns: ",
"\"age\", \"sex\", \"param\", \"upper\", \"lower\".\n",
"See '?lookup_limits' for details.")
num <- vapply(x, is.numeric, FALSE, USE.NAMES = FALSE) &
!cnxl %in% c("age", "sex")
if (any(!cnx[num] %in% limits$param)) {
na <- cnx[num & (!cnx %in% limits$param)]
warning(
"No reference for column(s): ", paste0(na, collapse = ", ")
)
ina <- nrow(limits) + seq_len(length(na))
limits[ina, c("param", "age", "sex")] <-
cbind.data.frame(param = na, age = 0L, sex = "both")
}
lookup_limits(
age = x[[which(cnxl == "age")]], sex = x[[which(cnxl == "sex")]],
table = limits[limits$param %in% cnx[num],]
)
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/lookup_limits.R |
#' Calculate Reference Limits
#'
#' Calculates the lower and upper reference limit for given probabilities.
#'
#' @param x `numeric`, laboratory values
#' @param probs `numeric`, probabilities of the lower and upper reference limit,
#' default: `c(0.025, 0.975)` (spanning 95 %).
#' @param na.rm `logical`, if `TRUE` (default) `NA` values are removed before
#' the reference limits are calculated.
#'
#' @return `numeric` of length 2 with the lower and upper limit.
#'
#' @author Sebastian Gibb
#' @importFrom stats setNames quantile
#' @export
#' @examples
#' reference_limits(1:10)
reference_limits <- function(x, probs = c(0.025, 0.975), na.rm = TRUE) {
if (!is.numeric(probs) || length(probs) != 2L)
stop("'probs' has to be a numeric of length 2.")
setNames(
quantile(x, probs = range(probs), na.rm = na.rm, names = FALSE),
c("lower", "upper")
)
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/reference_limits.R |
#' Set Missing Limits in Reference Tables
#'
#' Sometimes reference limits are not specified. That is often the case for
#' biomarkers that are related to infection or cancer. Using zero as lower
#' boundary results in skewed distributions (Hoffmann et al. 2017; fig. 7).
#' Haeckel et al. 2015 suggested to set the lower reference limit to 0.15 of
#' the upper one.
#'
#' @param x `data.frame`, reference table, has to have the columns:
#' "lower" and "upper", `numeric` for the lower and upper reference
#' limits. Additional columns are allowed (and ignored).
#' @param fraction `numeric(2)`, targeted fraction of the lower to the upper and
#' the upper to the lower limit. Haeckel et al. 2015 suggested to set the lower
#' limit to 0.15 of the upper one. We choose 20/3 (the reciprocal of 0.15) for
#' the upper to the lower one.
#'
#' @return `data.frame`, the same as `x` but the "lower" and "upper" columns are
#' modified if there were `NA` before.
#' @author Sebastian Gibb
#' @references
#' Georg Hoffmann, Frank Klawonn, Ralf Lichtinghagen, and Matthias Orth.
#' 2017.
#' "The Zlog-Value as Basis for the Standardization of Laboratory Results."
#' LaboratoriumsMedizin 41 (1): 23–32.
#' \doi{10.1515/labmed-2016-0087}.
#'
#' Rainer Haeckel, Werner Wosniok, Ebrhard Gurr and Burkhard Peil.
#' 2015.
#' "Permissible limits for uncertainty of measurement in laboratory medicine"
#' Clinical Chemistry and Laboratory Medicine 53 (8): 1161-1171.
#' \doi{10.1515/cclm-2014-0874}.
#' @export
#' @examples
#' reference <- data.frame(
#' param = c("albumin", rep("bilirubin", 4)),
#' age = c(0, 1, 2, 3, 7), # ignored
#' sex = "both", # ignored
#' units = c("g/l", rep("µmol/l", 4)), # ignored
#' lower = c(35, rep(NA, 4)), # no real reference values
#' upper = c(52, 5, 8, 13, 18) # no real reference values
#' )
#' set_missing_limits(reference)
#' set_missing_limits(reference, fraction = c(0.2, 5))
set_missing_limits <- function(x, fraction = c(0.15, 20/3)) {
if (!is.data.frame(x))
stop("'x' has to be a data.frame")
if (!all(c("lower", "upper") %in% colnames(x)))
stop("'x' has to have the columns: \"upper\", \"lower\".")
if (!is.numeric(fraction) || length(fraction) != 2L)
stop("'fraction' has to be a numeric of length 2")
na <- is.na(x[c("lower", "upper")])
x$lower[na[, "lower"]] <- x$upper[na[, "lower"]] * fraction[1L]
x$upper[na[, "upper"]] <- x$lower[na[, "upper"]] * fraction[2L]
x
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/set_missing_limits.R |
#' Z(log) Depending Color
#'
#' This function provides a color gradient depending on the zlog value as
#' described in Hoffmann et al. 2017. The colours are only roughly equal to the
#' one found in the article.
#'
#' @param x `numeric`, z(log) value.
#' @return `character`, of `length(x)` with the corresponding color hex code.
#'
#' @author Sebastian Gibb
#' @references
#' Hoffmann, Georg, Frank Klawonn, Ralf Lichtinghagen, and Matthias Orth.
#' 2017.
#' "The Zlog-Value as Basis for the Standardization of Laboratory Results."
#' LaboratoriumsMedizin 41 (1): 23–32. \doi{10.1515/labmed-2016-0087}.
#' @importFrom graphics image text
#' @importFrom grDevices rgb
#' @export
#' @examples
#' z <- -10:10
#' image(matrix(z, ncol = 1), col = zcol(z), xaxt = "n", yaxt = "n")
#' text(seq(0, 1, length.out=length(z)), 0, label = z)
zcol <- function(x) {
x[is.na(x)] <- 0
## the colour values are picked from the PDF version of Hoffmann et al. 2017
## and may be incorrect cause of jpeg artefacts
rgb(
red = 255 - .zlogF(x, ifelse(x < 0, 185, 10)),
green = 255 - .zlogF(x, 135),
blue = 255 - .zlogF(x, ifelse(x < 0, 70, 255)),
maxColorValue = 255
)
}
#' Map zlog Value to 0:255
#'
#' Similar to the `F` described in Hoffmann et al. 2017.
#'
#' @param x `numeric`, zlog value.
#' @param d `numeric`, scale value.
#'
#' @return `numeric`, of `length(x)` in the range `0:255`.
#' @noRd
.zlogF <- function(x, d) {
# the proposed function in Hoffmann et al. 2017 doesn't increase enough,
# so we add 4 here
# the color range is white:color for 0:10, 0:1 should be white, 2 should
# have a clear visible color, d / 1 + exp(4 - abs(x)) is in the range from
# 4.6:254.4 for x = 0:10 and d = 255
d / (1 + exp(4 - abs(x)))
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/zcol.R |
#' Calculate z/zlog Values
#'
#' Calculates the z or z(log) values for laboratory measurement standardisation
#' as proposed in Hoffmann 2017 et al.
#'
#' @param x `numeric`, laboratory values.
#' @param limits `numeric` or `matrix`, lower and upper reference limits. Has to
#' be of length 2 for `numeric` or a two-column `matrix` with as many rows as
#' elements in `x`.
#' @param probs `numeric`, probabilities of the lower and upper reference limit,
#' default: `c(0.025, 0.975)` (spanning 95 %). Has to be of length 2 for
#' `numeric` or a two-column `matrix` with as many rows as elements in `x`.
#' @param log `logical`, should z (`log = FALSE`, default) or
#' z(log) (`log = TRUE`) calculated?
#'
#' @details
#' The z value is calculated as follows (assuming that the limits where 0.025
#' and 0.975 quantiles):
#' \eqn{z = (x - (limits_1 + limits_2 )/2) * 3.92/(limits_2 - limits_1)}.
#'
#' The z(log) value is calculated as follows (assuming that the limits where 0.025
#' and 0.975 quantiles):
#' \eqn{z = (\log(x) - (\log(limits_1) + \log(limits_2))/2) * 3.92/(\log(limits_2) - \log(limits_1))}.
#'
#' `zlog` is an alias for `z(..., log = TRUE)`.
#'
#' @return `numeric`, z or z(log) values.
#' @rdname zlog
#' @author Sebastian Gibb
#' @references
#' Georg Hoffmann, Frank Klawonn, Ralf Lichtinghagen, and Matthias Orth.
#' 2017.
#' "The Zlog-Value as Basis for the Standardization of Laboratory Results."
#' LaboratoriumsMedizin 41 (1): 23–32.
#' \doi{10.1515/labmed-2016-0087}.
#' @seealso [`izlog()`]
#'
#' @importFrom stats qnorm
#' @export
#' @examples
#' z(1:10, limits = c(2, 8))
#'
z <- function(x, limits, probs = c(0.025, 0.975), log = FALSE) {
if (!(is.numeric(limits) && length(limits) == 2L) &&
!(is.matrix(limits) && mode(limits) == "numeric" &&
nrow(limits) == length(x) && ncol(limits) == 2L))
stop("'limits' has to be a numeric of length 2, or a ",
"matrix with 2 columns (lower and upper limit) where ",
"the number of rows equals the length of 'x'.")
if (!is.matrix(limits))
limits <- t(limits)
if (!(is.numeric(probs) && length(probs) == 2L) &&
!(is.matrix(probs) && mode(probs) == "numeric" &&
nrow(probs) == length(x) && ncol(probs) == 2L))
stop("'probs' has to be a numeric of length 2, or a ",
"matrix with 2 columns (lower and upper limit) where ",
"the number of rows equals the length of 'x'.")
if (!is.matrix(probs))
probs <- t(probs)
if (log) {
x <- log(x)
limits <- log(limits)
}
m <- (limits[, 1L] + limits[, 2L]) / 2L
s <- abs(limits[, 2L] - limits[, 1L]) / rowSums(abs(qnorm(probs)))
(x - m) / s
}
#' @rdname zlog
#' @export
#' @examples
#' # from Hoffmann et al. 2017
#' albumin <- c(42, 34, 38, 43, 50, 42, 27, 31, 24)
#' zlog(albumin, limits = c(35, 52))
#'
#' bilirubin <- c(11, 9, 2, 5, 22, 42, 37, 200, 20)
#'
#' limits <- cbind(
#' lower = rep(c(35, 2), c(length(albumin), length(bilirubin))),
#' upper = rep(c(52, 21), c(length(albumin), length(bilirubin)))
#' )
#' zlog(c(albumin, bilirubin), limits = limits)
zlog <- function(x, limits, probs = c(0.025, 0.975)) {
z(x, limits, probs, log = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/zlog.R |
#' Calculate z/zlog Values for a data.frame
#'
#' Calculates the z or z(log) values for laboratory measurement standardisation
#' as proposed in Hoffmann 2017 et al. for a complete `data.frame`.
#'
#' @param x `data.frame`, with the columns: "age", `numeric`, "sex", `factor`
#' and more user defined `numeric` columns that should be z/z(log) transformed.
#' @param limits `data.frame`, reference table, has to have the columns:
#' "age", `numeric` (same units as in `age`, e.g. days or years, age of `0`
#' matches all ages),
#' "sex", `factor` (same levels for male and female as `sex` and a special level
#' `"both"`), "param", `character` with the laboratory parameter name that have
#' to match the column name in `x`, "lower" and "upper", `numeric` for the
#' lower and upper reference limits.
#' @param probs `numeric`, probabilities of the lower and upper reference limit,
#' default: `c(0.025, 0.975)` (spanning 95 %). Has to be of length 2 for
#' `numeric` or a two-column `matrix` with as many rows as elements in `x`.
#' @param log `logical`, should z (`log = FALSE`, default) or
#' z(log) (`log = TRUE`) calculated?
#'
#' @details
#' This is a wrapper function for [`z()`] and [`lookup_limits()`]. Please find
#' the details for the z/z(log) calculation at [`z()`].
#'
#' `zlog_df` is an alias for `z_df(..., log = TRUE)`.
#'
#' @return `data.frame`, with the columns: "age", "sex" and all `numeric`
#' columns z/zlog transformed. If a column name is missing in `limits$param`
#' a warning is thrown and the column is set to `NA`.
#' @rdname zlog_df
#' @author Sebastian Gibb
#' @references
#' Georg Hoffmann, Frank Klawonn, Ralf Lichtinghagen, and Matthias Orth.
#' 2017.
#' "The Zlog-Value as Basis for the Standardization of Laboratory Results."
#' LaboratoriumsMedizin 41 (1): 23–32.
#' \doi{10.1515/labmed-2016-0087}.
#' @seealso [`zlog()`]
#'
#' @export
#' @examples
#' l <- data.frame(
#' param = c("alb", "bili"),
#' age = c(0, 0),
#' sex = c("both", "both"),
#' units = c("mg/l", "µmol/l"),
#' lower = c(35, 2),
#' upper = c(52, 21)
#' )
#' x <- data.frame(
#' age = 40:48,
#' sex = rep(c("female", "male"), c(5, 4)),
#' # from Hoffmann et al. 2017
#' alb = c(42, 34, 38, 43, 50, 42, 27, 31, 24),
#' bili = c(11, 9, 2, 5, 22, 42, 37, 200, 20)
#' )
#' z_df(x, l)
#'
z_df <- function(x, limits, probs = c(0.025, 0.975), log = FALSE) {
limits <- .lookup_limits_df(x, limits)
prms <- unique(rownames(limits))
x[prms] <- z(as.matrix(x[prms]), limits, probs = probs, log = log)
x
}
#' @rdname zlog_df
#' @export
#' @examples
#' zlog_df(x, l)
zlog_df <- function(x, limits, probs = c(0.025, 0.975)) {
z_df(x, limits, probs, log = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zlog/R/zlog_df.R |
## ----zlog---------------------------------------------------------------------
library("zlog")
albumin <- c(42, 34, 38, 43, 50, 42, 27, 31, 24)
z(albumin, limits = c(35, 52))
zlog(albumin, limits = c(35, 52))
## ----izlog--------------------------------------------------------------------
izlog(zlog(albumin, limits = c(35, 52)), limits = c(35, 52))
## ----zcol, echo = FALSE, out.width = "95%", fig.width = 10, fig.height = 1, fig.align = "center"----
z <- -10:10
oldpar <- par(mar = c(0, 0, 0, 0), oma = c(0, 0, 0, 0))
image(matrix(z, ncol = 1), col = zcol(z), axes = FALSE)
text(seq(0, 1, length.out=length(z)), 0, label = z)
par(oldpar)
## ----zcoltable, echo = FALSE, result = "asis"---------------------------------
bilirubin <- c(11, 9, 2, 5, 22, 42, 37, 200, 20)
zloga <- zlog(albumin, limits = c(35, 52))
zlogb <- zlog(bilirubin, limits = c(2, 21))
d <- data.frame(
Category = c(
rep(c(
"blood donor",
"hepatitis without cirrhosis",
"hepatitis with cirrhosis"
),
each = 3
)
),
albumin = albumin,
zloga = zloga,
bilirubin = bilirubin,
zlogb = zlogb
)
d$albumin <- kableExtra::cell_spec(
d$albumin, background = zcol(zloga), align = "right"
)
d$bilirubin <- kableExtra::cell_spec(
d$bilirubin, background = zcol(zlogb), align = "right"
)
kableExtra::kable_classic(
kableExtra::kbl(
d,
col.names = c(
"Category",
"albumin", "zlog(albumin)", "bilirubin", "zlog(bilirubin)"
),
digits = 2,
escape = FALSE,
caption = paste0(
"Table reproduced from @hoffmann2017, Table 2, limits used: ",
"albumin 35-52 g/l, bilirubin 2-21 µmol/l."
)
),
"basic"
)
## ----reference_limits---------------------------------------------------------
reference_limits(albumin)
reference_limits(albumin, probs = c(0.05, 0.95))
exp(reference_limits(log(albumin)))
## ----reference_table----------------------------------------------------------
# toy example
reference <- data.frame(
param = c("albumin", rep("bilirubin", 4)),
age = c(0, 1, 2, 3, 7), # days
sex = "both",
units = c("g/l", rep("µmol/l", 4)), # ignored
lower = c(35, rep(NA, 4)), # no real reference values
upper = c(52, 5, 8, 13, 18) # no real reference values
)
knitr::kable(reference)
# lookup albumin reference values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference[reference$param == "albumin",]
)
# lookup albumin and bilirubin values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference
)
# lookup bilirubin reference values for infants
lookup_limits(
age = 0:8,
sex = rep(c("female", "male"), 5:4),
table = reference[reference$param == "bilirubin",]
)
## ----missing_reference--------------------------------------------------------
# use default fractions
set_missing_limits(reference)
# set fractions manually
set_missing_limits(reference, fraction = c(0.2, 5))
## ----impute_missing_values----------------------------------------------------
x <- data.frame(
age = c(40, 50),
sex = c("female", "male"),
albumin = c(42, NA)
)
x
z_df(impute_df(x, reference, method = "mean"), reference)
zlog_df(impute_df(x, reference), reference)
## ----pbc_load-----------------------------------------------------------------
library("survival")
data("pbc")
labs <- c(
"bili", "chol", "albumin", "copper", "alk.phos", "ast", "trig",
"platelet", "protime"
)
pbc <- pbc[, c("age", "sex", labs)]
knitr::kable(head(pbc), digits = 1)
## ----pbc_reference_limits-----------------------------------------------------
## replicate copper and ast 2 times, use the others just once
param <- rep(labs, ifelse(labs %in% c("copper", "ast"), 2, 1))
sex <- rep_len("both", length(param))
## replace sex == both with female and male for copper and ast
sex[param %in% c("copper", "ast")] <- c("f", "m")
## create data.frame, we ignore age-specific values for now and set age to zero
## (means applicable for all ages)
reference <- data.frame(
param = param, age = 0, sex = sex, lower = NA, upper = NA
)
## estimate reference limits from sample data
for (i in seq_len(nrow(reference))) {
reference[i, c("lower", "upper")] <-
if (reference$sex[i] == "both")
reference_limits(pbc[reference$param[i]])
else
reference_limits(pbc[pbc$sex == reference$sex[i], reference$param[i]])
}
knitr::kable(reference)
## ----pbc_impute---------------------------------------------------------------
pbc[c(6, 14),]
pbc <- impute_df(pbc, reference)
pbc[c(6, 14),]
## ----pbc_zlog-----------------------------------------------------------------
pbc <- zlog_df(pbc, reference)
## ----pbc_table, echo = FALSE--------------------------------------------------
pbctbl <- head(pbc, n = 25)
pbctbl[labs] <- lapply(labs, function(l) {
kableExtra::cell_spec(
sprintf("%.1f", unlist(pbctbl[l])),
background = zcol(unlist(pbctbl[l])),
align = "right"
)
})
kableExtra::kable_classic(
kableExtra::kbl(pbctbl, digits = 1, escape = FALSE),
"basic"
)
## ----si-----------------------------------------------------------------------
sessionInfo()
| /scratch/gouwar.j/cran-all/cranData/zlog/inst/doc/zlog.R |
---
title: Z(log) Transformation for Laboratory Measurements
output:
rmarkdown::html_vignette:
toc_float: true
vignette: >
%\VignetteIndexEntry{Z(log) Transformation for Laboratory Measurements}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: bibliography.bib
---
# Introduction
The `zlog` package offers functions to transform laboratory measurements into
standardised $z$ or $z(log)$-values as suggested in @hoffmann2017.
Therefore the lower and upper reference limits are needed. If these are not
known they could estimated from a given sample.
# Z or Z(log) Transformation
@hoffmann2017 define $z$ as follows:
$$z = (x - (limits_1 + limits_2 )/2) * 3.92/(limits_2 - limits_1)$$
Consequently the $z(log)$ is defined as:
$$zlog = (\log(x) - (\log(limits_1) + \log(limits_2))/2) * 3.92/(\log(limits_2) - \log(limits_1))$$
Where $x$ is the measured laboratory value and $limits_1$ and $limits_2$ are
the lower and upper reference limit, respectively.
Example data and reference limits are taken from @hoffmann2017, Table 2.
```{r zlog}
library("zlog")
albumin <- c(42, 34, 38, 43, 50, 42, 27, 31, 24)
z(albumin, limits = c(35, 52))
zlog(albumin, limits = c(35, 52))
```
# Inverse Z or Z(log) Transformation/Undo Transformation
```{r izlog}
izlog(zlog(albumin, limits = c(35, 52)), limits = c(35, 52))
```
# Z(log) Dependent Colour Gradient
@hoffmann2017 suggested a colour gradient to visualise laboratory measurements
for the user.
```{r zcol, echo = FALSE, out.width = "95%", fig.width = 10, fig.height = 1, fig.align = "center"}
z <- -10:10
oldpar <- par(mar = c(0, 0, 0, 0), oma = c(0, 0, 0, 0))
image(matrix(z, ncol = 1), col = zcol(z), axes = FALSE)
text(seq(0, 1, length.out=length(z)), 0, label = z)
par(oldpar)
```
It could be used to highlight the values in a table:
```{r zcoltable, echo = FALSE, result = "asis"}
bilirubin <- c(11, 9, 2, 5, 22, 42, 37, 200, 20)
zloga <- zlog(albumin, limits = c(35, 52))
zlogb <- zlog(bilirubin, limits = c(2, 21))
d <- data.frame(
Category = c(
rep(c(
"blood donor",
"hepatitis without cirrhosis",
"hepatitis with cirrhosis"
),
each = 3
)
),
albumin = albumin,
zloga = zloga,
bilirubin = bilirubin,
zlogb = zlogb
)
d$albumin <- kableExtra::cell_spec(
d$albumin, background = zcol(zloga), align = "right"
)
d$bilirubin <- kableExtra::cell_spec(
d$bilirubin, background = zcol(zlogb), align = "right"
)
kableExtra::kable_classic(
kableExtra::kbl(
d,
col.names = c(
"Category",
"albumin", "zlog(albumin)", "bilirubin", "zlog(bilirubin)"
),
digits = 2,
escape = FALSE,
caption = paste0(
"Table reproduced from @hoffmann2017, Table 2, limits used: ",
"albumin 35-52 g/l, bilirubin 2-21 µmol/l."
)
),
"basic"
)
```
# Estimate Reference Limits
The `reference_limits` functions calculates the lower and upper 2.5 or 97.5
(or a user given probability) quantiles:
```{r reference_limits}
reference_limits(albumin)
reference_limits(albumin, probs = c(0.05, 0.95))
exp(reference_limits(log(albumin)))
```
# Working with Reference Tables
Most laboratories use their own age- and sex-specific reference limits.
The `lookup_limits` function could be used to find the correct reference limit.
```{r reference_table}
# toy example
reference <- data.frame(
param = c("albumin", rep("bilirubin", 4)),
age = c(0, 1, 2, 3, 7), # days
sex = "both",
units = c("g/l", rep("µmol/l", 4)), # ignored
lower = c(35, rep(NA, 4)), # no real reference values
upper = c(52, 5, 8, 13, 18) # no real reference values
)
knitr::kable(reference)
# lookup albumin reference values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference[reference$param == "albumin",]
)
# lookup albumin and bilirubin values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference
)
# lookup bilirubin reference values for infants
lookup_limits(
age = 0:8,
sex = rep(c("female", "male"), 5:4),
table = reference[reference$param == "bilirubin",]
)
```
# Missing Reference Limits
Sometimes reference limits are not specified. That is often the case for
biomarkers that are related to infection or cancer. Using zero as lower
boundary results in skewed distributions [@hoffmann2017, fig. 7].
@haeckel2015 suggested to set the lower reference limit to 15 % of
the upper one.
```{r missing_reference}
# use default fractions
set_missing_limits(reference)
# set fractions manually
set_missing_limits(reference, fraction = c(0.2, 5))
```
# Impute Missing Laboratory Measurements
If laboratory measurements are missing they could be imputed using *"normal"*
values from the reference table. Using the `"logmean"` (default) or `"mean"`
reference value (default) will result in a $zlog$ or $z$-value of zero,
respectively.
```{r impute_missing_values}
x <- data.frame(
age = c(40, 50),
sex = c("female", "male"),
albumin = c(42, NA)
)
x
z_df(impute_df(x, reference, method = "mean"), reference)
zlog_df(impute_df(x, reference), reference)
```
# `PBC` Example
For demonstration we choose the `pbc` dataset from the `survival` package
and exclude all non-laboratory measurements except *age* and *sex*:
```{r pbc_load}
library("survival")
data("pbc")
labs <- c(
"bili", "chol", "albumin", "copper", "alk.phos", "ast", "trig",
"platelet", "protime"
)
pbc <- pbc[, c("age", "sex", labs)]
knitr::kable(head(pbc), digits = 1)
```
Next we estimate all reference limits from the data. We want to use sex-specific
values for copper and aspartate aminotransferase (`"ast"`).
```{r pbc_reference_limits}
## replicate copper and ast 2 times, use the others just once
param <- rep(labs, ifelse(labs %in% c("copper", "ast"), 2, 1))
sex <- rep_len("both", length(param))
## replace sex == both with female and male for copper and ast
sex[param %in% c("copper", "ast")] <- c("f", "m")
## create data.frame, we ignore age-specific values for now and set age to zero
## (means applicable for all ages)
reference <- data.frame(
param = param, age = 0, sex = sex, lower = NA, upper = NA
)
## estimate reference limits from sample data
for (i in seq_len(nrow(reference))) {
reference[i, c("lower", "upper")] <-
if (reference$sex[i] == "both")
reference_limits(pbc[reference$param[i]])
else
reference_limits(pbc[pbc$sex == reference$sex[i], reference$param[i]])
}
knitr::kable(reference)
```
The `pbc` dataset contains a few missing values. We impute the with the
corresponding mean reference value (which is in this example just the sample
mean but would be in real life the mean of a e.g. healthy subpopulation).
```{r pbc_impute}
pbc[c(6, 14),]
pbc <- impute_df(pbc, reference)
pbc[c(6, 14),]
```
Subsequently we can convert the laboratory measurements into $z(log)$-values
using the `zlog_df` function that applies the `zlog` for every `numeric` column
in a `data.frame` (except the `"age"` column):
```{r pbc_zlog}
pbc <- zlog_df(pbc, reference)
```
```{r pbc_table, echo = FALSE}
pbctbl <- head(pbc, n = 25)
pbctbl[labs] <- lapply(labs, function(l) {
kableExtra::cell_spec(
sprintf("%.1f", unlist(pbctbl[l])),
background = zcol(unlist(pbctbl[l])),
align = "right"
)
})
kableExtra::kable_classic(
kableExtra::kbl(pbctbl, digits = 1, escape = FALSE),
"basic"
)
```
# Session information
```{r si}
sessionInfo()
```
# References
| /scratch/gouwar.j/cran-all/cranData/zlog/inst/doc/zlog.Rmd |
---
title: Z(log) Transformation for Laboratory Measurements
output:
rmarkdown::html_vignette:
toc_float: true
vignette: >
%\VignetteIndexEntry{Z(log) Transformation for Laboratory Measurements}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: bibliography.bib
---
# Introduction
The `zlog` package offers functions to transform laboratory measurements into
standardised $z$ or $z(log)$-values as suggested in @hoffmann2017.
Therefore the lower and upper reference limits are needed. If these are not
known they could estimated from a given sample.
# Z or Z(log) Transformation
@hoffmann2017 define $z$ as follows:
$$z = (x - (limits_1 + limits_2 )/2) * 3.92/(limits_2 - limits_1)$$
Consequently the $z(log)$ is defined as:
$$zlog = (\log(x) - (\log(limits_1) + \log(limits_2))/2) * 3.92/(\log(limits_2) - \log(limits_1))$$
Where $x$ is the measured laboratory value and $limits_1$ and $limits_2$ are
the lower and upper reference limit, respectively.
Example data and reference limits are taken from @hoffmann2017, Table 2.
```{r zlog}
library("zlog")
albumin <- c(42, 34, 38, 43, 50, 42, 27, 31, 24)
z(albumin, limits = c(35, 52))
zlog(albumin, limits = c(35, 52))
```
# Inverse Z or Z(log) Transformation/Undo Transformation
```{r izlog}
izlog(zlog(albumin, limits = c(35, 52)), limits = c(35, 52))
```
# Z(log) Dependent Colour Gradient
@hoffmann2017 suggested a colour gradient to visualise laboratory measurements
for the user.
```{r zcol, echo = FALSE, out.width = "95%", fig.width = 10, fig.height = 1, fig.align = "center"}
z <- -10:10
oldpar <- par(mar = c(0, 0, 0, 0), oma = c(0, 0, 0, 0))
image(matrix(z, ncol = 1), col = zcol(z), axes = FALSE)
text(seq(0, 1, length.out=length(z)), 0, label = z)
par(oldpar)
```
It could be used to highlight the values in a table:
```{r zcoltable, echo = FALSE, result = "asis"}
bilirubin <- c(11, 9, 2, 5, 22, 42, 37, 200, 20)
zloga <- zlog(albumin, limits = c(35, 52))
zlogb <- zlog(bilirubin, limits = c(2, 21))
d <- data.frame(
Category = c(
rep(c(
"blood donor",
"hepatitis without cirrhosis",
"hepatitis with cirrhosis"
),
each = 3
)
),
albumin = albumin,
zloga = zloga,
bilirubin = bilirubin,
zlogb = zlogb
)
d$albumin <- kableExtra::cell_spec(
d$albumin, background = zcol(zloga), align = "right"
)
d$bilirubin <- kableExtra::cell_spec(
d$bilirubin, background = zcol(zlogb), align = "right"
)
kableExtra::kable_classic(
kableExtra::kbl(
d,
col.names = c(
"Category",
"albumin", "zlog(albumin)", "bilirubin", "zlog(bilirubin)"
),
digits = 2,
escape = FALSE,
caption = paste0(
"Table reproduced from @hoffmann2017, Table 2, limits used: ",
"albumin 35-52 g/l, bilirubin 2-21 µmol/l."
)
),
"basic"
)
```
# Estimate Reference Limits
The `reference_limits` functions calculates the lower and upper 2.5 or 97.5
(or a user given probability) quantiles:
```{r reference_limits}
reference_limits(albumin)
reference_limits(albumin, probs = c(0.05, 0.95))
exp(reference_limits(log(albumin)))
```
# Working with Reference Tables
Most laboratories use their own age- and sex-specific reference limits.
The `lookup_limits` function could be used to find the correct reference limit.
```{r reference_table}
# toy example
reference <- data.frame(
param = c("albumin", rep("bilirubin", 4)),
age = c(0, 1, 2, 3, 7), # days
sex = "both",
units = c("g/l", rep("µmol/l", 4)), # ignored
lower = c(35, rep(NA, 4)), # no real reference values
upper = c(52, 5, 8, 13, 18) # no real reference values
)
knitr::kable(reference)
# lookup albumin reference values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference[reference$param == "albumin",]
)
# lookup albumin and bilirubin values for 18 year old woman
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference
)
# lookup bilirubin reference values for infants
lookup_limits(
age = 0:8,
sex = rep(c("female", "male"), 5:4),
table = reference[reference$param == "bilirubin",]
)
```
# Missing Reference Limits
Sometimes reference limits are not specified. That is often the case for
biomarkers that are related to infection or cancer. Using zero as lower
boundary results in skewed distributions [@hoffmann2017, fig. 7].
@haeckel2015 suggested to set the lower reference limit to 15 % of
the upper one.
```{r missing_reference}
# use default fractions
set_missing_limits(reference)
# set fractions manually
set_missing_limits(reference, fraction = c(0.2, 5))
```
# Impute Missing Laboratory Measurements
If laboratory measurements are missing they could be imputed using *"normal"*
values from the reference table. Using the `"logmean"` (default) or `"mean"`
reference value (default) will result in a $zlog$ or $z$-value of zero,
respectively.
```{r impute_missing_values}
x <- data.frame(
age = c(40, 50),
sex = c("female", "male"),
albumin = c(42, NA)
)
x
z_df(impute_df(x, reference, method = "mean"), reference)
zlog_df(impute_df(x, reference), reference)
```
# `PBC` Example
For demonstration we choose the `pbc` dataset from the `survival` package
and exclude all non-laboratory measurements except *age* and *sex*:
```{r pbc_load}
library("survival")
data("pbc")
labs <- c(
"bili", "chol", "albumin", "copper", "alk.phos", "ast", "trig",
"platelet", "protime"
)
pbc <- pbc[, c("age", "sex", labs)]
knitr::kable(head(pbc), digits = 1)
```
Next we estimate all reference limits from the data. We want to use sex-specific
values for copper and aspartate aminotransferase (`"ast"`).
```{r pbc_reference_limits}
## replicate copper and ast 2 times, use the others just once
param <- rep(labs, ifelse(labs %in% c("copper", "ast"), 2, 1))
sex <- rep_len("both", length(param))
## replace sex == both with female and male for copper and ast
sex[param %in% c("copper", "ast")] <- c("f", "m")
## create data.frame, we ignore age-specific values for now and set age to zero
## (means applicable for all ages)
reference <- data.frame(
param = param, age = 0, sex = sex, lower = NA, upper = NA
)
## estimate reference limits from sample data
for (i in seq_len(nrow(reference))) {
reference[i, c("lower", "upper")] <-
if (reference$sex[i] == "both")
reference_limits(pbc[reference$param[i]])
else
reference_limits(pbc[pbc$sex == reference$sex[i], reference$param[i]])
}
knitr::kable(reference)
```
The `pbc` dataset contains a few missing values. We impute the with the
corresponding mean reference value (which is in this example just the sample
mean but would be in real life the mean of a e.g. healthy subpopulation).
```{r pbc_impute}
pbc[c(6, 14),]
pbc <- impute_df(pbc, reference)
pbc[c(6, 14),]
```
Subsequently we can convert the laboratory measurements into $z(log)$-values
using the `zlog_df` function that applies the `zlog` for every `numeric` column
in a `data.frame` (except the `"age"` column):
```{r pbc_zlog}
pbc <- zlog_df(pbc, reference)
```
```{r pbc_table, echo = FALSE}
pbctbl <- head(pbc, n = 25)
pbctbl[labs] <- lapply(labs, function(l) {
kableExtra::cell_spec(
sprintf("%.1f", unlist(pbctbl[l])),
background = zcol(unlist(pbctbl[l])),
align = "right"
)
})
kableExtra::kable_classic(
kableExtra::kbl(pbctbl, digits = 1, escape = FALSE),
"basic"
)
```
# Session information
```{r si}
sessionInfo()
```
# References
| /scratch/gouwar.j/cran-all/cranData/zlog/vignettes/zlog.Rmd |
#' Return a threadbare version of a vector
#'
#' A bare object is an R object that has no class attributes (see
#' [rlang::is_bare_character()]). A threadbare object is an atomic object (i.e.
#' not a [list()], see [is.atomic()]), with no attributes at all. The function
#' returns an error if a list is passed.
#'
#' @param x A vector, possibly classed, but not a list object, to strip of all
#' attributes.
#'
#' @return A vector with the same core values as `x`, but with no [attributes()]
#' at all, not even [names()].
#'
#' @family labelled light
#' @keywords internal
threadbare <- function(x) {
is.atomic(x) || stop('x must be atomic')
attributes(x) <- NULL
x
}
#' Create a labelled variable
#'
#' @description
#'
#' The labelled_light (ll) collection is a minimal implementation of core
#' functions for creating and managing `haven_labelled` variables, and with
#' minimal dependencies. These functions, prefixed with `ll_` rely only on base
#' R, and operate only on objects of type `haven_labelled`. All functions check
#' internally that the variables have the correct class and the correct
#' structure for labelled variables, satisfying the (minimal) specification
#' inherent in the parameter documentation of the [haven::labelled()] function.
#'
#' The constructor, `ll_labelled()`, creates a labelled variable satisfying that
#' specification.
#'
#' @param x A vector to label. Must be either numeric (integer or double) or
#' character.
#' @param labels A named vector or `NULL`. The vector should be the same type
#' as `x`. Unlike factors, labels don't need to be exhaustive: only a fraction
#' of the values might be labelled.
#' @param label A short, human-readable description of the vector.
#'
#' @return A valid labelled variable.
#'
#' @family labelled light
#' @keywords internal
#' @export
ll_labelled <- function(x = double(), labels = NULL, label = NULL) {
# Construct variable
x <- as.vector(x)
class(x) <- c("haven_labelled", "vctrs_vctr", typeof(x))
attr(x, "labels") <- labels
attr(x, "label") <- label
# Check that the result is valid (an error will be thrown if not)
ll_assert_labelled(x)
# Return the result
x
}
#' Verify that x is a valid labelled variable
#'
#' Verify that x is a valid labelled variable satisfying the (minimal)
#' specification inherent in the parameter documentation of the
#' [haven::labelled()] function for `haven_labelled` objects.
#'
#' @param x A labelled variable
#' @return Invisibly returns x if the check is successful.
#'
#' @family labelled light
#' @keywords internal
#' @export
ll_assert_labelled <- function(x) {
# Retrieve attributes
labels <- attr(x, "labels", exact = TRUE)
label <- attr(x, "label", exact = TRUE)
# Perform the checks
inherits(x, "haven_labelled") ||
stop('x must be of class "haven_labelled"')
inherits(x, "vctrs_vctr") ||
stop('x must inherit from "vctrs_vctr"')
inherits(x, typeof(x)) ||
stop('x must inherit from typeof(x)')
typeof(x) %in% c("double", "integer", "character") ||
stop('x must be of type "double", "integer", or "character"')
if (!is.null(labels)) {
typeof(labels) == typeof(x) ||
stop('labels must be of same type as x')
!is.null(names(labels)) ||
stop("labels must be named")
!any(duplicated(stats::na.omit(labels))) ||
stop("labels must not contain duplicate values")
}
if (!is.null(label)) {
typeof(label) == "character" ||
stop('label must be of type "character"')
length(label) == 1 ||
stop("label must be a single string")
}
x
}
#' Get or set variable label of a labelled variable
#'
#' Gets or sets the variable label (`label` attribute) of a labelled vector. The
#' getters/setters should be used rather than manipulating attributes directly,
#' since these functions perform checks to ensure that the result, and the
#' resulting labelled variable, are valid.
#'
#' @param x A labelled variable
#'
#' @family labelled light
#' @keywords internal
#' @rdname ll_var_label
#' @export
ll_var_label <- function(x) {
ll_assert_labelled(x)
attr(x, "label", exact = TRUE)
}
#' @rdname ll_var_label
#' @export
`ll_var_label<-` <- function(x, value) {
attr(x, "label") <- value
ll_assert_labelled(x)
}
#' Get or set value labels of a labelled variable
#'
#' Gets or sets the value labels (`labels` attribute) of a labelled vector. The
#' getters/setters should be used rather than manipulating attributes directly,
#' since these functions perform checks to ensure that the result, and the
#' resulting labelled variable, are valid.
#'
#' @param x A labelled variable
#' @param always Always return at least an empty vector of the correct
#' type, even if the attribute is not set.
#'
#' @family labelled light
#' @keywords internal
#' @rdname ll_val_labels
#' @export
ll_val_labels <- function(x, always = FALSE) {
# Check args
ll_assert_labelled(x)
is.logical(always) || stop('always must be of type "logical"')
# Prepare and return the result
labels <- attr(x, "labels", exact = TRUE)
if (always && is.null(labels)) {
# Return an empty, but named, vector
labels <- vector(typeof(x))
names(labels) <- character()
}
labels
}
#' @rdname ll_val_labels
#' @export
`ll_val_labels<-` <- function(x, value) {
attr(x, "labels") <- value
ll_assert_labelled(x)
}
#' Get the character representation of a labelled variable
#'
#' @description
#' Returns a character representation of a labelled variable, using the value
#' labels to look up the label for a given value.
#'
#' The default behavior of this function is similar to
#' [labelled::to_character()]. The options, however, are slightly different.
#' Most importantly, instead of specifying `NA` handling using parameters, the
#' function relies on the `default` parameter to determine what happens for
#' unlabelled variables, allowing users to specify including the original values
#' of `x` instead of the labels, returning `NA`, or returning a specific string
#' value. Also, the default behavior is to drop any variable label attribute, in
#' line with the default [as.character()] method.
#'
#' @param x A labelled variable
#' @param default Vector providing a default label for any values not found in
#' the `val_labels` (unlabelled values). Must be of length 1 or of the same
#' length as x. Useful possibilities are `x` (use values where labels are not
#' found), `NA` (return NA for such values), and `""` (an empty string).
#' Missing (`NA`) values in `x`, however, are never replaced with the default,
#' they remain `NA`.
#' @param preserve_var_label Should any `var_label` in x be preserved, or
#' should they be dropped from the result (ensuring that the result is bare
#' and without any attributes).
#'
#' @family labelled light
#' @keywords internal
#' @export
ll_to_character <- function(x, default = x, preserve_var_label = FALSE) {
# Check args
ll_assert_labelled(x) # stops if x not valid labelled vector
is.atomic(default) || stop('default must be an atomic vector')
length(default) %in% c(1, length(x)) || stop('length(default) must be 1 or length(x)')
is.logical(preserve_var_label) || stop('preserve_var_label must be of type "logical"')
# Prepare the result, using match to look up in the labels attribute
vals <- threadbare(x)
labs <- ll_val_labels(x, always = TRUE)
ix <- match(vals, labs) # Find the values in the labels vector
result <- names(labs)[ix] # Return the names for each index
# Handle default values
if (length(default) == 1) {
result[is.na(result)] <- default
} else {
result[is.na(result)] <- default[is.na(result)]
}
result[is.na(vals)] <- NA # Missing values in x are always preserved
# Preserve (copy) variable label if specified
if (preserve_var_label) {
attr(result, "label") <- ll_var_label(x)
}
# Return the result
result
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/labelled_light.R |
#' Lookup values from a lookup table
#'
#' @description
#' The [lookup()] function implements lookup of certain strings (such as
#' variable names) from a lookup table which maps keys onto values (such as
#' variable labels or descriptions).
#'
#' The lookup table can be in the form of a two-column `data.frame`, in the form
#' of a named `vector`, or in the form of a `list`. If the table is in the form
#' of a `data.frame`, the lookup columns should be named `name` (for the key)
#' and `value` (for the value). If the lookup table is in the form of a named
#' `vector` or `list`, the name is used for the key, and the returned value is
#' taken from the values in the vector or list.
#'
#' Original values are returned if they are not found in the lookup table.
#' Alternatively, a `default` can be specified for values that are not found.
#' Note that an `NA` in x will never be found and will be replaced with the
#' default value. To specify different defaults for values that are not found
#' and for `NA` values in `x`, the `default` must be crafted manually to achieve
#' this.
#'
#' Any names in x are not included in the result.
#'
#' @param x A string vector whose elements are to be looked up.
#'
#' @param lookup_table The lookup table to use.
#'
#' @param default If a value is not found in the lookup table, the value will be
#' taken from `default`. This must be a character vector of length 1 or the
#' same length as x. Useful values include `x` (the default setting), `NA`, or
#' `""` (an empty string).
#'
#' @return The [lookup()] function returns string vector based on `x`, with
#' values replaced with the lookup values from `lookup_table`. Any values not
#' found in the lookup table are taken from `default`.
#'
#' @examples
#' fruit_lookup_vector <- c(a="Apple", b="Banana", c="Cherry")
#' lookup(letters[1:5], fruit_lookup_vector)
#' lookup(letters[1:5], fruit_lookup_vector, default = NA)
#'
#' mtcars_lookup_data_frame <- data.frame(
#' name = c("mpg", "hp", "wt"),
#' value = c("Miles/(US) gallon", "Gross horsepower", "Weight (1000 lbs)"))
#' lookup(names(mtcars), mtcars_lookup_data_frame)
#'
#' @export
lookup <- function(x, lookup_table, default = x) {
# Check args (lookup table is checked separately)
is.character(x) || is.factor(x) || stop("x must be a character or a factor")
is.character(default) || all(is.na(default)) || stop("default must be a character vector or NA")
length(default) %in% c(1, length(x)) || stop("length(default) must be 1 or length(x)")
# If x is a factor, we look up the levels of x instead of the values of x
# Note that levels of x will always be a character vector
if (is.factor(x)) {
levels(x) <- lookup(levels(x), lookup_table)
return(x)
}
# Standardize the lookup_table
lookup_table <- standardize_lookup_table(lookup_table)
# Do the lookup
result <- lookup_table[x]
names(result) <- NULL
not.found <- unlist(lapply(result, is.null))
if (length(default) == 1) {
result[not.found] <- default
} else {
result[not.found] <- default[not.found]
}
result <- unlist(result)
# Return the result
result
}
#' Construct lookup function based on a specific lookup table
#'
#' @description
#' The [lookuper()] function returns *a function* equivalent to the [lookup()]
#' function, except that instead of taking a lookup table as an argument, the
#' lookup table is embedded in the function itself.
#'
#' This can be very useful, in particular when using the lookup function as an
#' argument to other functions that expect a function which maps
#' `character`->`character` but do not offer a good way to pass additional
#' arguments to that function.
#'
#' @return The [lookuper()] function returns *a function* that takes `character`
#' vectors as its argument `x`, and returns either the corresponding values
#' from the underlying lookup table, or the original values from x for those
#' elements that are not found in the lookup table (or looks them up from the
#' `default`).
#'
#' @examples
#' lookup_fruits <- lookuper(list(a="Apple", b="Banana", c="Cherry"))
#' lookup_fruits(letters[1:5])
#'
#' @rdname lookup
#' @export
lookuper <- function(lookup_table, default = NULL) {
# Standardize the lookup_table
lookup_table <- standardize_lookup_table(lookup_table)
# Return a function suitable for lookups
if (is.null(default)) {
result <- function(x) {
lookup(x, lookup_table = lookup_table)
}
} else {
result <- function(x) {
lookup(x, lookup_table = lookup_table, default = default)
}
}
# Return result
result
}
#' Helper function to standardize the `lookup_table`.
#'
#' Preprocessing the lookup table to convert it to a list can take some time, so
#' when possible, we want to do it only once. Therefore we offload it to a
#' helper function
#'
#' @param lookup_table The unstandardized lookup table (must still be one of the
#' formats specified for the `lookup()` function).
#'
#' @return The lookup table as a list.
#'
#' @keywords internal
standardize_lookup_table <- function(lookup_table) {
# Progressively convert data.frame -> vector -> list
if (is.data.frame(lookup_table)) {
stopifnot(
"name" %in% names(lookup_table),
"value" %in% names(lookup_table)
)
attributes(lookup_table$name) <- NULL
attributes(lookup_table$value) <- NULL
lookup_table <- tibble::deframe(lookup_table[, c("name", "value")])
}
if (is.vector(lookup_table) && !is.list(lookup_table)) {
stopifnot(is.character(lookup_table))
lookup_table <- as.list(lookup_table)
}
stopifnot(is.list(lookup_table))
# Return the standardized lookup_table
lookup_table
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/lookup.R |
#' Embed factor levels and value labels in values.
#'
#' @description
#' This function adds level/label information as an annotation to either factors
#' or `labelled` variables. This function is called `notate()` rather than
#' `annotate()` to avoid conflict with `ggplot2::annotate()`. It is a generic that
#' can operate either on individual vectors or on a `data.frame`.
#'
#' When printing `labelled` variables from a `tibble` in a console, both the
#' numeric value and the text label are shown, but no variable labels. When
#' using the `View()` function, only variable labels are shown but no value
#' labels. For factors, there is no way to view the integer levels and values at
#' the same time.
#'
#' In order to allow the viewing of both variable and value labels at the same
#' time, this function converts both `factor` and `labelled` variables to
#' `character`, including both numeric levels (`labelled` values) and character
#' values (`labelled` labels) in the output.
#'
#' @param x The object (either vector or `date.frame` of vectors), that one
#' desires to annotate and/or view.
#'
#' @return The processed `data.frame`, suitable for viewing, in particular
#' through the `View()` function.
#'
#' @examples
#' d <- data.frame(
#' chr = letters[1:4],
#' fct = factor(c("alpha", "bravo", "chrly", "delta")),
#' lbl = ll_labelled(c(1, 2, 3, NA),
#' labels = c(one=1, two=2),
#' label = "A labelled vector")
#' )
#' dn <- notate(d)
#' dn
#' # View(dn)
#'
#' @export
notate <- function(x) {
UseMethod("notate")
}
#' @export
notate.default <- function(x) {
type_short <- typeof(x) |> lookup_types_short()
attr(x, "label") <- paste_na(
paste0("<", type_short, ">"),
attr(x, "label"))
x
}
#' @export
notate.data.frame <- function(x) {
# Apply to individual columns
ddply_helper(x, notate)
}
#' @export
notate.factor <- function(x) {
is.factor(x) || stop("x must be a factor")
r <- rep(c(character(0), NA), length(x))
r[!is.na(x)] <- paste0("[", as.numeric(x[!is.na(x)]), "] ", as.character(x[!is.na(x)]))
attr(r, "label") <- paste_na("<fct>", attr(x, "label")) # (ll_var_label() requires correct class)
r
}
#' @export
notate.haven_labelled <- function(x) {
ll_assert_labelled(x)
vals <- as.vector(x)
labs_n <- ll_to_character(x, default = NA)
r <- rep(c(character(0), NA), length(x))
r[!is.na(x)] <- paste_na(
paste0("[", vals[!is.na(x)], "]"),
labs_n[!is.na(x)])
attr(r, "label") <- paste_na("<lbl>", ll_var_label(x)) # (ll_var_label() requires correct class)
r
}
# Helper to look up the short types given typeof()
lookup_types_short <- lookuper(
c(logical = "lgl", integer = "int", double = "dbl",
character = "chr", complex = "cpl"))
# Helper to suppress NAs in paste
# https://stackoverflow.com/questions/13673894/suppress-nas-in-paste
paste_na <- function(..., sep = " ") {
values <- cbind(...)
apply(values, 1, function(x) paste(x[!is.na(x)], collapse = sep))
}
# paste_na(c(1,1), c(2, NA))
# paste_na(c(1,1), c(2, NA), 4:5)
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/notate.R |
#' Sample from a vector in a safe way
#'
#' @description
#' The [zample()] function duplicates the functionality of [sample()], with the
#' exception that it does not attempt the (sometimes dangerous)
#' user-friendliness of switching the interpretation of the first element to a
#' number if the length of the vector is 1. `zample()` *always* treats its first
#' argument as a vector containing elements that should be sampled, so your code
#' won't break in unexpected ways when the input vector happens to be of length
#' 1.
#'
#' @details
#' If what you really want is to sample from an interval between 1 and n, you can
#' use `sample(n)` or `sample.int(n)` (but make sure to only pass vectors of
#' length one to those functions).
#'
#' @param x The vector to sample from
#' @param size The number of elements to sample from `x` (defaults to `length(x)`)
#' @param replace Should elements be replaced after sampling (defaults to `false`)
#' @param prob A vector of probability weights (defaults to equal probabilities)
#'
#' @return The resulting sample
#'
#' @examples
#' # For vectors of length 2 or more, zample() and sample() are identical
#' set.seed(42); zample(7:11)
#' set.seed(42); sample(7:11)
#'
#' # For vectors of length 1, zample() will still sample from the vector,
#' # whereas sample() will "magically" switch to interpreting the input
#' # as a number n, and sampling from the vector 1:n.
#' set.seed(42); zample(7)
#' set.seed(42); sample(7)
#'
#' # The other arguments work in the same way as for sample()
#' set.seed(42); zample(7:11, size=13, replace=TRUE, prob=(5:1)^3)
#' set.seed(42); sample(7:11, size=13, replace=TRUE, prob=(5:1)^3)
#'
#' # Of course, sampling more than the available elements without
#' # setting replace=TRUE will result in an error
#' set.seed(42); tryCatch(zample(7, size=2), error=wrap_error)
#'
#' @export
zample = function (x, size=length(x), replace = FALSE, prob = NULL)
{
# Bail out of sampling from data.frames, use dplyr::sample_X() for that
if (inherits(x, "data.frame"))
{
stop("zulutils::zample() does not support data.frames")
}
# Sampling zero elements from a zero length vector should be allowed
if ( size==0 & length(x)==0 ) { return(vector(mode=mode(x))) }
# The code from original sample(), minus the silly numeric handling
x[sample.int(length(x), size, replace, prob)]
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/zample.R |
#' Generate sequence in a safe way
#'
#' @description
#' The [zeq()] function creates an increasing integer sequence, but differs from
#' the standard one in that it will not silently generate a decreasing sequence
#' when the second argument is smaller than the first. If the second argument is
#' one smaller than the first it will generate an empty sequence, if the
#' difference is greater, the function will throw an error.
#'
#' @param from The lower bound of the sequence
#' @param to The higher bound of the sequence
#'
#' @return A sequence ranging from `from` to `to`
#'
#' @examples
#' # For increasing sequences, zeq() and seq() are identical
#' zeq(11,15)
#' zeq(11,11)
#'
#' # If second argument equals first-1, an empty sequence is returned
#' zeq(11,10)
#'
#' # If second argument is less than first-1, the function throws an error
#' tryCatch(zeq(11,9), error=wrap_error)
#'
#' @export
zeq = function(from, to)
{
stopifnot ( round(from) == from )
stopifnot ( round(to) == to )
stopifnot ( to >= from - 1 )
return (seq_len(1+to-from)+from-1)
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/zeq.R |
#' Return the single (unique) value found in a vector
#'
#' @description
#' The [zingle()] function returns the first element in a vector, but only if
#' all the other elements are identical to the first one (the vector only has a
#' `zingle` value). If the elements are not all identical, it throws an error.
#' The vector must contain at least one non-`NA` value, or the function errors
#' out as well. This is especially useful in aggregations, when all values in a
#' given group should be identical, but you want to make sure.
#'
#' @details
#' Optionally takes a `na.rm` parameter, similarly to sum, mean and other
#' aggregate functions. If `TRUE`, `NA` values will be removed prior to
#' comparing the elements, so the function will accept input values that contain
#' a combination of the single value and any `NA` values (but at least one
#' non-`NA` value is required).
#'
#' Only values are tested for equality. Any names are simply ignored, and the
#' result is an unnamed value. This is in line with how other aggregation
#' functions handle names.
#'
#' @param x Vector of elements that should all be identical
#' @param na.rm Should `NA` elements be removed prior to comparison
#' @return The `zingle` element in the vector
#'
#' @examples
#' # If all elements are identical, all is good.
#' # The value of the element is returned.
#' zingle(c("Alpha", "Alpha", "Alpha"))
#'
#' # If any elements differ, an error is thrown
#' tryCatch(zingle(c("Alpha", "Beta", "Alpha")), error=wrap_error)
#'
#' if (require("dplyr", quietly=TRUE, warn.conflicts=FALSE)) {
#' d <- tibble::tribble(
#' ~id, ~name, ~fouls,
#' 1, "James", 3,
#' 2, "Jack", 2,
#' 1, "James", 4
#' )
#'
#' # If the data is of the correct format, all is good
#' d %>%
#' dplyr::group_by(id) %>%
#' dplyr::summarise(name=zingle(name), total_fouls=sum(fouls))
#' }
#'
#' if (require("dplyr", quietly=TRUE, warn.conflicts=FALSE)) {
#' # If a name does not match its ID, we should get an error
#' d[1,"name"] <- "Jammes"
#' tryCatch({
#' d %>%
#' dplyr::group_by(id) %>%
#' dplyr::summarise(name=zingle(name), total_fouls=sum(fouls))
#' }, error=wrap_error)
#' }
#
#' @export
zingle = function(x, na.rm = FALSE)
{
if (na.rm) x = x[!is.na(x)]
stopifnot(all(x[1]==x))
unname(x[1])
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/zingle.R |
# The package documentation uses desc::desc_get() to get the description,
# instead of relying on autogenerated description. This is done in order to get
# markdown parsing and facilitate adding extra text to the package doc in
# addition to the text from the DESCRIPTION file.
#' @description
#' `r desc::desc_get("Description")`
#'
#' For more information, see vignette("zmisc").
#'
#' @docType package
#' @name zmisc
#' @keywords internal
"_PACKAGE"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
## usethis namespace: end
NULL
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/zmisc-package.R |
#' Utility function to output an error
#'
#' This function is used to capture errors, typically inside a `tryCatch()`
#' statement and output them in a clean and readable way. The function provides
#' line-wrapping, with a configurable width. When printing the error message, it
#' prefixes the text with "`#E> `" to make it easier to look for the error.
#'
#' @param e The error to wrap.
#' @param wrap How many characters per line before wrapping.
#'
#' @return The original error is returned invisibly.
#'
#' @examples
#' tryCatch(stop("This is an error"), error=wrap_error)
#'
#' @keywords internal
#' @export
wrap_error <- function(e, wrap=50) {
cat( paste0("#E> ", strwrap(e$message, width=50), "\n"), sep="" )
invisible(e)
}
#' Apply a function to each column of a data.frame
#'
#' Thin wrapper around `lapply()` that checks that the input is a table before
#' applying the function to each column, and converts the result back to a table
#' afterwards. If the `tibble` package is available and the input is a `tibble`,
#' the result will be a `tibble`; otherwise, it will be a plain `data.frame`.
#'
#' @param d A `data.frame` or `tibble`.
#' @param fun A function to apply to each column of `d`.
#'
#' @return A `data.frame` or `tibble` with the function applied to each column.
#'
#' @examples
#' df <- data.frame(
#' col1 = c(1, 2, 3),
#' col2 = c(4, 5, 6)
#' )
#' sum_fun <- function(x) sum(x)
#' result <- ddply_helper(df, sum_fun)
#' print(result)
#'
#' @keywords internal
#' @export
ddply_helper <- function(d, fun) {
# Check args
is.data.frame(d) || stop("d must be a data.frame")
# Apply the function
result <- lapply(d, fun)
# Convert result to a table
if (inherits(d, "tbl_df") && requireNamespace("tibble", quietly = TRUE)) {
# Convert to tibble if input is a tibble and tibble package is available
result <- tibble::as_tibble(result)
} else {
# Else convert to a plain data.frame
result <- as.data.frame(result)
}
# Return the result
result
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/R/zmisc-utils.R |
# This script manages the development build process for zmisc.
# The starting point is a clean checkout, typically from Github:
# > git clone https://github.com/torfason/zmisc
## Build package and basic documentation (before commits)
{
devtools::document()
devtools::build()
devtools::build_readme()
devtools::test()
message("Build OK")
}
## Build vignettes and site
{
devtools::build_vignettes()
devtools::build_manual()
devtools::build_site()
}
## Final checks (before release)
{
system("R CMD INSTALL --preclean --no-multiarch --with-keep.source .")
devtools::spell_check()
devtools::check()
devtools::release_checks()
devtools:::git_checks()
}
## Remote checks (commented out, copy to terminal and run manually)
# devtools::check_rhub()
# devtools::check_win_devel()
## Finally submit to cran (commented out, copy to terminal and run manually)
# devtools::release()
## There should be no need to run the following cleanup tasks
# devtools::clean_vignettes()
# pkgdown::clean_site()
| /scratch/gouwar.j/cran-all/cranData/zmisc/build/build_and_release_process.R |
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
# We need rprojroot to locate other files needed for the Vignette
library(rprojroot)
# Source a few helper/utility functions
source(find_package_root_file("vignettes","utils_knitr.R"))
source(find_package_root_file("vignettes","utils_roxygen.R"))
# Get roxygen blocks, use force to trigger any warnings immediately
blocks <- roxy_get_blocks(find_package_root_file())
blocks <- force(blocks)
## ----load_package-------------------------------------------------------------
library(zmisc)
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "lookup", "examples") |> kat_code()
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "lookuper", "examples") |> kat_code()
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "zample", "examples") |> kat_code()
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "zeq", "examples") |> kat_code()
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "zingle", "examples") |> kat_code()
## ---- echo=FALSE--------------------------------------------------------------
roxy_get_section(blocks, "notate", "examples") |> kat_code()
| /scratch/gouwar.j/cran-all/cranData/zmisc/inst/doc/zmisc.R |
---
title: "zmisc"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zmisc}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
# We need rprojroot to locate other files needed for the Vignette
library(rprojroot)
# Source a few helper/utility functions
source(find_package_root_file("vignettes","utils_knitr.R"))
source(find_package_root_file("vignettes","utils_roxygen.R"))
# Get roxygen blocks, use force to trigger any warnings immediately
blocks <- roxy_get_blocks(find_package_root_file())
blocks <- force(blocks)
```
## `r desc::desc_get("Title")`
`r desc::desc_get("Description")`
## Installation
You can install the released version of `zmisc` from [CRAN](https://cran.r-project.org/package=zmisc) with:
```r
install.packages("zmisc")
```
You can use `pak` to install the development version of `zmisc` from [GitHub](https://github.com/torfason/zmisc) with:
```r
pak::pak("torfason/zmisc")
```
## Usage
In order to use the package, you generally want to attach it first:
```{r load_package}
library(zmisc)
```
## Quick and easy value lookups
The functions [lookup()] and [lookuper()] are used to look up values from a lookup
table, which can be supplied as a `vector`, a `list`, or a `data.frame`. The functions
are in some ways similar to the Excel function `VLOOKUP()`, but are designed to work smoothly
in an R workflow, in particular within pipes.
### lookup: `r roxy_get_section(blocks, "lookup", "title")`
`r roxy_get_section(blocks, "lookup", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "lookup", "examples") |> kat_code()
```
### lookuper: `r roxy_get_section(blocks, "lookuper", "title")`
`r roxy_get_section(blocks, "lookuper", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "lookuper", "examples") |> kat_code()
```
## Safer sampling, sequencing and aggregation
The functions [zample()], [zeq()], and [zingle()] are intended to make your code
less likely to break in mysterious ways when you encounter unexpected boundary
conditions. The [zample()] and [zeq()] are almost identical to the [sample()]
and [seq()] functions, but a bit safer.
### zample: `r roxy_get_section(blocks, "zample", "title")`
`r roxy_get_section(blocks, "zample", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zample", "examples") |> kat_code()
```
### zeq: `r roxy_get_section(blocks, "zeq", "title")`
`r roxy_get_section(blocks, "zeq", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zeq", "examples") |> kat_code()
```
### zingle: `r roxy_get_section(blocks, "zingle", "title")`
`r roxy_get_section(blocks, "zingle", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zingle", "examples") |> kat_code()
```
## Getting a better view on variables
The [notate()] function adds annotations to `factor` and `labelled` variables
that make it easier to see both values and labels/levels when using the [View()]
function
### notate: `r roxy_get_section(blocks, "notate", "title")`
`r roxy_get_section(blocks, "notate", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "notate", "examples") |> kat_code()
```
[lookup()]: https://torfason.github.io/zmisc/reference/lookup.html
[lookuper()]: https://torfason.github.io/zmisc/reference/lookuper.html
[zeq()]: https://torfason.github.io/zmisc/reference/zeq.html
[zample()]: https://torfason.github.io/zmisc/reference/zample.html
[zingle()]: https://torfason.github.io/zmisc/reference/zingle.html
[notate()]: https://torfason.github.io/zmisc/reference/zingle.html
[seq()]: https://rdrr.io/r/base/seq.html
[sample()]: https://rdrr.io/r/base/sample.html
[View()]: https://rdrr.io/r/utils/View.html
| /scratch/gouwar.j/cran-all/cranData/zmisc/inst/doc/zmisc.Rmd |
#' ---
#' output: reprex::reprex_document
#' ---
# Parse source code to get roxygen block objects
#
# This function is based on roxygenise, but omits the parts that have side
# effects - that is the parts that affect the enviroment and that output
# documentation files.
roxy_get_blocks <- function (package.dir = ".") {
load_code <- NULL
clean <- FALSE
base_path <- normalizePath(package.dir, mustWork = TRUE)
encoding <- desc::desc_get("Encoding", file = base_path)[[1]]
if (!identical(encoding, "UTF-8")) {
warning("roxygen2 requires Encoding: UTF-8", call. = FALSE)
}
roxygen2:::roxy_meta_load(base_path)
packages <- roxygen2:::roxy_meta_get("packages")
lapply(packages, loadNamespace)
load_code <- roxygen2:::find_load_strategy(load_code)
env <- load_code(base_path)
blocks <- roxygen2:::parse_package(base_path, env = NULL)
blocks <- lapply(blocks, roxygen2:::block_set_env, env = env)
blocks
}
# Extract a documentation section from roxy blocks object
#
# This function takes a roxygen blocks structure, which typically is created by
# calling roxy_get_blocks(), and extracts the content for a particular topic
# (usually a function name) and tag (such as @title/@description/@examples).
#
# The main use case is to include the result in custom documentation files. The
# result is returned in the form of a character vector, which contains any
# formating as it is written in the source file. Thus, if the intention is to
# use the result in an .Rmd file, the roxydoc documentation should be formatted
# using markdown (and the @md tag should therefore be included)
#
# @param blocks A roxy blocks structure (list)
# @param name_topic The name of the topic (usually a function name)
# @param name_tag The name of the tag/section (@title/@description/@examples)
roxy_get_section <- function(blocks, name_topic, name_tag) {
# Better to work with unclassed structure
b <- blocks |> rapply(unclass, how="list")
# Get the list of all topics (function names) that are
# documented in the package, and assign as names to b
topics <- b |>
lapply('[[', 'object') |>
lapply('[[', 'topic') |>
unlist()
names(b) <- topics
# Get the substructure for the current topic, extract
# all its tags, and assign as names to the structure
b.cur_topic <- b[[name_topic]]$tags
cur_topic_tags <- b.cur_topic |>
lapply('[[', 'tag') |>
unlist()
names(b.cur_topic) <- cur_topic_tags
# What we are interested in is the 'raw' field in
# of the focal tag of the topic
result <- b.cur_topic[[name_tag]]$raw
# Return the result, trimming whitespace at start/end
stringr::str_trim(result)
}
blocks <- roxy_get_blocks(rprojroot::find_package_root_file())
blocks <- force(blocks)
roxy_get_section(blocks, "lookup", "title")
| /scratch/gouwar.j/cran-all/cranData/zmisc/vignettes/REPREX_reprex.R |
# Simple way to output code as-is to knitr
kat <- knitr::asis_output
# Function to wrap example code between ``` before katting
kat_code <- function(code, language="r") {
result <- c(
paste0("```",language, "\n"),
code,
"\n```")
kat(result)
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/vignettes/utils_knitr.R |
#### .Rd file parsing ####
# Utility function to extract title from Rd file
#
# The function could theoretically return most fields from the Rd file, but any
# formatting will be included, making other fields than "title" of little use,
# so this is currently the only supported field.
#
# In most cases, it is better to use the roxy_* functions which use roxygen to
# extract fields (tags) directly from the source files.
rd_get <- function(function_name, section) {
stopifnot(section %in% c("title", "description", "examples"))
rd <- find_package_root_file("man", paste0(function_name,".Rd")) |>
tools::parse_Rd()
rd_tags <- tools:::RdTags(rd)
rd_section <- rd[[which(rd_tags == paste0("\\", section))]] |> unlist()
rd_section
}
#### Roxygen parsing ####
# Parse source code to get roxygen block objects
#
# This function is based on roxygenise, but opits the parts that have side
# effects - that is the parts that affect the enviroment and that output
# documentation files.
roxy_get_blocks <- function (package.dir = ".") {
load_code <- NULL
clean <- FALSE
base_path <- normalizePath(package.dir, mustWork = TRUE)
encoding <- desc::desc_get("Encoding", file = base_path)[[1]]
if (!identical(encoding, "UTF-8")) {
warning("roxygen2 requires Encoding: UTF-8", call. = FALSE)
}
roxygen2:::roxy_meta_load(base_path)
packages <- roxygen2:::roxy_meta_get("packages")
lapply(packages, loadNamespace)
load_code <- roxygen2:::find_load_strategy(load_code)
env <- load_code(base_path)
blocks <- roxygen2:::parse_package(base_path, env = NULL)
blocks <- lapply(blocks, roxygen2:::block_set_env, env = env)
blocks
}
# Extract a documentation section from roxy blocks object
#
# This function takes a roxygen blocks structure, which typically is created by
# calling roxy_get_blocks(), and extracts the content for a particular topic
# (usually a function name) and tag (such as @title/@description/@examples).
#
# The main use case is to include the result in custom documentation files. The
# result is returned in the form of a character vector, which contains any
# formating as it is written in the source file. Thus, if the intention is to
# use the result in an .Rmd file, the roxydoc documentation should be formatted
# using markdown (and the @md tag should therefore be included)
#
# @param blocks A roxy blocks structure (list)
# @param name_topic The name of the topic (usually a function name)
# @param name_tag The name of the tag/section (@title/@description/@examples)
roxy_get_section <- function(blocks, name_topic, name_tag) {
# Do not unclass, because that fails with roxygen2 v7.1.3 onward
b <- blocks # |> rapply(unclass, how="list")
# Get the list of all topics (function names) that are
# documented in the package, and assign as names to b
topics <- b |>
lapply('[[', 'object') |>
lapply('[[', 'topic') |>
unlist()
names(b) <- topics
# Get the substructure for the current topic, extract
# all its tags, and assign as names to the structure
b.cur_topic <- b[[name_topic]]$tags
cur_topic_tags <- b.cur_topic |>
lapply('[[', 'tag') |>
unlist()
names(b.cur_topic) <- cur_topic_tags
# What we are interested in is the 'raw' field in
# of the focal tag of the topic
result <- b.cur_topic[[name_tag]]$raw
# Return the result, trimming whitespace at start/end
stringr::str_trim(result)
}
| /scratch/gouwar.j/cran-all/cranData/zmisc/vignettes/utils_roxygen.R |
---
title: "zmisc"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zmisc}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
# We need rprojroot to locate other files needed for the Vignette
library(rprojroot)
# Source a few helper/utility functions
source(find_package_root_file("vignettes","utils_knitr.R"))
source(find_package_root_file("vignettes","utils_roxygen.R"))
# Get roxygen blocks, use force to trigger any warnings immediately
blocks <- roxy_get_blocks(find_package_root_file())
blocks <- force(blocks)
```
## `r desc::desc_get("Title")`
`r desc::desc_get("Description")`
## Installation
You can install the released version of `zmisc` from [CRAN](https://cran.r-project.org/package=zmisc) with:
```r
install.packages("zmisc")
```
You can use `pak` to install the development version of `zmisc` from [GitHub](https://github.com/torfason/zmisc) with:
```r
pak::pak("torfason/zmisc")
```
## Usage
In order to use the package, you generally want to attach it first:
```{r load_package}
library(zmisc)
```
## Quick and easy value lookups
The functions [lookup()] and [lookuper()] are used to look up values from a lookup
table, which can be supplied as a `vector`, a `list`, or a `data.frame`. The functions
are in some ways similar to the Excel function `VLOOKUP()`, but are designed to work smoothly
in an R workflow, in particular within pipes.
### lookup: `r roxy_get_section(blocks, "lookup", "title")`
`r roxy_get_section(blocks, "lookup", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "lookup", "examples") |> kat_code()
```
### lookuper: `r roxy_get_section(blocks, "lookuper", "title")`
`r roxy_get_section(blocks, "lookuper", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "lookuper", "examples") |> kat_code()
```
## Safer sampling, sequencing and aggregation
The functions [zample()], [zeq()], and [zingle()] are intended to make your code
less likely to break in mysterious ways when you encounter unexpected boundary
conditions. The [zample()] and [zeq()] are almost identical to the [sample()]
and [seq()] functions, but a bit safer.
### zample: `r roxy_get_section(blocks, "zample", "title")`
`r roxy_get_section(blocks, "zample", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zample", "examples") |> kat_code()
```
### zeq: `r roxy_get_section(blocks, "zeq", "title")`
`r roxy_get_section(blocks, "zeq", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zeq", "examples") |> kat_code()
```
### zingle: `r roxy_get_section(blocks, "zingle", "title")`
`r roxy_get_section(blocks, "zingle", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "zingle", "examples") |> kat_code()
```
## Getting a better view on variables
The [notate()] function adds annotations to `factor` and `labelled` variables
that make it easier to see both values and labels/levels when using the [View()]
function
### notate: `r roxy_get_section(blocks, "notate", "title")`
`r roxy_get_section(blocks, "notate", "description")`
#### Examples
```{r, echo=FALSE}
roxy_get_section(blocks, "notate", "examples") |> kat_code()
```
[lookup()]: https://torfason.github.io/zmisc/reference/lookup.html
[lookuper()]: https://torfason.github.io/zmisc/reference/lookuper.html
[zeq()]: https://torfason.github.io/zmisc/reference/zeq.html
[zample()]: https://torfason.github.io/zmisc/reference/zample.html
[zingle()]: https://torfason.github.io/zmisc/reference/zingle.html
[notate()]: https://torfason.github.io/zmisc/reference/zingle.html
[seq()]: https://rdrr.io/r/base/seq.html
[sample()]: https://rdrr.io/r/base/sample.html
[View()]: https://rdrr.io/r/utils/View.html
| /scratch/gouwar.j/cran-all/cranData/zmisc/vignettes/zmisc.Rmd |
`piczoeppritz` <-
function(LL=list(x=c(0,1), y=c(0,1)) , chincw="P")
{
if(missing(LL)) { LL = locator(2) }
if(missing(chincw)) { chincw="P" }
zoepcols = c("red", "green" , "blue", "purple")
mx = mean(LL$x)
my = mean( LL$y)
rect(LL$x[1], LL$y[1], LL$x[2], LL$y[2], col=NULL, border=grey(0.85) )
segments(LL$x[1], my , LL$x[2], my, lty=2 )
segments(mx, LL$y[1], mx, LL$y[2], lty=2 )
arrows(LL$x[1]+0.25*(diff(LL$x)) , LL$y[2], mx, my, length = 0.1 )
text(LL$x[1]+0.25*(diff(LL$x)) , LL$y[2], labels=chincw, pos=3)
arrows(mx, my, LL$x[1]+0.65*(diff(LL$x)), LL$y[2], length = 0.1, col=zoepcols[2])
arrows(mx, my, LL$x[1]+0.85*(diff(LL$x)), LL$y[2], length = 0.1, col=zoepcols[1])
text( LL$x[1]+0.65*(diff(LL$x)), LL$y[2] , labels="S", pos=3, col=zoepcols[2])
text( LL$x[1]+0.85*(diff(LL$x)), LL$y[2] , labels="P", pos=3, col=zoepcols[1])
arrows(mx, my, LL$x[1]+0.65*(diff(LL$x)), LL$y[1], length = 0.1, col=zoepcols[4])
arrows(mx, my, LL$x[1]+0.85*(diff(LL$x)), LL$y[1], length = 0.1, col=zoepcols[3])
text(LL$x[1]+0.65*(diff(LL$x)), LL$y[1], labels="S", pos=1, col=zoepcols[4])
text( LL$x[1]+0.85*(diff(LL$x)), LL$y[1], labels="P", pos=1, col=zoepcols[3])
}
| /scratch/gouwar.j/cran-all/cranData/zoeppritz/R/piczoeppritz.R |
`plotzoeppritz` <-
function(A, zoepcols = c("red", "green" , "blue", "purple"), zoeplty=c(1,1,1,1) )
{
if(missing(zoepcols) ) zoepcols = c("red", "green" , "blue", "purple")
if(missing(zoeplty) ) zoeplty=c(1,1,1,1)
######### A = list(angle=angle, rmat=rmat, rra=rra, ria=ria, ang=ang, input.model)
plot(range(A$angle), range(A$rmat, na.rm=TRUE), col=4, type="n", xlab="Angle of Incidence",
ylab=A$chtype ) ;
u = par("usr")
A$rmat[ A$rmat==0.0 ] = NA
for(i in 1:length(A$rmat[1,]))
{
lines(A$angle, A$rmat[,i], col=zoepcols[i], lty=zoeplty[i])
}
if(!is.null(A$alphacrit)) { abline(v=A$alphacrit, lty=2, col=grey(.75) ) }
## title(paste(sep="", chincw, " Incident/", choutkind, " Out" ) );
## text(0 , 1.15, paste('Layer 1: Vp=',alpha1,' Vs=',beta1, ' Rho=', rho1), pos=4)
## text(0, 1.05, paste('Layer 2: Vp=',alpha2,' Vs=',beta2, ' Rho=', rho2), pos=4)
## legend("topleft", legend=c(paste(sep=" ", "Incident:", A$incw),
## paste('Layer 1:', bquote(alpha[1]), '=',alpha1, bquote(beta[1]), '=',beta1, bquote(rho[1]), '=', rho1),
## paste('Layer 2: Vp=',alpha2,' Vs=',beta2, ' Rho=', rho2)))
alpha1 = A$input.model$vp1
alpha2 = A$input.model$vp2
beta1 = A$input.model$vs1
beta2 = A$input.model$vs2
rho1 = A$input.model$rho1
rho2 = A$input.model$rho2
leg1 = bquote(alpha[1] == .(alpha1))
vskip = strheight(leg1, units = "user", cex = 1)*1.4
text(u[1], u[4] -vskip, leg1, pos=4)
leg1 = bquote(beta[1] == .(beta1))
text(u[1], u[4] -2*vskip, leg1, pos=4)
leg1 = bquote(rho[1] == .(rho1))
text(u[1], u[4] -3*vskip, leg1, pos=4)
leg1 = bquote(alpha[2] == .(alpha2))
text(u[1], u[4] -4*vskip, leg1, pos=4)
leg1 = bquote(beta[2] == .(beta2))
text(u[1], u[4] -5*vskip, leg1, pos=4)
leg1 = bquote(rho[2] == .(rho2))
text(u[1], u[4] -6*vskip, leg1, pos=4)
legend("topright", legend=c("P-reflected", "S-reflected", "P-refracted", "S-refracted"), lty=zoeplty, lwd=2, col=zoepcols)
}
| /scratch/gouwar.j/cran-all/cranData/zoeppritz/R/plotzoeppritz.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.