content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
ggFactorPlot <- function(v, partial, band, rug, w, strip.names, overlay, top, line.par, fill.par, points.par, ...) {
if ("by" %in% names(v$meta)) {
if (is.factor(v$fit[, v$meta$by])) {
lev <- levels(v$fit[, v$meta$by])
b <- vrb <- factor(lev, levels=lev)
z <- vrz <- v$res[, v$meta$by]
} else {
lev <- abbrNum(v$fit[, v$meta$by])
b <- factor(lev, levels=lev)
vrz <- v$res[, v$meta$by]
vrb <- unique(vrz)
}
J <- length(b)
if (overlay) {
facet <- FALSE
} else {
facet <- TRUE
}
} else {
J <- 1
facet <- FALSE
}
K <- length(levels(v$fit[, v$meta$x]))
len <- K*(1-w)+(K-1)*w
# Initialize gg object and aesthetic defaults
fillData <- lineData <- pointData <- NULL
df0 <- data.frame(visregFit = c(v$fit$visregFit, v$fit$visregFit))
df0$visregGGX <- rep(0:1, each=nrow(v$fit))
df0$visregGGY <- rep(v$fit$visregFit, 2)
dots <- list(...)
xlab <- if ("xlab" %in% names(dots)) dots$xlab else v$meta$x
if ("ylab" %in% names(dots)) {
ylab <- dots$ylab
} else {
ylab <- if (is.null(v$meta$yName)) paste("f(", v$meta$x, ")", sep="") else v$meta$yName
}
if ("by" %in% names(v$meta) & overlay){
p <- ggplot2::ggplot(df0, ggplot2::aes_string('visregGGX', 'visregGGY', group = v$meta$by))
fill.args <- list(mapping=ggplot2::aes_string(fill=v$meta$by))
line.args <- list(mapping=ggplot2::aes_string(color=v$meta$by), size=1)
point.args <- list(mapping=ggplot2::aes_string(color=v$meta$by), size=0.8)
col <- pal(length(lev))
acol <- pal(length(lev), alpha=0.3)
aacol <- pal(length(lev), alpha=0.3/K)
if (length(fill.par)) fill.args[names(fill.par)] <- fill.par
if (length(line.par)) line.args[names(line.par)] <- line.par
if (length(points.par)) point.args[names(points.par)] <- points.par
p <- p + ggplot2::scale_fill_manual(values=acol) +
ggplot2::scale_color_manual(values=col) +
ggplot2::guides(fill=ggplot2::guide_legend(override.aes = list(fill=aacol)))
} else {
p <- ggplot2::ggplot(pointData, ggplot2::aes_string('visregGGX', 'visregGGY'))
fill.args <- list(fill="gray85")
line.args <- list(size=1, col="#008DFFFF")
point.args <- list(size=0.8, col="gray50")
if (length(fill.par)) fill.args[names(fill.par)] <- fill.par
if (length(line.par)) line.args[names(line.par)] <- line.par
if (length(points.par)) point.args[names(points.par)] <- points.par
}
p <- p + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) +
ggplot2::scale_x_continuous(breaks=(0:(K-1))/len+(1-w)/(2*len), labels = levels(v$fit[, v$meta$x]))
# Bands
if (band) {
for(k in 1:K) {
x1 <- (k-1)/len
x2 <- (k-1)/len + (1-w)/len
xx <- c(x1, x2, x2, x1)
fillData <- data.frame(visregGGX = rep(xx, J),
visregGGY = as.double(apply(v$fit[(1:J-1)*K + k, c("visregLwr", "visregUpr")], 1, function(x) rep(x, each=2))))
if ("by" %in% names(v$meta)) {
fillData$visregGGZ <- rep(b, each=4)
names(fillData)[3] <- v$meta$by
}
fill.args$data <- fillData
p <- p + do.call("geom_polygon", fill.args, envir=asNamespace("ggplot2"))
}
}
# Plot points
for (j in 1:J) {
for (k in 1:K) {
x1 <- (k-1)/len
x2 <- (k-1)/len + (1-w)/len
xx <- c(x1, x2)
x <- v$res[, v$meta$x]
df <- NULL
if ("by" %in% names(v$meta)) {
ind <- (x==levels(x)[k]) & (vrz==vrb[j])
if (any(ind)) {
rx <- seq(x1, x2, len=sum(ind)+2)[c(-1,-(sum(ind)+2))]
df <- data.frame(visregGGX = rx,
visregGGY = v$res$visregRes[ind],
visregGGZ = b[j],
visregGGP = v$res$visregPos[ind])
}
} else {
ind <- (x==levels(x)[k])
if (any(ind)) {
rx <- seq(x1, x2, len=sum(ind)+2)[c(-1,-(sum(ind)+2))]
df <- data.frame(visregGGX = rx,
visregGGY = v$res$visregRes[ind],
visregGGP = v$res$visregPos[ind])
}
}
pointData <- rbind(pointData, df)
}
}
if ("by" %in% names(v$meta)) names(pointData)[3] <- v$meta$by
if (!partial) {
p <- ggfp_lines(p, K, len, w, xx, J, v, b, line.args)
} else {
point.args$data <- pointData
if (top == 'line') {
p <- p + do.call("geom_point", point.args, envir=asNamespace("ggplot2"))
p <- ggfp_lines(p, K, len, w, xx, J, v, b, line.args)
} else {
p <- ggfp_lines(p, K, len, w, xx, J, v, b, line.args)
p <- p + do.call("geom_point", point.args, envir=asNamespace("ggplot2"))
}
}
# Rug
if (rug==1) {
rug.args <- point.args
rug.args$sides <- 'b'
p <- p + do.call("geom_rug", point.args, envir=asNamespace("ggplot2"))
}
if (rug==2) {
top.args <- bot.args <- point.args
top.args$sides <- 't'
bot.args$sides <- 'b'
top.args$data <- pointData[v$res$visregPos,]
bot.args$data <- pointData[!v$res$visregPos,]
p <- p + do.call("geom_rug", top.args, envir=asNamespace("ggplot2"))
p <- p + do.call("geom_rug", bot.args, envir=asNamespace("ggplot2"))
}
# Facet
if (facet) {
form <- as.formula(paste("~", v$meta$by))
if (identical(strip.names, TRUE)) {
p <- p + ggplot2::facet_grid(form, labeller=ggplot2::label_both)
} else if (identical(strip.names, FALSE)) {
p <- p + ggplot2::facet_grid(form)
} else if (is.character(strip.names) & length(strip.names) == J) {
names(strip.names) <- levels(b)
args <- list(strip.names)
names(args) <- v$meta$by
lbl <- do.call(ggplot2::labeller, args)
p <- p + ggplot2::facet_grid(form, labeller=lbl)
} else {
stop('strip.names must either be logical or a character vector with length equal to the number of facets', call.=FALSE)
}
}
p
}
ggfp_lines <- function(p, K, len, w, xx, J, v, b, line.args) {
for(k in 1:K) {
x1 <- (k-1)/len
x2 <- (k-1)/len + (1-w)/len
xx <- c(x1, x2)
lineData <- data.frame(visregGGX = rep(xx, J),
visregGGY = rep(v$fit$visregFit[(1:J-1)*K + k], each=2))
if ("by" %in% names(v$meta)) {
lineData$visregGGZ <- rep(b, each=2)
names(lineData)[3] <- v$meta$by
}
line.args$data <- lineData
p <- p + do.call("geom_line", line.args, envir=asNamespace("ggplot2"))
}
p
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/ggFactorPlot.R
|
makeYName <- function(fit, scale, trans, type) {
if (scale=="response" | (class(fit)[1] %in% c("lm", "aov") & identical(trans, I))) {
if (type=="contrast") {
yName <- as.expression(substitute(list(Delta) * x, list(x=as.character(formula(fit)[2]))))
} else {
yName <- as.character(formula(fit)[2])
}
} else if (inherits(fit, "mlm")) {
if (type=="contrast") {
yName <- sapply(colnames(fit$residuals), function(y) {as.expression(substitute(list(Delta) * x, list(x=y)))})
} else {
yName <- colnames(fit$residuals)
}
} else if (inherits(fit, "randomForest")) {
if (fit$type=="regression") yName <- as.character(formula(fit)[2])
if (fit$type=="classification") yName <- paste0("Pr(", as.character(formula(fit)[2]), ")")
} else {
yName <- NULL
}
yName
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/makeYName.R
|
pal <- function(n, alpha=1)
{
if (n==2) {
val <- hcl(seq(15, 375, len=4), l=60, c=150, alpha=alpha)[c(1,3)]
} else val <- hcl(seq(15, 375, len=n+1), l=60, c=150, alpha=alpha)[1:n]
val
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/pal.R
|
parseFormula <- function(form) {
form <- gsub("\\|", "\\+", as.character(form))
form <- gsub("\\*", "\\+", as.character(form))
f <- if (grepl("\\+", form)) unlist(strsplit(form, "\\+")) else form
n.f <- length(f)
for (i in 1:n.f) {
f[i] <- gsub(" ", "", f[i])
if (substr(f[i], 1, 3) %in% c("te(", "ti(", "lp(") || substr(f[i], 1, 2) %in% c("s(")) {
matched <- gregexpr("\\((?>[^()]|(?R))*\\)", f[i], perl = T)
fi <- substring(f[i], matched[[1]]+1, matched[[1]] + attr(matched[[1]], "match.length")-2)
fi <- gsub("\\([^\\)]+.*\\)", "", fi)
fi <- unlist(strsplit(fi, ","))
fi <- fi[!grepl("=", fi) | grepl("by\\s*=", fi)]
fi <- gsub("by\\s*=", "", fi)
f[i] <- paste(fi, collapse=" + ")
}
f[i] <- gsub("\\b[^\\(]*\\(([^,]+).*\\)", "\\1", f[i])
}
f <- f[f!=""]
val <- paste(f, collapse=" + ")
val <- gsub("()", "", val)
val
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/parseFormula.R
|
plot.visreg <- function(
x, overlay=FALSE, print.cond=FALSE, whitespace=0.2, partial=identical(x$meta$trans, I),
band=TRUE, rug=ifelse(partial, 0, 2), strip.names=is.numeric(x$fit[, x$meta$by]),
legend=TRUE, top=c('line', 'points'), gg=FALSE, line.par=NULL, fill.par=NULL,
points.par=NULL, ...) {
top <- match.arg(top)
warn <- FALSE
if (missing(print.cond)) {
if (!("by" %in% names(x$meta)) & x$meta$hasInteraction) print.cond <- warn <- TRUE
}
if (print.cond) printCond(x, warn)
if (all(is.na(x$res$visregRes))) {
partial <- FALSE
rug <- FALSE
warning(paste0("The generic function residuals() is not set up for this type of model object. To plot partial residuals, you will need to define your own residuals.", x$meta$class[1], "() function."))
}
if (gg) {
if (!requireNamespace("ggplot2")) stop("You must first install the ggplot2 package: install.packages('ggplot2')", call.=FALSE)
if (is.factor(x$fit[, x$meta$x])) {
p <- ggFactorPlot(x, partial, band, rug, whitespace, strip.names, overlay, top, line.par, fill.par, points.par, ...)
} else {
p <- ggContPlot(x, partial, band, rug, whitespace, strip.names, overlay, top, line.par, fill.par, points.par, ...)
}
return(p)
} else {
if ("by" %in% names(x$meta)) {
if (overlay) {
visregOverlayPlot(x, strip.names=strip.names, legend=legend, whitespace=whitespace, partial=partial, band=band, rug=rug, line.par=line.par, fill.par=fill.par, points.par=points.par, ...)
} else {
p <- visregLatticePlot(x, strip.names=strip.names, whitespace=whitespace, partial=partial, band=band, rug=rug, top=top, line.par=line.par, fill.par=fill.par, points.par=points.par, ...)
return(invisible(p))
}
} else {
visregPlot(x, whitespace=whitespace, partial=partial, band=band, rug=rug, top=top, line.par=line.par, fill.par=fill.par, points.par=points.par, ...)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/plot-visreg.R
|
plot.visreg2d <- function(x, plot.type=c("image","persp","rgl", "gg"), xlab, ylab, zlab, color, print.cond=FALSE, whitespace=0.2, ...) {
plot.type <- match.arg(plot.type)
if (missing(xlab)) xlab <- x$meta$x
if (missing(ylab)) ylab <- x$meta$y
if (missing(zlab)) {
if (plot.type %in% c("persp", "rgl") & is.expression(x$meta$z)) x$meta$z <- NULL ## persp cannot handle expressions
zlab <- if (is.null(x$meta$z)) paste("f(", x$meta$x, ", ", x$meta$y, ")", sep="") else x$meta$z
}
if (missing(color)) {
if (plot.type %in% c('image', 'gg')) {
color <- c(pal(3)[3], 'gray90', pal(3)[1])
} else if (plot.type == 'persp') {
color <- '#2fa4e7'
} else if (plot.type == 'rgl') {
color <- 'gray'
}
}
zz <- x$z
## Make factor axes
if (plot.type=='gg') {
mx <- my <- lx <- ly <- ggplot2::waiver()
} else {
mx <- my <- NULL
lx <- ly <- TRUE
}
if (is.factor(x$x)) {
xAxis <- factorAxis2d(x$x, whitespace, 99)
xx <- xAxis$x
mx <- xAxis$m
lx <- xAxis$l
zz <- zz[xAxis$ind,]
} else {
xx <- x$x
}
if (is.factor(x$y)) {
yAxis <- factorAxis2d(x$y, whitespace, 99)
yy <- yAxis$x
my <- yAxis$m
ly <- yAxis$l
zz <- zz[, yAxis$ind]
} else {
yy <- x$y
}
xlim <- if (is.factor(x$x)) c(0,1) else range(x$x)
ylim <- if (is.factor(x$y)) c(0,1) else range(x$y)
if (plot.type=="image") {
color.palette=colorRampPalette(color, space="Lab")
plot.args <- list(x=xx, y=yy, z=zz, xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, color.palette=color.palette, main=zlab)
plot.args$plot.axes <- quote({axis(1, at=mx, labels=lx); axis(2, at=my, labels=ly)})
new.args <- list(...)
if (length(new.args)) plot.args[names(new.args)] <- new.args
do.call("filled.contour", plot.args)
} else if (plot.type=="persp") {
ticktype <- ifelse(is.factor(x$x) | is.factor(x$y),"simple","detailed")
plot.args <- list(x=xx, y=yy, z=zz, xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, zlab=zlab, ticktype=ticktype, theta=-30, col=color, border="#BEBEBE33", shade=0.5)
new.args <- list(...)
if (length(new.args)) plot.args[names(new.args)] <- new.args
p <- do.call("persp", plot.args)
return(p)
} else if (plot.type=="rgl") {
if (!requireNamespace("rgl")) stop("You must first install the rgl package: install.packages('rgl')", call.=FALSE)
plot.args <- list(x=xx, y=yy, z=zz, xlab=xlab, ylab=ylab, zlab=zlab, color=color)
new.args <- list(...)
if (length(new.args)) plot.args[names(new.args)] <- new.args
#if (i >= 2) rgl::open3d()
do.call(rgl::persp3d, plot.args)
} else if (plot.type=="gg") {
if (!requireNamespace("ggplot2")) stop("You must first install the ggplot2 package: install.packages('ggplot2')", call.=FALSE)
df <- data.frame(x = xx[row(zz)], y = yy[col(zz)], z = c(zz))
p <- ggplot2::ggplot(df, ggplot2::aes_string('x', 'y')) +
ggplot2::geom_raster(ggplot2::aes_string(fill='z')) +
#ggplot2::geom_contour(ggplot2::aes(z=z), color="#BEBEBE7F") +
ggplot2::scale_x_continuous(expand = c(0, 0), labels=lx, breaks=mx) +
ggplot2::scale_y_continuous(expand = c(0, 0), labels=ly, breaks=my) +
ggplot2::xlab(xlab) + ggplot2::ylab(ylab) +
ggplot2::scale_fill_gradientn(colors=color, na.value='white', guide=ggplot2::guide_colorbar(title=zlab))
return(p)
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/plotVisreg2d.R
|
plot.visregList <- function(x, ask=TRUE, ...) {
n <- length(x)
prompt.user <- FALSE
if (ask & (prod(par("mfcol")) < n) && dev.interactive()) {
oask <- devAskNewPage()
prompt.user <- TRUE
on.exit(devAskNewPage(oask))
}
for (i in 1:length(x)) {
p <- plot(x[[i]], ...)
if (inherits(p, 'gg')) {
if (i==1) {
ggList <- vector('list', length(x))
}
ggList[[i]] <- p
} else {
if (prompt.user) devAskNewPage(TRUE)
}
}
if (inherits(p, 'gg')) return(ggList)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/plotVisregList.R
|
printCond <- function(v, warn=FALSE) {
if (warn) warning(" Note that you are attempting to plot a 'main effect' in a model that contains an
interaction. This is potentially misleading; you may wish to consider using the 'by'
argument.", call.=FALSE)
p <- ncol(v$fit)-4
X <- v$fit[, 1:p, drop=FALSE]
X <- X[,-which(names(X) == v$meta$x), drop=FALSE]
constant.columns <- which(sapply(X, function(x) all(x==x[1])))
varying.columns <- setdiff(1:ncol(X), constant.columns)
for (j in 1:ncol(X)) if (is.factor(X[,j])) X[,j] <- as.character(X[,j])
cat("Conditions used in construction of plot\n")
for (j in varying.columns) {
x <- paste(unique(X[,j]), collapse= " / ")
cat(names(X)[j], ": ", x, "\n", sep="")
}
for (j in constant.columns) {
cat(names(X)[j], ": ", X[1,j], "\n", sep="")
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/printCond.R
|
se.mlm <- function(object, newdata) {
coef <- coef(object)
ny <- ncol(coef)
effects <- object$effects
resid <- object$residuals
fitted <- object$fitted.values
ynames <- colnames(coef)
if (is.null(ynames)) {
lhs <- object$terms[[2L]]
if (mode(lhs) == "call" && lhs[[1L]] == "cbind")
ynames <- as.character(lhs)[-1L]
else ynames <- paste0("Y", seq_len(ny))
}
ind <- ynames == ""
if (any(ind))
ynames[ind] <- paste0("Y", seq_len(ny))[ind]
value <- NULL
cl <- oldClass(object)
class(object) <- cl[match("mlm", cl):length(cl)][-1L]
object$call$formula <- formula(object)
for (i in seq(ny)) {
object$coefficients <- coef[, i]
names(object$coefficients) <- rownames(coef)
object$residuals <- resid[, i]
object$fitted.values <- fitted[, i]
object$effects <- effects[, i]
object$call$formula[[2L]] <- object$terms[[2L]] <- as.name(ynames[i])
value <- cbind(value, predict(object, newdata=newdata, se.fit=TRUE)$se.fit)
}
colnames(value) <- ynames
value
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/se.mlm.R
|
setupCond <- function(cond, f, by, breaks) {
for (i in seq_along(cond)) if(!is.character(cond[[i]]) & is.factor(f[, names(cond)[i]])) cond[[i]] <- as.character(cond[[i]])
if (missing(by)) {
cond <- list(cond)
} else {
cond.orig <- cond
if(is.numeric(f[, by])) {
if (length(breaks)==1) {
unique.by <- unique(f[, by])
if (breaks >= length(unique.by)) {
lev <- sort(unique.by)
} else {
a <- 1/5/2^(breaks-2)
lev <- as.double(quantile(f[, by], seq(a, 1-a, length=breaks), type=1))
}
} else {
lev <- breaks
}
n.by <- length(lev)
} else {
if (is.factor(breaks) || is.character(breaks)) {
if (!all(breaks %in% levels(f[, by]))) stop("'breaks' does not match levels of 'by' variable", call.=FALSE)
lev <- breaks
} else {
lev <- levels(f[, by])
}
n.by <- length(lev)
}
cond <- vector("list", n.by)
for (i in 1:n.by) {
a <- if (is.factor(lev)) as.character(lev[i]) else lev[i]
cond[[i]] <- c(a, cond.orig)
names(cond[[i]])[1] <- by
cond[[i]] <- as.list(cond[[i]])
}
attr(cond, "lev") <- lev
}
cond
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupCond.R
|
setupD <- function(fit, f, name, nn, cond, whitespace, ...) {
## Set up n-row data frame for residuals
x <- f[, name]
xdf <- data.frame(x)
names(xdf) <- name
df <- fillFrame(f, xdf, cond)
rhs_form <- formula(fit)
rhs_form[2] <- NULL
simple_rhs <- paste(all.vars(rhs_form), collapse = ' + ')
simple_form <- as.formula(paste("~", simple_rhs))
D <- model.frame(simple_form, df)
condNames <- setdiff(names(D), name)
condNames <- intersect(condNames, names(df))
D <- cbind(D, df[, setdiff(names(df), names(D)), drop=FALSE])
## Set up nn-row data frame for prediction
dots <- list(...)
if (is.factor(x)) {
xx <- factor(levels(x), levels=levels(x))
} else {
xx <- seq(min(x), max(x), length=nn)
}
xxdf <- data.frame(xx)
names(xxdf) <- name
df <- fillFrame(f, xxdf, cond)
DD <- model.frame(simple_form, df)
DD <- cbind(DD, df[, setdiff(names(df), names(DD)), drop=FALSE])
list(x=x, xx=xx, D=D, DD=DD, factor=is.factor(x), name=name, cond=D[1, condNames, drop=FALSE])
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupD.R
|
setupF <- function(fit, xvar, call.env, data) {
CALL <- if (isS4(fit)) fit@call else fit$call
if (!is.null(data)) {
Data <- data
} else if (!is.null(CALL) && ('data' %in% names(CALL)) && exists(as.character(CALL$data), call.env)) {
env <- call.env
Data <- eval(CALL$data, envir=env)
} else if (isS4(fit)) {
FRAME <- try(fit@frame, silent=TRUE)
DATA <- try(fit@data, silent=TRUE)
if (!inherits(DATA, 'try-error')) {
Data <- DATA
} else if (!inherits(FRAME, 'try-error')) {
Data <- FRAME
} else {
stop("visreg cannot find the data set used to fit your model; supply it using the 'data=' option", call.=FALSE)
}
} else {
ENV <- environment(fit$terms)
if ("data" %in% names(fit) && is.data.frame(fit$data)) {
Data <- fit$data
env <- NULL
} else if (is.null(CALL$data)) {
env <- NULL
Data <- NULL
} else if (exists(as.character(CALL$data), call.env)) {
env <- call.env
Data <- eval(CALL$data, envir=env)
} else if (exists(as.character(CALL$data), ENV)) {
env <- ENV
Data <- eval(CALL$data, envir=ENV)
} else {
stop("visreg cannot find the data set used to fit your model; supply it using the 'data=' option", call.=FALSE)
}
}
form <- formula(fit)
if (!is.null(Data)) names(Data) <- gsub('offset\\((.*)\\)', '\\1', names(Data))
if (inherits(fit, 'mlm') && fit$terms[[2L]] != 'call') {
ff <- form
ff[[2]] <- NULL
av <- get_all_vars(ff, Data) # If mlm with matrix as Y, outside of data frame framework
} else {
av <- get_all_vars(form, Data) # https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=14905
}
f <- as.data.frame(av)
if (inherits(CALL$random, "call")) {
rf <- as.data.frame(as.list(get_all_vars(CALL$random, Data)))
rf <- rf[, setdiff(names(rf), names(f)), drop=FALSE]
f <- cbind(f, rf)
}
if ("subset" %in% names(CALL) & !(inherits(fit, 'averaging'))) {
s <- CALL$subset
subset <- eval(substitute(s), Data, env)
f <- f[which(subset==TRUE), , drop=FALSE]
}
suppressWarnings(f <- f[!apply(is.na(f), 1, any), , drop=FALSE])
# Handle some variable type issues
needsUpdate <- FALSE
f <- droplevels(f)
frameClasses <- sapply(f, class)
if (any(frameClasses=="Surv")) needsUpdate <- TRUE
if (any(frameClasses=="character")) {
needsUpdate <- TRUE
for (j in 1:ncol(f)) if (typeof(f[,j])=="character") f[,j] <- factor(f[,j])
}
if (any(frameClasses=="logical")) {
needsUpdate <- TRUE
for (j in 1:ncol(f)) if (typeof(f[,j])=="logical") f[,j] <- as.double(f[,j])
}
if (missing(xvar)) {
all_x <- strsplit(parseFormula(formula(fit)[3]), ' + ', fixed=TRUE)[[1]]
inModel <- sapply(names(f), function(x) x %in% all_x)
const <- sapply(f, function(x) all(x==x[1]))
xvar <- names(f)[!const & inModel]
}
if (length(xvar)==0) stop("The model has no predictors; visreg has nothing to plot.", call.=FALSE)
for (i in 1:length(xvar)){if (!is.element(xvar[i], names(f))) stop(paste(xvar[i], "not in model"), call.=FALSE)}
attr(f, "needsUpdate") <- needsUpdate
attr(f, "xvar") <- xvar
f
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupF.R
|
# v is a list of three elements: fit, res, and meta
# alternatively (class "visregList"), a list of visreg elements
setupV <- function(fit, f, xvar, nn, cond, type, trans, xtrans, alpha, jitter, by, yName, ...) {
# Initial setup
if (length(xvar) > 1 & length(cond) > 1) stop("Cannot specify 'by' and multiple x variables simultaneously", call.=FALSE)
J <- max(length(xvar), length(cond))
Attempt <- try(max(attr(terms(as.formula(formula(fit))), "order")) > 1, silent=TRUE)
hasInteraction <- ifelse(inherits(Attempt, 'try-error'), FALSE, Attempt)
lev <- attr(cond, "lev")
# Get xy list
xy <- vector("list", J)
for (j in 1:J) {
cond.j <- if (length(cond) > 1) cond[[j]] else cond[[1]]
name <- if (length(xvar) > 1) xvar[j] else xvar
xy[[j]] <- getXY(fit, f, name, nn, cond.j, type, trans, xtrans, alpha, jitter, ...)
}
if (!missing(by)) xy <- subsetV(xy, f, by, lev, type)
# Format
meta <- list(x=xvar, y=xy[[1]]$y$name, hasInteraction=hasInteraction, yName=yName, trans=trans, class=class(fit))
K <- xy[[1]]$y$n
if (K==1) {
if (!missing(by)) {
meta$by <- by
v <- list(fit=NULL, res=NULL, meta=meta)
for (j in 1:length(xy)) {
fit.j <- data.frame(xy[[j]]$x$DD, visregFit=xy[[j]]$y$fit, visregLwr=xy[[j]]$y$lwr, visregUpr=xy[[j]]$y$upr)
res.j <- data.frame(xy[[j]]$x$D, visregRes=xy[[j]]$y$r, visregPos=xy[[j]]$y$pos)
fit.j[, xvar] <- xy[[j]]$x$xx
res.j[, xvar] <- xy[[j]]$x$x
v$fit <- rbind(v$fit, fit.j)
v$res <- rbind(v$res, res.j)
}
class(v) <- "visreg"
} else {
v <- vector("list", J)
for (j in 1:J) {
meta.j <- meta
meta.j$x <- xvar[j]
v[[j]] <- list(fit=data.frame(xy[[j]]$x$DD, visregFit=xy[[j]]$y$fit, visregLwr=xy[[j]]$y$lwr, visregUpr=xy[[j]]$y$upr),
res=data.frame(xy[[j]]$x$D, visregRes=xy[[j]]$y$r, visregPos=xy[[j]]$y$pos),
meta=meta.j)
v[[j]]$fit[, xvar[j]] <- xy[[j]]$x$xx
v[[j]]$res[, xvar[j]] <- xy[[j]]$x$x
class(v[[j]]) <- "visreg"
}
if (J==1) {
v <- v[[1]]
} else {
class(v) <- "visregList"
}
}
} else {
if (!missing(by)) {
meta$by <- by
v <- vector("list", K)
for (k in 1:K) {
meta.k <- meta
meta.k$y <- meta$y[k]
meta.k$yName <- meta$yName[k]
v[[k]] <- list(fit=NULL, res=NULL, meta=meta.k)
for (j in 1:J) {
fit.jk <- data.frame(xy[[j]]$x$DD, visregFit=xy[[j]]$y$fit[,k], visregLwr=xy[[j]]$y$lwr[,k], visregUpr=xy[[j]]$y$upr[,k])
res.jk <- data.frame(xy[[j]]$x$D, visregRes=xy[[j]]$y$r[,k], visregPos=xy[[j]]$y$pos[,k])
fit.jk[, xvar] <- xy[[j]]$x$xx
res.jk[, xvar] <- xy[[j]]$x$x
v[[k]]$fit <- rbind(v[[k]]$fit, fit.jk)
v[[k]]$res <- rbind(v[[k]]$res, res.jk)
}
class(v[[k]]) <- "visreg"
}
class(v) <- "visregList"
} else {
v <- vector("list", J*K)
for (j in 1:J) {
for (k in 1:K) {
meta.jk <- meta
meta.jk$x <- meta$x[j]
meta.jk$y <- meta$y[k]
meta.jk$yName <- meta$yName[k]
l <- (j-1)*K + k
v[[l]] <- list(fit=data.frame(xy[[j]]$x$DD, visregFit=xy[[j]]$y$fit[,k], visregLwr=xy[[j]]$y$lwr[,k], visregUpr=xy[[j]]$y$upr[,k]),
res=data.frame(xy[[j]]$x$D, visregRes=xy[[j]]$y$r[,k], visregPos=xy[[j]]$y$pos[,k]),
meta=meta.jk)
v[[l]]$fit[, xvar[j]] <- xy[[j]]$x$xx
v[[l]]$res[, xvar[j]] <- xy[[j]]$x$x
class(v[[l]]) <- "visreg"
}
}
class(v) <- "visregList"
}
}
v
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupV.R
|
# setupV for visreg2d
# Returns a list of x, y, and z for plotting
setupV2 <- function(fit, f, xvar, yvar, nn, cond, type, scale, trans) {
n.z <- if (inherits(fit, "mlm")) ncol(coef(fit)) else 1
form <- parseFormula(formula(fit)[3])
x <- f[, xvar]
y <- f[, yvar]
xx <- if(is.factor(x)) factor(levels(x), levels=levels(x)) else seq(min(x), max(x), length=nn)
yy <- if(is.factor(y)) factor(levels(y), levels=levels(y)) else seq(min(y), max(y), length=nn)
xydf <- as.data.frame(expand.grid(xx, yy))
names(xydf) <- c(xvar, yvar)
if (type=="conditional") {
df <- fillFrame(f, xydf, cond)
DD <- model.frame(as.formula(paste("~", form)), df)
DD <- cbind(DD, df[, setdiff(names(df), names(DD)), drop=FALSE])
P <- predict(fit, newdata=DD)
if (inherits(fit, "mlm")) {
z <- vector("list", n.z)
for (i in 1:n.z) z[[i]] <- matrix(trans(P[,i]), nrow=length(xx), ncol=length(yy))
} else {
z <- matrix(trans(P), nrow=length(xx), ncol=length(yy))
}
} else if (type=="contrast") {
xref <- if(is.factor(x)) xx[1] else xref <- mean(x)
yref <- if(is.factor(y)) yy[1] else yref <- mean(y)
xydf <- rbind(c(xref, yref), xydf)
df <- fillFrame(f, xydf, cond)
DD <- rbind(f, df)
if (inherits(fit, "mlm")) {
ind <- apply(is.finite(coef(fit)), 1, all)
if (!identical(ind, apply(is.finite(coef(fit)), 1, any))) stop("Inconsistent NA/NaN coefficients across outcomes", call.=FALSE)
} else ind <- is.finite(coef(fit))
XX. <- model.matrix(as.formula(paste("~", formula(fit)[3])), DD)[-(1:nrow(f)), ind]
XX <- t(t(XX.[-1,])-XX.[1,])
if (inherits(fit, "mlm")) {
z <- vector("list", n.z)
for (i in 1:n.z) z[[i]] <- matrix(trans(XX%*%coef(fit)[ind, i]), nrow=length(xx), ncol=length(yy))
} else {
z <- matrix(trans(XX%*%coef(fit)[ind]), nrow=length(xx), ncol=length(yy))
}
}
zname <- makeYName(fit, scale, trans, type)
D <- model.frame(as.formula(paste("~", form)), df)
condNames <- setdiff(names(D), c(xvar, yvar))
condNames <- intersect(condNames, names(df))
baseMeta <- list(x=xvar, y=yvar, trans=trans, class=class(fit), cond=D[1, condNames, drop=FALSE])
if (n.z > 1) {
v <- vector("list", n.z)
for (i in 1:n.z) {
meta <- baseMeta
meta$z <- zname[i]
v[[i]] <- list(x=xx, y=yy, z=z[[i]], meta=meta)
class(v[[i]]) <- 'visreg2d'
}
class(v) <- 'visregList'
} else {
meta <- baseMeta
meta$z <- zname
v <- list(x=xx, y=yy, z=z, meta=meta)
class(v) <- 'visreg2d'
}
v
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupV2.R
|
setupX <- function(fit, f, name, nn, cond, ...) {
## Set up n x p matrix for (conditional) partial residuals
x <- f[, name]
if (is.factor(x)) {
xref <- 1
if (name %in% names(cond)) {
if (cond[[name]] %in% levels(x)) {
xref <- which(levels(x) == cond[[name]])
} else if (cond[[name]] %in% 1:length(levels(x))) {
xref <- cond[[name]]
} else {
warning(paste0("You have specified a value for ", name, " that is not one of its levels.\n Using reference level instead."))
}
}
} else {
if (name %in% names(cond)) {
xref <- cond[[name]]
} else {
xref <- mean(x)
}
}
x <- if (is.factor(x)) factor(c(xref, as.integer(x)), labels=levels(x)) else c(xref, x)
xdf <- data.frame(x)
names(xdf) <- name
df <- fillFrame(f, xdf, cond)
D <- rbind(f[, names(df)], df)
form <- formula(fit)[3]
if (inherits(fit, "lme")) {
b <- nlme::fixed.effects(fit)
} else if (inherits(fit, "merMod")) {
b <- fit@beta
} else {
b <- coef(fit)
}
if (inherits(fit, "mlm")) {
ind <- apply(is.finite(b), 1, all)
if (!identical(ind, apply(is.finite(b), 1, any))) stop("Inconsistent NA/NaN coefficients across outcomes", call.=FALSE)
} else ind <- is.finite(b)
if (inherits(fit, "gam")) {
form <- parseFormula(formula(fit)[3])
D <- model.frame(as.formula(paste("~", form)), df)
X. <- predict(fit, newdata=as.list(D), type="lpmatrix")
} else if (inherits(fit, "merMod")) {
form <- formula(fit, fixed.only = TRUE)
RHS <- formula(substitute(~R, list(R = form[[length(form)]])))
X. <- model.matrix(RHS, D)[-(1:nrow(f)), ind]
} else if (inherits(fit, "glmmadmb")) {
form <- as.formula(paste("~", as.character(fit$fixed[3])))
X. <- model.matrix(form, D)[-(1:nrow(f)), ind]
} else {
X. <- model.matrix(as.formula(paste("~", form)), D)[-(1:nrow(f)), ind]
}
X <- t(t(X.[-1,])-X.[1,])
## Set up data frame with nn rows for prediction
dots <- list(...)
if (is.factor(x)) {
xx <- factor(c(xref, 1:length(levels(x))), labels=levels(x))
} else {
xx <- c(xref, seq(min(x), max(x), length=nn))
}
xxdf <- data.frame(xx)
names(xxdf) <- name
df <- fillFrame(f, xxdf, cond)
DD <- rbind(f[, names(df)], df)
if (inherits(fit, "gam")) {
DD <- model.frame(as.formula(paste("~", form)), df)
XX. <- predict(fit, newdata=as.list(DD), type="lpmatrix")
} else if (inherits(fit, "merMod")) {
XX. <- model.matrix(RHS, DD)[-(1:nrow(f)), ind]
} else XX. <- model.matrix(as.formula(paste("~", form)), DD)[-(1:nrow(f)), ind]
XX <- t(t(XX.[-1,])-XX.[1,])
## Remove extraneous columns for coxph
if (inherits(fit, "coxph")) {
remove.xx <- c(grep("(Intercept)", colnames(XX), fixed=TRUE),
grep("strata(", colnames(XX), fixed=TRUE),
grep("cluster(", colnames(XX), fixed=TRUE))
remove.x <- c(grep("(Intercept)", colnames(X), fixed=TRUE),
grep("strata(", colnames(XX), fixed=TRUE),
grep("cluster(", colnames(X), fixed=TRUE))
XX <- XX[, -remove.xx, drop=FALSE]
X <- X[, -remove.xx, drop=FALSE]
} else if (inherits(fit, "polr")) {
remove.xx <- grep("(Intercept)", colnames(XX), fixed=TRUE)
remove.x <- grep("(Intercept)", colnames(X), fixed=TRUE)
XX <- XX[, -remove.xx, drop=FALSE]
X <- X[, -remove.xx, drop=FALSE]
}
condNames <- names(model.frame(as.formula(paste("~", parseFormula(formula(fit)[3]))), df))
condNames <- setdiff(condNames, name)
condNames <- intersect(condNames, names(df))
return(list(x=x[-1], xx=xx[-1], X=X, XX=XX, factor=is.factor(x), name=name, cond=df[1, condNames, drop=FALSE]))
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/setupX.R
|
subset.visreg <- function(x, sub, ...) {
x$fit <- x$fit[eval(match.call()$sub, x$fit),]
x$res <- x$res[eval(match.call()$sub, x$res),]
x
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/subset.R
|
## Subsets xy so that residuals appear only once
## Should probably be renamed subsetXY
subsetV <- function(v, f, by, lev, type) {
## Calculate distance
if (is.numeric(f[, by])) {
D <- matrix(NA, nrow(f), length(v))
for (i in 1:length(v)) {
D[,i] <- (f[, by]-lev[i])^2
}
}
for (i in 1:length(v)) {
if (is.factor(f[, by])) {
ind <- as.character(f[, by])==as.character(lev[i])
} else {
ind <- (apply(D, 1, which.min)==i)
}
v[[i]]$x$D <- v[[i]]$x$D[ind,]
v[[i]]$x$x <- v[[i]]$x$x[ind]
v[[i]]$y$r <- if (v[[i]]$y$n == 1) v[[i]]$y$r[ind] else v[[i]]$y$r[ind,]
v[[i]]$y$pos <- if (v[[i]]$y$n == 1) v[[i]]$y$pos[ind] else v[[i]]$y$pos[ind,]
}
v
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/subsetV.R
|
toplegend <- function(...) {
if (par("oma")[3]==0) {
x <- mean(par("usr")[1:2])
yy <- transform.coord(par("usr")[3:4], par("plt")[3:4])
y <- mean(c(yy[2], par("usr")[4]))
legend(x, y, xpd=NA, bty="n", xjust=0.5, yjust=0.5, ...)
} else {
g <- par("mfrow")
xx <- transform.coord(par("usr")[1:2], par("plt")[1:2])
yy <- transform.coord(par("usr")[3:4], par("plt")[3:4])
xxx <- transform.coord(xx, c(g[2]-1, g[2])/g[2])
yyy <- transform.coord(yy, c(g[1]-1, g[1])/g[1])
yyyy <- transform.coord(yyy, par("omd")[3:4])
legend(mean(xxx), mean(c(yyy[2], yyyy[2])), xpd=NA, bty="n", xjust=0.5, yjust=0.5, ...)
}
}
transform.coord <- function(x, p) {
ba <- (x[2]-x[1])/(p[2]-p[1])
a <- x[1]-p[1]*ba
b <- a + ba
c(a, b)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/toplegend.R
|
visreg <- function(fit, xvar, by, breaks=3, type=c("conditional", "contrast"), data=NULL, trans=I,
scale=c("linear","response"), xtrans, alpha=.05, nn=101, cond=list(), jitter=FALSE, collapse=FALSE,
plot=TRUE, ...) {
# Setup
if (type[1]=="effect") {
warning("Please note that type='effect' is deprecated and may not be supported in future versions of visreg. Use type='contrast' instead.")
type <- "contrast"
}
type <- match.arg(type)
scale <- match.arg(scale)
if (scale=="response") {
if (inherits(fit, "lrm")) {
trans <- binomial()$linkinv
} else if (inherits(fit, "betareg")) {
trans <- fit$link$mean$linkinv
} else {
trans <- family(fit)$linkinv
}
}
if (!identical(trans, I) & type=="contrast") warning("You are attempting to transform a contrast. The resulting plot is not guaranteed to be meaningful.", call.=FALSE)
Data <- setupF(fit, xvar, parent.frame(), data)
xvar <- attr(Data, "xvar")
if (attr(Data, "needsUpdate")) {
if (inherits(fit, 'coxph')) {
fit <- update(fit, formula=formula(fit), data=Data, model=TRUE)
} else {
fit <- update(fit, formula=formula(fit), data=Data)
}
}
cond <- setupCond(cond, Data, by, breaks)
# Calculate v
yName <- makeYName(fit, scale, trans, type)
v <- setupV(fit, Data, xvar, nn, cond, type, trans, xtrans, alpha, jitter, by, yName, ...)
if (collapse) v <- collapse.visregList(v)
# Plot/return
if (plot) {
p <- plot(v, ...)
if (!is.null(p) && inherits(p, 'gg')) return(p)
if (!is.null(p) && inherits(p, 'list') && inherits(p[[1]], 'gg')) return(p)
}
invisible(v)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visreg.R
|
visreg2d <- function(fit, xvar, yvar, type=c("conditional", "contrast"), data=NULL, trans=I, scale=c("linear","response"), nn=99, cond=list(), plot=TRUE, ...) {
# Setup
if (type[1]=="effect") {
warning("Please note that type='effect' is deprecated and may not be supported in future versions of visreg. Use type='contrast' instead.")
type <- "contrast"
}
type <- match.arg(type)
scale <- match.arg(scale)
if (scale=="response") trans <- family(fit)$linkinv
if (missing(xvar) | missing(yvar)) stop("Must specify and x and y variable", call.=FALSE)
if (!identical(trans, I) & type=="contrast") warning("You are attempting to transform a contrast. The resulting plot is not guaranteed to be meaningful.", call.=FALSE)
# Set up f
f <- setupF(fit, c(xvar, yvar), parent.frame(), data)
if (attr(f, "needsUpdate")) fit <- update(fit, data=f)
cond <- setupCond(cond, f)[[1]]
# Calculate v
v <- setupV2(fit, f, xvar, yvar, nn, cond, type, scale, trans)
# Plot/return
if (plot) {
p <- plot(v, ...)
if (!is.null(p) && inherits(p, 'gg') || inherits(p, 'list')) return(p)
}
invisible(v)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visreg2d.R
|
visregFactorPanel <- function(x, y, w, subscripts, lframe, lresids, partial, band, rug, top, fill.par, ...) {
K <- length(levels(lframe$xx))
len <- K*(1-w)+(K-1)*w
for(k in 1:K) {
x1 <- (k-1)/len
x2 <- (k-1)/len + (1-w)/len
xx <- c(x1, x2)
if (band) {
poly.args <- list(x=c(xx, rev(xx)), y=c(rep(lframe$lwr[subscripts][k], 2), rev(rep(lframe$upr[subscripts][k], 2))), subscripts=subscripts, col="gray85", border=F)
if (length(fill.par)) poly.args[names(fill.par)] <- fill.par
do.call("panel.polygon", poly.args, envir=asNamespace("lattice"))
}
if (!partial) {
lattice::panel.lines(xx, rep(lframe$fit[subscripts][k], 2), subscripts=subscripts, ...)
} else {
ind <- (lresids$by == lframe$by[subscripts][1]) & (lresids$x == levels(lresids$x)[k])
rx <- seq(x1, x2, len=sum(ind)+2)[c(-1,-(sum(ind)+2))]
if (top == 'line') {
lattice::panel.points(rx, lresids$r[ind])
lattice::panel.lines(xx, rep(lframe$fit[subscripts][k], 2), subscripts=subscripts, ...)
} else {
lattice::panel.lines(xx, rep(lframe$fit[subscripts][k], 2), subscripts=subscripts, ...)
lattice::panel.points(rx, lresids$r[ind])
}
}
if (rug==1) lattice::panel.rug(rx)
if (rug==2) {
ind1 <- ind & !lresids$pos
ind2 <- ind & lresids$pos
rx1 <- seq(x1, x2, len=sum(ind1)+2)[c(-1, -(sum(ind1)+2))]
rx2 <- seq(x1, x2, len=sum(ind2)+2)[c(-1, -(sum(ind2)+2))]
lattice::panel.rug(rx1)
lattice::panel.rug(rx2, regular=FALSE)
}
}
lattice::panel.xyplot(0, 0, subscripts=subscripts, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregFactorPanel.R
|
visregLatticePlot <- function(v, partial, band, rug, whitespace, strip.names, top, line.par, fill.par, points.par, ...) {
## Setup
x <- v$res[, v$meta$x]
y <- v$res$visregRes
b <- v$res[, v$meta$by]
xx <- v$fit[, v$meta$x]
yy <- v$fit$visregFit
bb <- v$fit[, v$meta$by]
lwr <- v$fit$visregLwr
upr <- v$fit$visregUpr
if (is.factor(bb)) {
b <- droplevels(b)
bb <- droplevels(bb)
}
xlim <- if (is.factor(xx)) c(0, 1) else range(xx)
if (partial) {
ylim <- range(c(y, lwr, upr), na.rm=TRUE)
} else {
ylim <- range(c(yy, lwr, upr), na.rm=TRUE)
}
pad <- 0.05*diff(ylim)
ylim[1] <- ylim[1]-pad
ylim[2] <- ylim[2]+pad
pad <- 0.04*diff(xlim)
xlim[1] <- xlim[1]-pad
xlim[2] <- xlim[2]+pad
ylab <- if (is.null(v$meta$yName)) paste("f(", v$meta$x, ")", sep="") else v$meta$yName
new.args <- list(...)
if (identical(strip.names, FALSE)) {
strip <- lattice::strip.custom(strip.names=FALSE, factor.levels=levels(as.factor(bb)), strip.levels=c(TRUE, TRUE), fg=lattice::trellis.par.get("strip.background")$col)
} else if (identical(strip.names, TRUE)) {
if (is.factor(v$fit[, v$meta$by])) {
strip <- lattice::strip.custom(strip.names=TRUE, strip.levels=c(TRUE, TRUE), var.name=v$meta$by)
} else {
strip <- lattice::strip.custom(strip.names=FALSE, factor.levels=paste(v$meta$by, abbrNum(bb), sep=": "), strip.levels=c(TRUE, TRUE), fg=lattice::trellis.par.get("strip.background")$col)
}
} else {
strip <- lattice::strip.custom(strip.names=FALSE, factor.levels=strip.names, strip.levels=c(TRUE, TRUE), fg=lattice::trellis.par.get("strip.background")$col)
}
lframe <- data.frame(fit=yy, lwr=lwr, upr=upr, xx=xx, by=bb)
lresids <- data.frame(r=y, x=x, by=b, pos=v$res$visregPos)
plot.args <- list(x=formula(lframe$fit~lframe$xx | lframe$by), type="l", ylim=ylim, xlab=v$meta$x, ylab=ylab, lframe=lframe, lresids=lresids, partial=partial, band=band, rug=rug, xlim=xlim, strip=strip, top=top, fill.par=fill.par)
if (length(new.args)) plot.args[names(new.args)] <- new.args
if (is.null(dev.list())) trellis.device()
opar <- lattice::trellis.par.get()
# Plot
line.args <- list(lwd=3, col="#008DFFFF")
if (length(line.par)) line.args[names(line.par)] <- line.par
lattice::trellis.par.set(plot.line=line.args)
points.args <- list(cex=0.4, pch=19, col="gray50")
if (length(points.par)) points.args[names(points.par)] <- points.par
lattice::trellis.par.set(plot.symbol=points.args)
FUN <- getFromNamespace('xyplot', 'lattice')
if (is.factor(x)) {
K <- length(levels(x))
len <- K*(1-whitespace)+(K-1)*whitespace
scales <- list(x=list(at=((0:(K-1))/len+(1-whitespace)/(2*len)), labels=levels(x)))
if (is.null(plot.args$scales)) {
plot.args$scales <- scales
} else if (is.null(plot.args$scales$x)) {
plot.args$scales$x <- scales$x
} else {
plot.args$scales$x <- c(plot.args$scales$x, scales)
}
plot.args$panel <- visregFactorPanel
plot.args$w <- whitespace
tp <- do.call(FUN, plot.args)
plot(tp)
} else {
plot.args$panel <- visregPanel
tp <- do.call(FUN, plot.args)
plot(tp)
}
lattice::trellis.par.set(opar)
return(tp)
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregLatticePlot.R
|
visregList <- function(..., labels, collapse=FALSE) {
out <- structure(list(...), class="visregList")
if (collapse) out <- collapse.visregList(out, labels=labels)
out
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregList.R
|
visregOverlayPlot <- function(v, partial, band, rug, ask, whitespace, legend, strip.names, line.par, fill.par, points.par, ...) {
# Setup
x <- v$res[, v$meta$x]
y <- v$res$visregRes
b <- v$res[, v$meta$by]
xx <- v$fit[, v$meta$x]
yy <- v$fit$visregFit
bb <- v$fit[, v$meta$by]
lev <- unique(bb)
lwr <- v$fit$visregLwr
upr <- v$fit$visregUpr
xlim <- if (is.factor(xx)) c(0, 1) else range(xx)
if (partial) {
ylim <- range(c(y, lwr, upr), na.rm=TRUE)
} else {
ylim <- range(c(yy, lwr, upr), na.rm=TRUE)
}
ylab <- if (is.null(v$meta$yName)) paste("f(", v$meta$x, ")", sep="") else v$meta$yName
# Empty plot
plot.args <- list(x=1, y=1, ylim=ylim, xlab=v$meta$x, ylab=ylab, type="n", xlim=xlim, xaxt=ifelse(is.factor(xx),'n','s'), las=1)
new.args <- list(...)
if (length(new.args)) plot.args[names(new.args)] <- new.args
do.call("plot", plot.args)
col <- pal(length(lev))
acol <- pal(length(lev), alpha=0.5)
line.args <- list(lwd=3, col=col, lty=1)
if (length(line.par)) line.args[names(line.par)] <- line.par
points.args <- list(pch=19, cex=0.4, col=col)
if (length(points.par)) points.args[names(points.par)] <- points.par
fill.args <- list(col=acol, border=F)
if (length(fill.par)) fill.args[names(fill.par)] <- fill.par
fun <- function(x, i) if (length(x)==length(lev)) x[i] else x
if (is.factor(x) && !("xaxt" %in% names(new.args) && new.args$xaxt=="n")) factorAxis(x, whitespace, new.args)
# Add bands
if (band) {
for (i in 1:length(lev)) {
indfit <- v$fit[, v$meta$by] == lev[i]
fill.args.i <- lapply(fill.args, fun, i)
if (is.factor(x)) {
v.i <- v
v.i$fit <- subset(v.i$fit, indfit)
fp_bands(v.i, whitespace, fill.args.i)
} else {
fill.args.i$x <- c(xx[indfit], rev(xx[indfit]))
fill.args.i$y <- c(lwr[indfit], rev(upr[indfit]))
do.call("polygon", fill.args.i)
}
}
}
# Add points
if (partial) {
for (i in 1:length(lev)) {
indres <- v$res[, v$meta$by] == lev[i]
points.args.i <- lapply(points.args, fun, i)
if (is.factor(x)) {
v.i <- v
v.i$res <- subset(v.i$res, indres)
fp_points(v.i, whitespace, points.args.i)
} else {
points.args.i$x <- x[indres]
points.args.i$y <- y[indres]
do.call("points", points.args.i)
}
}
}
# Add lines and rugs
for (i in 1:length(lev)) {
line.args.i <- lapply(line.args, fun, i)
if (is.factor(x)) {
indfit <- v$fit[, v$meta$by] == lev[i]
v.i <- v
v.i$fit <- subset(v.i$fit, indfit)
fp_lines(v.i, whitespace, line.args.i)
fp_rug(v.i, whitespace, rug, line.args.i)
} else {
indfit <- v$fit[, v$meta$by] == lev[i]
indres <- v$res[, v$meta$by] == lev[i]
line.args.i$x <- xx[indfit]
line.args.i$y <- yy[indfit]
do.call("lines", line.args.i)
if (rug==1) rug(x[indres], side=1, col=line.args.i$col)
if (rug==2) {
rug(x[indres][!v$res$visregPos[indres]], side=1, col=line.args.i$col)
rug(x[indres][v$res$visregPos[indres]], side=3, col=line.args.i$col)
}
}
}
# Add legend
if (legend) {
if (identical(strip.names, FALSE)) {
if (is.double(lev)) {
lgtext <- round(lev, 3)
} else {
lgtext <- lev
}
} else if (identical(strip.names, TRUE)) {
if (is.double(lev)) {
lgtext <- paste(v$meta$by, round(lev, 3), sep=" : ")
} else {
lgtext <- paste(v$meta$by, lev, sep=" : ")
}
} else {
lgtext <- strip.names
}
toplegend(lgtext, col=line.args$col, lwd=line.args$lwd, lty=line.args$lty, ncol=min(length(lev), 5))
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregOverlayPlot.R
|
visregPanel <- function(x, y, subscripts, lframe, lresids, partial, band, rug, top, fill.par, ...) {
if (band) {
poly.args <- list(x=c(lframe$xx[subscripts], rev(lframe$xx[subscripts])), y=c(lframe$lwr[subscripts], rev(lframe$upr[subscripts])), subscripts=subscripts, col="gray85", border=F)
if (length(fill.par)) poly.args[names(fill.par)] <- fill.par
FUN <- getFromNamespace('panel.polygon', 'lattice')
do.call(FUN, poly.args)
}
current.level <- lframe$by[subscripts][1]
if (!partial) {
lattice::panel.xyplot(x, y, subscripts=subscripts,...)
} else {
if (top=='line') {
lattice::panel.points(lresids$x[lresids$by==current.level], lresids$r[lresids$by==current.level])
lattice::panel.xyplot(x, y, subscripts=subscripts,...)
} else {
lattice::panel.xyplot(x, y, subscripts=subscripts,...)
lattice::panel.points(lresids$x[lresids$by==current.level], lresids$r[lresids$by==current.level])
}
}
if (rug==1) lattice::panel.rug(lresids$x[lresids$by==current.level], lwd=1)
if (rug==2) {
lattice::panel.rug(lresids$x[lresids$by==current.level & !lresids$pos], lwd=1)
lattice::panel.rug(lresids$x[lresids$by==current.level & lresids$pos], regular=FALSE, lwd=1)
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregPanel.R
|
visregPlot <- function(v, partial, rug, band, whitespace, top, line.par, fill.par, points.par, ...) {
## Setup
x <- v$res[, v$meta$x]
y <- v$res$visregRes
xx <- v$fit[, v$meta$x]
yy <- v$fit$visregFit
lwr <- v$fit$visregLwr
upr <- v$fit$visregUpr
xlim <- if (is.factor(xx)) c(0, 1) else range(xx)
ylab <- if (is.null(v$meta$yName)) paste("f(", v$meta$x, ")", sep="") else v$meta$yName
if (partial && sum(!is.na(y))>0) {
ylim <- range(c(y, lwr, upr), na.rm=TRUE)
} else if (band) {
ylim <- range(c(yy, lwr, upr), na.rm=TRUE)
} else {
ylim <- range(yy)
}
plot.args <- list(x=1, y=1, ylim=ylim, xlab=v$meta$x, ylab=ylab, type="n", xlim=xlim, xaxt=ifelse(is.factor(xx),'n','s'), las=1)
new.args <- list(...)
if (length(new.args)) plot.args[names(new.args)] <- new.args
do.call("plot", plot.args)
if (is.factor(xx)) {
factorPlot(v, partial, band, rug, whitespace, top, line.par, fill.par, points.par, ...)
if (!("xaxt" %in% names(new.args) && new.args$xaxt=="n")) factorAxis(x, whitespace, new.args)
} else {
if (band) {
fill.args <- list(x=c(xx, rev(xx)), y=c(lwr, rev(upr)), col="gray85", border=F)
if (length(fill.par)) fill.args[names(fill.par)] <- fill.par
do.call("polygon", fill.args)
}
line.args <- list(x=xx, y=yy, lwd=3, lty=1, col="#008DFFFF")
if (length(line.par)) line.args[names(line.par)] <- line.par
if (!partial) {
do.call("lines", line.args)
} else {
points.args <- list(x=x, y=y, pch=19, cex=0.4, col="gray50")
if (length(points.par)) points.args[names(points.par)] <- points.par
if (top == 'line') {
do.call("points", points.args)
do.call("lines", line.args)
} else {
do.call("lines", line.args)
do.call("points", points.args)
}
}
if (rug==1) rug(x, side=1)
if (rug==2) {
rug(x[!v$res$visregPos], side=1)
rug(x[v$res$visregPos], side=3)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregPlot.R
|
visregPred <- function(fit, Data, se.fit=FALSE, ...) {
predict.args <- list(object=fit, newdata=Data)
if (inherits(fit, "lme")) predict.args$level <- 0
if (inherits(fit, "merMod")) predict.args$re.form <- NA
if (inherits(fit, "rq")) predict.args$interval <- "confidence"
if (inherits(fit, "svm")) predict.args$probability <- TRUE
if (inherits(fit, "multinom") | inherits(fit, "polr")) predict.args$type <- "probs"
if (inherits(fit, "gbm")) predict.args$n.trees <- length(fit$trees)
if (inherits(fit, "betareg")) predict.args$type <- "link"
dots <- list(...)
if (length(dots)) predict.args[names(dots)] <- dots
if (se.fit) {
if (inherits(fit, "mlm")) {
p <- list(fit = suppressWarnings(do.call("predict", predict.args)), se.fit = se.mlm(fit, newdata=Data))
} else if (inherits(fit, "randomForest") && fit$type=="classification") {
predict.args$type <- "prob"
P <- suppressWarnings(do.call("predict", predict.args))
p <- list(fit=P[,2], se.fit=NA)
} else if (inherits(fit, "loess")) {
predict.args$se <- TRUE
p <- suppressWarnings(do.call("predict", predict.args))
} else {
predict.args$se.fit <- TRUE
p <- suppressWarnings(do.call("predict", predict.args))
}
} else {
if (inherits(fit, "randomForest") && fit$type=="classification") {
p <- predict(fit, type="prob")[,2]
} else if (inherits(fit, 'rq')) {
p <- suppressWarnings(do.call("predict", predict.args))[,1]
} else {
p <- suppressWarnings(do.call("predict", predict.args))
}
}
if (inherits(fit, "svm") && fit$type < 3) p <- attr(p, "probabilities")
p
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregPred.R
|
visregResid <- function(fit) {
if (inherits(fit, "randomForest")) {
if (fit$type=="regression") rr <- fit$y - fit$predicted
if (fit$type=="classification") {
P <- predict(fit, type="prob")
rr <- (fit$y==colnames(P)[2]) - P[,2]
}
} else if (inherits(fit, 'coxph')) {
rr <- residuals(fit, type='deviance')
} else if (inherits(fit, 'gamlss')) {
rr <- residuals(fit, what='mu')
} else {
rr <- residuals(fit)
}
if (!is.matrix(rr) & length(rr)>0) rr <- rr[!is.na(rr)]
rr
}
|
/scratch/gouwar.j/cran-all/cranData/visreg/R/visregResid.R
|
## ---- include=FALSE-----------------------------------------------------------
library(visreg)
knitr::opts_knit$set(aliases=c(h = 'fig.height', w = 'fig.width'))
## -----------------------------------------------------------------------------
fit <- lm(Ozone ~ Solar.R + Wind + Temp, data=airquality)
## ---- h=5, w=5----------------------------------------------------------------
visreg(fit, "Wind")
## -----------------------------------------------------------------------------
airquality$Heat <- cut(airquality$Temp, 3, labels=c("Cool","Mild","Hot"))
fit <- lm(Ozone ~ Solar.R + Wind*Heat, data=airquality)
## ---- h=4, w=9, out.width='100%'----------------------------------------------
visreg(fit, "Wind", by="Heat")
## ---- h=5, w=5----------------------------------------------------------------
visreg(fit, "Wind", by="Heat", overlay=TRUE)
## ---- h=5, w=6----------------------------------------------------------------
fit <- lm(Ozone ~ poly(Wind, 2)*poly(Temp, 2), data=airquality)
visreg2d(fit, "Wind", "Temp")
|
/scratch/gouwar.j/cran-all/cranData/visreg/inst/doc/quick-start.R
|
---
title: "Quick start guide for visreg"
output:
rmarkdown::html_vignette:
css: vignette.css
vignette: >
%\VignetteIndexEntry{Quick start guide}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include=FALSE}
library(visreg)
knitr::opts_knit$set(aliases=c(h = 'fig.height', w = 'fig.width'))
```
This guide is intended to briefly demonstrate the basic usage of `visreg`.
For details on `visreg` syntax and how to use it, see:
* The online documentation at <http://pbreheny.github.io/visreg> contains many examples of visreg plots and the code to create them.
* [Breheny P and Burchett W (2017). Visualization of Regression Models Using visreg. *The R Journal*, 9: 56-71.](https://journal.r-project.org/archive/2017/RJ-2017-046/index.html)
* The R help files `?visreg`, `?plot.visreg`, and `?visreg2d`
The website focuses more on syntax, options, and user interface, while the paper goes into more depth regarding the statistical details.
The basic idea of visreg is that you fit some sort of regression model and visreg provides a convenient interface for visualizing it. Let's fit the following model:
```{r}
fit <- lm(Ozone ~ Solar.R + Wind + Temp, data=airquality)
```
We can then visualize what the model says about the relationship between the outcome and, say, wind, with:
```{r, h=5, w=5}
visreg(fit, "Wind")
```
The plot displays (a) the model's estimated relationship between wind and ozone, (b) a confidence band about that estimate, and (c) the partial residuals, so that one can assess model fit.
`visreg` correctly displays factors, transformations, etc., and has many options to produce many types of plots. As another example, suppose the model contains an interaction:
```{r}
airquality$Heat <- cut(airquality$Temp, 3, labels=c("Cool","Mild","Hot"))
fit <- lm(Ozone ~ Solar.R + Wind*Heat, data=airquality)
```
Visreg can plot cross-sections of this fit, either in separate panels:
```{r, h=4, w=9, out.width='100%'}
visreg(fit, "Wind", by="Heat")
```
Or overlaid on top of one another:
```{r, h=5, w=5}
visreg(fit, "Wind", by="Heat", overlay=TRUE)
```
Or as a two-dimensional filled contour plot (level plot):
```{r, h=5, w=6}
fit <- lm(Ozone ~ poly(Wind, 2)*poly(Temp, 2), data=airquality)
visreg2d(fit, "Wind", "Temp")
```
`visreg` is not limited to linear regression models. It can be used with virtually any type of model in `R` that provides generic functions for `model.frame` and `predict`, such as `glm`, `coxph`, `rlm`, `gam`, `locfit`, `quantreg`, `gbm`, `randomForest`, etc. See the [homepage](http://pbreheny.github.io/visreg) for additional examples with other types of models. If there is a model that you think should work with `visreg` but doesn't, please [open an issue](https://github.com/pbreheny/visreg/issues).
|
/scratch/gouwar.j/cran-all/cranData/visreg/inst/doc/quick-start.Rmd
|
---
title: "Quick start guide for visreg"
output:
rmarkdown::html_vignette:
css: vignette.css
vignette: >
%\VignetteIndexEntry{Quick start guide}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include=FALSE}
library(visreg)
knitr::opts_knit$set(aliases=c(h = 'fig.height', w = 'fig.width'))
```
This guide is intended to briefly demonstrate the basic usage of `visreg`.
For details on `visreg` syntax and how to use it, see:
* The online documentation at <http://pbreheny.github.io/visreg> contains many examples of visreg plots and the code to create them.
* [Breheny P and Burchett W (2017). Visualization of Regression Models Using visreg. *The R Journal*, 9: 56-71.](https://journal.r-project.org/archive/2017/RJ-2017-046/index.html)
* The R help files `?visreg`, `?plot.visreg`, and `?visreg2d`
The website focuses more on syntax, options, and user interface, while the paper goes into more depth regarding the statistical details.
The basic idea of visreg is that you fit some sort of regression model and visreg provides a convenient interface for visualizing it. Let's fit the following model:
```{r}
fit <- lm(Ozone ~ Solar.R + Wind + Temp, data=airquality)
```
We can then visualize what the model says about the relationship between the outcome and, say, wind, with:
```{r, h=5, w=5}
visreg(fit, "Wind")
```
The plot displays (a) the model's estimated relationship between wind and ozone, (b) a confidence band about that estimate, and (c) the partial residuals, so that one can assess model fit.
`visreg` correctly displays factors, transformations, etc., and has many options to produce many types of plots. As another example, suppose the model contains an interaction:
```{r}
airquality$Heat <- cut(airquality$Temp, 3, labels=c("Cool","Mild","Hot"))
fit <- lm(Ozone ~ Solar.R + Wind*Heat, data=airquality)
```
Visreg can plot cross-sections of this fit, either in separate panels:
```{r, h=4, w=9, out.width='100%'}
visreg(fit, "Wind", by="Heat")
```
Or overlaid on top of one another:
```{r, h=5, w=5}
visreg(fit, "Wind", by="Heat", overlay=TRUE)
```
Or as a two-dimensional filled contour plot (level plot):
```{r, h=5, w=6}
fit <- lm(Ozone ~ poly(Wind, 2)*poly(Temp, 2), data=airquality)
visreg2d(fit, "Wind", "Temp")
```
`visreg` is not limited to linear regression models. It can be used with virtually any type of model in `R` that provides generic functions for `model.frame` and `predict`, such as `glm`, `coxph`, `rlm`, `gam`, `locfit`, `quantreg`, `gbm`, `randomForest`, etc. See the [homepage](http://pbreheny.github.io/visreg) for additional examples with other types of models. If there is a model that you think should work with `visreg` but doesn't, please [open an issue](https://github.com/pbreheny/visreg/issues).
|
/scratch/gouwar.j/cran-all/cranData/visreg/vignettes/quick-start.Rmd
|
#' Standardize column names
#'
#' @param data input data frame
#' @param col.event event column name (optional)
#' @param col.start name of col.start column, default: "start"
#' @param col.end name of end column (optional)
#' @param col.group name of group column (optional)
#' @param col.tooltip column name of tooltips (optional)
#'
#' @return of the data frame prepared for plotting
#'
#' @keywords internal
#' @noRd
#'
#' @examples
#' \dontrun{
#' fix_columns(data.frame(
#' event = 1:4,
#' col.start = c("2019-01-01", "2019-01-10"),
#' col.end = c("2019-01-01", "2019-01-10"),
#' col.event = "event", col.start = "start", end = "end",
#' col.group = "group", col.tooltip = "tooltip"
#' ))
#' }
#'
fix_columns <- function(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor, col.tooltip) {
# col.event -> "event"
data$event <- data[[col.event]]
# col.start and col.end -> "start" and "end"
data$start <- data[[col.start]]
if (!is.null(col.end) && col.end %in% names(data)){
data$end <- data[[col.end]]
}else{
data$end <- data$start
}
data$start <- as.POSIXct(data$start)
data$end <- as.POSIXct(data$end)
# col.group -> "group"
if (col.group %in% names(data)){
data$group <- data[[col.group]]
}else{
data$group <- ""
}
data <- set_colors(data, col.color, col.fontcolor)
# convert all but start, end, & group to character
for (col in names(data)[!names(data) %in% c("start", "end", 'group')])
data[[col]] <- as.character(data[[col]])
# sort out missing end dates
if (any(is.na(data$end)))
data$end[is.na(data$end)] <- data$start[is.na(data$end)]
# remove leading and trailing whitespaces
data$event <- trimws(data$event)
data_group_character <- trimws(as.character(data$group))
if(is.factor(data$group)){
data$group <- factor(data_group_character, levels = unique(trimws(levels(data$group))))
}else{
data$group <- data_group_character
}
# col.tooltip -> "tooltip"
if (!is.null(col.tooltip) && col.tooltip %in% names(data)) {
data$tooltip <- data[[col.tooltip]]
} else {
data$tooltip <- ifelse(data$start == data$end,
paste0("<b>", data$event, ": ", data$start, "</b>"),
paste0("<b>", data$event, "</b><br>from <b>",
data$start, "</b> to <b>", data$end, "</b>")
)
}
data$label <- data$event
return(data[, c("event", "start", "end", "group", "tooltip", "label", "col", "fontcol")])
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/fix_columns.R
|
#' Create a Timeline rendered by ggplot2
#'
#' Provide a data frame with event data to create a static timeline plot created by ggplot2.
#' Simplest drawable dataframe can have columns `event` and `start`.
#'
#' @param data \code{data.frame} that contains the data to be visualized
#' @param col.event (optional, character) the column name in \code{data} that contains event
#' names. Default: \emph{event}.
#' @param col.start (optional, character) the column name in \code{data} that contains start
#' dates. Default: \emph{start}.
#' @param col.end (optional, character) the column name in \code{data} that contains end dates.
#' Default: \emph{end}.
#' @param col.group (optional, character) the column name in \code{data} to be used for
#' grouping. Default: \emph{group}.
#' @param col.color (optional, character) the column name in \code{data} that contains colors
#' for events. Default: \emph{color}, if not present, colors are chosen via
#' \code{RColorBrewer}.
#' @param col.fontcolor (optional, character) the column name in \code{data} that contains the
#' font color for event labels. Default: \emph{fontcolor}, if not present,
#' color will be black.
#' @param optimize_y (optional, logical) distribute events on y-axis by smart heuristic (default),
#' otherwise use order of input data.
#' @param linewidth (optional, numeric) the linewidth (in pixel) for the events (typically used for
#' large amount of parallel events). Default: heuristic value.
#' @param title (optional, character) the title to be shown on top of the timeline.
#' Default: \code{NULL}.
#' @param show_labels (optional, boolean) choose whether or not event labels shall be
#' visible. Default: \code{TRUE}.
#' @param background_lines (optional, integer) the number of vertical lines to draw in the background to demonstrate structure (default: heuristic).
#' @param ... for deprecated arguments up to vistime 1.1.0 (like events, colors, ...)
#' @seealso Functions \code{?vistime} and \code{?hc_vistime} for different charting engines (Plotly and Highcharts).
#' @export
#' @return \code{gg_vistime} returns an object of class \code{gg} and \code{ggplot}.
#' @examples
#' # presidents and vice presidents
#' pres <- data.frame(
#' Position = rep(c("President", "Vice"), each = 3),
#' Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
#' start = c("1789-03-29", "1797-02-03", "1801-02-03"),
#' end = c("1797-02-03", "1801-02-03", "1809-02-03"),
#' color = c("#cbb69d", "#603913", "#c69c6e")
#' )
#'
#' gg_vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
#'
#' \dontrun{
#' # ------ It is possible to change all attributes of the timeline using ggplot2::theme()
#' data <- read.csv(text="event,start,end
#' Phase 1,2020-12-15,2020-12-24
#' Phase 2,2020-12-23,2020-12-29
#' Phase 3,2020-12-28,2021-01-06
#' Phase 4,2021-01-06,2021-02-02")
#'
#' p <- gg_vistime(data, optimize_y = T, col.group = "event", title = "ggplot customization example")
#'
#' library(ggplot2)
#' p + theme(
#' plot.title = element_text(hjust = 0, size=30),
#' axis.text.x = element_text(size = 30, color = "violet"),
#' axis.text.y = element_text(size = 30, color = "red", angle = 30),
#' panel.border = element_rect(linetype = "dashed", fill=NA),
#' panel.background = element_rect(fill = 'green')) +
#' coord_cartesian(ylim = c(0.7, 3.5))
#' }
gg_vistime <- function(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
optimize_y = TRUE, linewidth = NULL, title = NULL,
show_labels = TRUE, background_lines = NULL, ...) {
checked_dat <- validate_input(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor, col.tooltip = NULL, optimize_y, linewidth, title,
show_labels, background_lines, list(...))
cleaned_dat <- vistime_data(checked_dat$data, checked_dat$col.event, checked_dat$col.start,
checked_dat$col.end, checked_dat$col.group, checked_dat$col.color,
checked_dat$col.fontcolor, checked_dat$col.tooltip, optimize_y)
total <- plot_ggplot(cleaned_dat, linewidth, title, show_labels, background_lines)
return(total)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/gg_vistime.R
|
#' Create a Timeline rendered by Highcharts.js
#'
#' Provide a data frame with event data to create a visual and interactive timeline plot
#' rendered by Highcharts. Simplest drawable dataframe can have columns `event` and `start`.
#' This feature is facilitated by the `highcharter` package, so, this package needs to be
#' installed before attempting to produce any `hc_vistime()` output.
#'
#' @param data \code{data.frame} that contains the data to be visualized
#' @param col.event (optional, character) the column name in \code{data} that contains event
#' names. Default: \emph{event}.
#' @param col.start (optional, character) the column name in \code{data} that contains start
#' dates. Default: \emph{start}.
#' @param col.end (optional, character) the column name in \code{data} that contains end dates.
#' Default: \emph{end}.
#' @param col.group (optional, character) the column name in \code{data} to be used for
#' grouping. Default: \emph{group}.
#' @param col.color (optional, character) the column name in \code{data} that contains colors
#' for events. Default: \emph{color}, if not present, colors are chosen via
#' \code{RColorBrewer}.
#' @param col.tooltip (optional, character) the column name in \code{data} that contains the
#' mouseover tooltips for the events. Default: \emph{tooltip}, if not present,
#' then tooltips are built from event name and date.
#' @param optimize_y (optional, logical) distribute events on y-axis by smart heuristic (default),
#' otherwise use order of input data.
#' @param title (optional, character) the title to be shown on top of the timeline.
#' Default: \code{NULL}.
#' @param show_labels (optional, boolean) choose whether or not event labels shall be
#' visible. Default: \code{TRUE}.
#' @param ... for deprecated arguments up to vistime 1.1.0 (like events, colors, ...)
#' @seealso Functions \code{?vistime} and \code{?gg_vistime} for different charting engines (Plotly and ggplot2).
#' @export
#' @return \code{hc_vistime} returns an object of class \code{highchart} and \code{htmlwiget}
#' @examples
#' # presidents and vice presidents
#' pres <- data.frame(
#' Position = rep(c("President", "Vice"), each = 3),
#' Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
#' start = c("1789-03-29", "1797-02-03", "1801-02-03"),
#' end = c("1797-02-03", "1801-02-03", "1809-02-03"),
#' color = c("#cbb69d", "#603913", "#c69c6e")
#' )
#'
#' hc_vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
#' #'
#' \dontrun{
#' # ------ It is possible to change all attributes of the timeline using highcharter::hc_*():
#' data <- read.csv(text="event,start,end
#' Phase 1,2020-12-15,2020-12-24
#' Phase 2,2020-12-23,2020-12-29
#' Phase 3,2020-12-28,2021-01-06
#' Phase 4,2021-01-06,2021-02-02")
#'
#' library(highcharter)
#' p <- hc_vistime(data, optimize_y = T, col.group = "event",
#' title = "Highcharts customization example")
#' p %>% hc_title(style = list(fontSize=30)) %>%
#' hc_yAxis(labels = list(style = list(fontSize=30, color="violet"))) %>%
#' hc_xAxis(labels = list(style = list(fontSize=30, color="red"), rotation=30)) %>%
#' hc_chart(backgroundColor = "lightgreen")
#' }
hc_vistime <- function(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.tooltip = "tooltip",
optimize_y = TRUE, title = NULL,
show_labels = TRUE, ...) {
if (!requireNamespace("highcharter", quietly = TRUE)) {
stop("The `highcharter` package is required for creating `hc_vistime()` objects.",
call. = FALSE)
}
checked_dat <- validate_input(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor = NULL, col.tooltip, optimize_y, linewidth = 0, title,
show_labels, background_lines = 0, list(...))
cleaned_dat <- vistime_data(checked_dat$data, checked_dat$col.event, checked_dat$col.start,
checked_dat$col.end, checked_dat$col.group, checked_dat$col.color,
checked_dat$col.fontcolor, checked_dat$col.tooltip, optimize_y)
total <- plot_highchart(cleaned_dat, title, show_labels)
return(total)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/hc_vistime.R
|
#' Plot the prepared data into ggplot2 plot
#'
#' @param data the data frame to be plotted (ranges + events), e.g. generated by `visime_data`
#' @param linewidth the width in pixel for the range lines
#' @param title the title for the plot
#' @param show_labels boolean, show labels on events or not
#' @param background_lines number of grey background lines to draw
#' @importFrom rlang .data
#' @importFrom ggplot2 aes
#' @importFrom ggplot2 ggtitle
#' @importFrom ggplot2 labs
#' @importFrom ggplot2 scale_y_continuous
#' @importFrom ggplot2 theme_classic
#' @importFrom ggplot2 theme
#' @importFrom ggplot2 element_line
#' @importFrom ggplot2 element_text
#' @importFrom ggplot2 element_blank
#' @importFrom ggplot2 element_rect
#' @importFrom ggplot2 coord_cartesian
#' @importFrom ggplot2 geom_hline
#' @importFrom ggplot2 geom_vline
#' @importFrom ggplot2 geom_segment
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_text
#' @importFrom ggplot2 ggplot
#' @importFrom ggrepel geom_text_repel
#'
#' @return a ggplot object
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
#' plot_ggplot(data.frame(
#' event = 1:2, start = as.POSIXct(c("2019-01-01", "2019-01-10")),
#' end = as.POSIXct(c("2019-01-10", "2019-01-25")),
#' group = "", tooltip = "", col = "green", fontcol = "black",
#' subplot = 1, y = 1:2, label = 1:2
#' ), linewidth = 10, title = "A title", show_labels = TRUE, background_lines = 10
#' )
#' }
plot_ggplot <- function(data, linewidth, title, show_labels, background_lines) {
# 1. Prepare basic plot
y_ticks <- tapply(data$y, data$subplot, mean)
gg <- ggplot(data, aes(x = .data$start, y = .data$y, xend = .data$end, yend = .data$y, color = I(.data$col))) +
ggtitle(title) + labs(x = NULL, y = NULL) +
scale_y_continuous(breaks = y_ticks, labels = unique(data$group)) +
theme_classic() +
theme(
plot.title = element_text(hjust = 0.5),
axis.ticks.y = element_blank(),
axis.text.y = element_text(hjust = 1),
# line = element_blank(),
panel.background = element_rect(colour = "black", linetype = "solid")) +
coord_cartesian(ylim = c(0.5, max(data$y) + 0.5))
# 2. Add background vertical lines
if(is.null(background_lines)){
gg <- gg + theme(panel.grid.major.x = element_line(colour = "grey90"),
panel.grid.minor.x = element_line(colour = "grey90"))
}else{
gg <- gg + geom_vline(xintercept = seq(min(c(data$start, data$end)), max(c(data$start, data$end)),
length.out = round(background_lines) + 1), colour = "grey90")
}
# 3. Divide subplots with horizontal lines
gg <- gg + geom_hline(yintercept = c(setdiff(seq_len(max(data$y)), data$y)),
colour = "grey65")
# Plot ranges and events
lw <- ifelse(is.null(linewidth), min(30, 100/max(data$y)), linewidth) # 1->30, 2->30, 3->30, 4->25
range_dat <- data[data$start != data$end, ]
event_dat <- data[data$start == data$end, ]
gg <- gg +
geom_segment(data = range_dat, linewidth = lw) +
geom_point(data = event_dat, mapping = aes(fill = I(.data$col)),
shape = 21, size = 0.7 * lw, colour = "black", stroke = 0.1)
# Labels for Ranges in center of range
ranges <- data[data$start != data$end, ]
ranges$start <- ranges$start + (ranges$end - ranges$start)/2
if(show_labels){
gg <- gg +
geom_text(mapping = aes(colour = I(.data$fontcol), label = .data$label), data = ranges) +
geom_text_repel(mapping = aes(colour = I(.data$fontcol), label = .data$label),
data = event_dat, direction = "y", segment.alpha = 0,
point.padding = grid::unit(0.75, "lines"))
#, nudge_y = rep_len(c(0.3,-0.3), nrow(event_dat)))
}
return(gg)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/plot_ggplot.R
|
#' Plot the prepared data into Highcharts.js plot
#'
#' @param data the data frame to be plotted (ranges + events), e.g. generated by `visime_data()`
#' @param title the title for the plot
#' @param show_labels boolean, show labels on events or not
#'
#' @return a plot object generated by `highchart`
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
#' plot_highchart(data.frame(
#' event = 1:2, start = as.POSIXct(c("2019-01-01", "2019-01-10")),
#' end = as.POSIXct(c("2019-01-10", "2019-01-25")),
#' group = "", tooltip = "", col = "green", fontcol = "black",
#' subplot = 1, y = 1:2, label = 1:2
#' ), title = "A title", show_labels = TRUE
#' )
#' }
plot_highchart <- function(data, title, show_labels){
# let an event be 1/50th of total timeline range
data$end <- with(data, ifelse(start != end, end, end + diff(range(c(start, end)))/50))
data$low <- 1000 * as.double(data$start)
data$high <- 1000 * as.double(data$end)
data$x <- max(data$y) - data$y + 1
data$color = data$col
cats <- round(tapply(data$y, data$group, mean))
y_vals <- names(sort(c(cats, setdiff(seq_len(max(data$y)), cats)), decreasing=TRUE))
highcharter::hc_chart(
highcharter::hc_title(
highcharter::hc_legend(
highcharter::hc_tooltip(
highcharter::hc_xAxis(
highcharter::hc_yAxis(
highcharter::hc_add_series(
highcharter::hc_chart(highcharter::highchart(), inverted =TRUE),
data, "columnrange",
dataLabels = list(enabled = show_labels, inside=T,
formatter = highcharter::JS("function () {return (this.y === this.point.low ? this.point.event : \"\")}"))),
type = "datetime"),
categories = c("", y_vals)),
crosshairs = TRUE, formatter = highcharter::JS("function () {return this.point.tooltip}")) ,
enabled=F),
text = title),
zoomType = "xy")
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/plot_highchart.R
|
#' Plot the prepared data into Plotly plot
#'
#' @param data the data frame to be plotted (ranges + events), e.g. generated by `visime_data`
#' @param linewidth the width in pixel for the range lines
#' @param title the title for the plot
#' @param show_labels boolean, show labels on events or not
#' @param background_lines number of grey background lines to draw (can be NULL)
#' @importFrom plotly plot_ly
#' @importFrom plotly layout
#' @importFrom plotly add_trace
#' @importFrom plotly add_text
#' @importFrom plotly add_markers
#' @importFrom plotly toRGB
#'
#' @return a plot object generated by `plot_ly`
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
#' plot_plotly(data.frame(
#' event = 1:2, start = as.POSIXct(c("2019-01-01", "2019-01-10")),
#' end = as.POSIXct(c("2019-01-10", "2019-01-25")),
#' group = "", tooltip = "", col = "green", fontcol = "black",
#' subplot = 1, y = 1:2, label = 1:2
#' ), linewidth = 10, title = "A title", show_labels = TRUE, background_lines = 10
#' )
#' }
plot_plotly <- function(data, linewidth, title, show_labels, background_lines) {
# 1. Prepare basic plot
p <- plot_ly(type = "scatter", mode = "lines")
y_ticks <- tapply(data$y, data$subplot, mean)
# 2. Divide subplots with horizontal lines
hline <- function(y = 0) list(type = "line", x0 = 0, x1 = 1, xref = "paper", y0 = y, y1 = y, line = list(color = "grey65", width = 0.5))
vline <- function(x = 0) list(type = "line", y0 = 0, y1 = 1, yref = "paper", x0 = x, x1 = x, line = list(color = "grey90", width = 0.1))
horizontal_lines <- lapply(setdiff(seq_len(max(data$y)), data$y), hline)
# 3. Add vertical lines
if(!is.null(background_lines)){
day_breaks <- as.POSIXct(seq(min(c(data$start, data$end)), max(c(data$start, data$end)),
length.out = round(background_lines) + 2), origin = "1970-01-01")
vertical_lines <- lapply(day_breaks, vline)
}else{
vertical_lines <- list()
}
p <- layout(p,
hovermode = "closest",
plot_bgcolor = "#FCFCFC",
title = title,
shapes = append(vertical_lines, horizontal_lines),
# Axis options:
xaxis = list(linewidth = 1, mirror = TRUE,
showgrid = is.null(background_lines),
gridcolor = "grey90", title = ""),
yaxis = list(
linewidth = 1, mirror = TRUE,
range = c(0, max(data$y) + 1),
showgrid = F, title = "",
tickmode = "array",
tickvals = y_ticks,
ticktext = as.character(unique(data$group))
)
)
# 4. plot ranges
range_dat <- data[data$start != data$end, ]
lw <- ifelse(is.null(linewidth), min(100, 300/max(data$y)), linewidth) # 1-> 100, 2->100, 3->100, 4->70
if(nrow(range_dat) > 0){
# draw ranges piecewise
for (i in seq_len(nrow(range_dat))) {
toAdd <- range_dat[i, ]
p <- add_trace(p,
x = c(toAdd$start, toAdd$end), # von, bis
y = toAdd$y,
line = list(color = toAdd$col, width = lw),
showlegend = F,
hoverinfo = "text",
text = toAdd$tooltip
)
# add annotations or not
if (show_labels) {
p <- add_text(p,
x = toAdd$start + (toAdd$end - toAdd$start) / 2, # in der Mitte
y = toAdd$y,
textfont = list(family = "Arial", size = 14, color = toRGB(toAdd$fontcol)),
textposition = "center",
showlegend = F,
text = toAdd$label,
hoverinfo = "none"
)
}
}
}
# 5. plot events
event_dat <- data[data$start == data$end, ]
if(nrow(event_dat) > 0){
# alternate y positions for event labels
event_dat$labelY <- event_dat$y + 0.5 * rep_len(c(1, -1), nrow(event_dat))
# add all the markers for this Category
p <- add_markers(p,
x = event_dat$start, y = event_dat$y,
marker = list(
color = event_dat$col, size = 0.7 * lw, symbol = "circle",
line = list(color = "black", width = 1)
),
showlegend = F, hoverinfo = "text", text = event_dat$tooltip
)
# add annotations or not
if (show_labels) {
p <- add_text(p,
x = event_dat$start, y = event_dat$labelY, textfont = list(family = "Arial", size = 14,
color = toRGB(event_dat$fontcol)),
textposition ="center", showlegend = F, text = event_dat$label, hoverinfo = "none"
)
}
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/plot_plotly.R
|
#' Set column col for event colors and column fontcol for label colors
#'
#' @param data the data frame containing event data
#' @param col.color name of the event color column
#' @param col.fontcolor name of the fontcolor column
#'
#' @return same data frame as input, but with columns \code{col} and \code{fontcol} filled with color codes or names.
#' @keywords internal
#' @noRd
set_colors <- function(data, col.color, col.fontcolor) {
if (!is.null(col.color) && col.color %in% names(data)){
data$col <- trimws(data[[col.color]])
}else{
palette <- "Set3"
data$col <- rep(RColorBrewer::brewer.pal(min(11, max(3, nrow(data))), palette), nrow(data))[1:nrow(data)]
}
if (!is.null(col.fontcolor) && col.fontcolor %in% names(data)){
data$fontcol <- trimws(data[[col.fontcolor]])
} else {
data$fontcol <- "black"
}
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/set_colors.R
|
#' Order groups for plotting
#'
#' We determine the subplot as follows: Groups appear in order of appearance in the data, data withing groups as well
#'
#' @param data the data frame with ranges and events
#'
#' @return data with additional numeric column "subplot"
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
#' set_order(data.frame(
#' event = 1:4, start = c("2019-01-01", "2019-01-10"),
#' end = c("2019-01-01", "2019-01-10"), group = "", stringsAsFactors = F))
#' set_order(data.frame(
#' event = 1:4, start = c("2019-01-01", "2019-01-10"),
#' end = c("2019-01-01", "2019-01-10"), group = 1:2, stringsAsFactors = F))
#' set_order(data.frame(
#' event = 1:3, start = c("2019-01-01", "2019-01-10", "2019-01-01"),
#' end = c("2019-01-10", "2019-01-20", "2019-01-10"),
#' group = c(1, 2, 1), stringsAsFactors = F))
#' }
set_order <- function(data) {
if (!is.factor(data$group)) {
# set group order to order of appearance using factor levels.
data$group <- factor(data$group, levels = unique(data$group))
}
data <- data[order(data$group),] # bring same groups together
data$subplot <- as.integer(data$group)
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/set_order.R
|
#' Function to distribute events in y-space
#' if optimize_y flag is TRUE, then heuristic to distribute events and ranges in y space is used
#' if optimize_y flag is FALSE, then events are distributed according to start column, each incremented by 1 on y-axis (= gantt chart)
#'
#' Instead of naive "always increment by 1" approach, we are using a more sophisticated method to use plot space efficiently if optimize_y = TRUE
#'
#' @param data the data frame with data to be distributed, has to have \code{start}, \code{end} and \code{subplot} column
#' @param optimize_y flag whether to distribute events optimally or naively
#'
#' @return the data frame enriched with numeric \code{y} column
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
# set_y_values(data.frame(
# event = 1:4, start = c("2019-01-01", "2019-01-10"),
# end = c("2019-01-01", "2019-01-10"), subplot = 1, stringsAsFactors = F),
# optimize_y = TRUE)
#' }
set_y_values <- function(data, optimize_y) {
if(optimize_y) data <- data[order(data$subplot, data$start, as.integer(factor(data$event, levels = unique(data$event)))), ] # order by group and start (and event if tie, as in order of data)
row.names(data) <- 1:nrow(data)
# decide y-position for each group, then elevate them at the end
for (i in unique(data$subplot)) {
# subset data for this group
thisGroup <- data[data$subplot == i, ]
thisGroup$y <- 0
if(optimize_y){
for (row in seq_len(nrow(thisGroup))) {
toAdd <- thisGroup[row, ]
# Algorithm: for each y, check for conflicts. If none on this y has conflicts, take it. Increase it otherwise
for (candidate_y in 0:nrow(thisGroup) + 1){
all_on_current_y <- thisGroup[thisGroup$y == candidate_y, ][-row,]
conflict_seen <- FALSE
for(j in seq_len(nrow(all_on_current_y))){
# conflict if starts or ends are equal or one start is between other start-end or end between other start-end
conflict_seen <- conflict_seen |
# case 1: both are events or begin/end is equal
toAdd$start == all_on_current_y[j,"start"] | toAdd$end == all_on_current_y[j,"end"] |
# case 2: toAdd = event, j = range
toAdd$start == toAdd$end & toAdd$start >= all_on_current_y[j,"start"] & toAdd$start <= all_on_current_y[j,"end"] |
# case 3: toAdd = range, j = event
all_on_current_y[j,"start"] == all_on_current_y[j,"end"] & toAdd$start <= all_on_current_y[j,"start"] & toAdd$end >= all_on_current_y[j,"end"] |
# case 4: both are ranges
all_on_current_y[j,"start"] != all_on_current_y[j,"end"] & toAdd$start != toAdd$end &
# case 4.1: start inside other range
(toAdd$start > all_on_current_y[j,"start"] & toAdd$start < all_on_current_y[j,"end"] |
# case 4.2: end insider other range
toAdd$end > all_on_current_y[j,"start"] & toAdd$end < all_on_current_y[j,"end"])
}
if (!isTRUE(conflict_seen)) {
thisGroup$y[row] <- candidate_y
break
}else{
next
}
}
}
}else{
thisGroup$y <- seq_len(nrow(thisGroup))
}
data[data$subplot == i, "y"] <- max(thisGroup$y) - thisGroup$y + 1 # ensure events from top to bottom
}
data$y <- as.numeric(data$y) # to ensure plotting goes smoothly
data$y[is.na(data$y)] <- max(data$y[!is.na(data$y)]) + 1 # just in case
adds <- cumsum(rev(unname(by(data, data$subplot, function(subplot) max(subplot$y)))))
adds <- c(0, adds[-length(adds)] + seq_len(length(adds)-1))
y_add <- rev(rep(adds, times = rev(table(data$subplot))))
data$y <- data$y + y_add
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/set_y_values.R
|
#' Validate input data
#'
#' @param data the data
#' @param col.event event column name
#' @param col.start start dates column
#' @param col.end end dates column
#' @param col.group group column name
#' @param col.tooltip tooltip column name
#' @param linewidth width of range lines
#' @param title plot title
#' @param show_labels logical
#' @param background_lines interval of gray background lines
#' @importFrom assertthat is.string
#' @importFrom assertthat is.flag
#' @importFrom assertthat assert_that
#' @importFrom assertthat is.time
#'
#' @return list of the data frame and column arguments, or an error
#' @keywords internal
#' @noRd
#' @examples
#' \dontrun{
#' validate_input(data.frame(event = 1:2, start = c("2019-01-01", "2019-01-10")),
#' col.event = "event", col.start = "start", col.end = "end", col.group = "group", col.tooltip = NULL,
#' optimize_y = TRUE, linewidth = NULL, title = NULL, show_labels = TRUE,
#' background_lines = 10
#' )
#' }
validate_input <- function(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor, col.tooltip, optimize_y, linewidth, title,
show_labels, background_lines, .dots) {
if("events" %in% names(.dots)){
.Deprecated(new = "col.event", old = "events")
col.event <- .dots$events
.dots$events <- NULL
}
if("start" %in% names(.dots)){
.Deprecated(new = "col.start", old = "start")
col.start <- .dots$start
.dots$start <- NULL
}
if("end" %in% names(.dots)){
.Deprecated(new = "col.end", old = "end")
col.end <- .dots$end
.dots$end <- NULL
}
if("groups" %in% names(.dots)){
.Deprecated(new = "col.group", old = "groups")
col.group <- .dots$groups
.dots$groups <- NULL
}
if("colors" %in% names(.dots)){
.Deprecated(new = "col.color", old = "colors")
col.color <- .dots$colors
.dots$colors <- NULL
}
if("fontcolors" %in% names(.dots)){
.Deprecated(new = "col.fontcolor", old = "fontcolors")
col.fontcolor <- .dots$fontcolors
.dots$fontcolors <- NULL
}
if("tooltips" %in% names(.dots)){
.Deprecated(new = "col.tooltip", old = "tooltips")
col.tooltip <- .dots$tooltips
.dots$tooltips <- NULL
}
if("lineInterval" %in% names(.dots)){
.Deprecated(new = "background_lines", old = "lineInterval")
.dots$lineInterval <- NULL
}
if("showLabels" %in% names(.dots)){
.Deprecated(new = "show_labels", old = "showLabels")
.dots$showLabels <- NULL
}
if(length(.dots) > 0) message("The following unexpected arguments were ignored: ", paste(names(.dots), collapse = ", "))
assert_that(is.string(col.start))
assert_that(is.string(col.end))
assert_that(is.string(col.event))
assert_that(is.string(col.group))
if(!is.null(col.tooltip)) assert_that(is.string(col.tooltip))
assert_that(is.flag(optimize_y))
# missing if called from vistime_data
if(!missing(linewidth) && !is.null(linewidth)) assert_that(is.numeric(linewidth))
if(!missing(title) && !is.null(title)) assert_that(is.string(title))
if(!missing(show_labels)) assert_that(is.flag(show_labels))
if(!missing(background_lines) && !is.null(background_lines)) assert_that(is.numeric(background_lines))
df <- tryCatch(as.data.frame(data, stringsAsFactors = F), error = function(e) assert_that(is.data.frame(data)))
assert_that(is.data.frame(df))
if (!col.start %in% names(df))
stop("Column '", col.start, "' not found in data")
if (sum(!is.na(df[[col.start]])) == 0)
stop(paste0("error in column '", col.start, "': Please provide at least one point in time"))
df[[col.start]] <- tryCatch(as.POSIXct(df[[col.start]]), error = function(e) assert_that(is.time(df[[col.start]])))
assert_that(is.time(df[[col.start]]))
if(!is.null(df[[col.end]])){
df[[col.end]] <- tryCatch(as.POSIXct(df[[col.end]]), error = function(e) assert_that(is.time(df[[col.end]])))
assert_that(is.time(df[[col.end]]))
}
if (!col.event %in% names(df)){
message("Column '", col.event, "' not found in data. Defaulting to col.event='", col.start, "'")
col.event <- col.start
}
return(list(data = df, col.event = col.event, col.start = col.start, col.end = col.end,
col.group = col.group, col.color = col.color, col.fontcolor = col.fontcolor,
col.tooltip = col.tooltip))
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/validate_input.R
|
#' Pretty timelines in R
#'
#' @name vistime-package
#' @docType package
#' @title vistime: Pretty Timeline Charts in R
#' @author Sandro Raabe \email{[email protected]}
#' @keywords timeline gantt timelines vistime plotly posix ggplot2
#' @description A library for creating time based charts, like Gantt or timelines. Possible outputs include ggplot2 diagrams, plotly.js graphs, Highcharts.js widgets and data.frames. Results can be used in the RStudio viewer pane, in RMarkdown documents or in Shiny apps. In the interactive outputs created by vistime() and hc_vistime(), you can interact with the plot using mouse hover or zoom.
#' @seealso Useful links: \itemize{ \item \url{https://shosaco.github.io/vistime/} \item Report bugs at \url{https://github.com/shosaco/vistime/issues} }
NULL
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/vistime-package.R
|
#' Create a Timeline rendered by Plotly
#'
#' Provide a data frame with event data to create a visual and interactive timeline plot rendered by Plotly.
#' Simplest drawable dataframe can have columns `event` and `start`.
#'
#' @param data \code{data.frame} that contains the data to be visualized
#' @param col.event (optional, character) the column name in \code{data} that contains event
#' names. Default: \emph{event}.
#' @param col.start (optional, character) the column name in \code{data} that contains start
#' dates. Default: \emph{start}.
#' @param col.end (optional, character) the column name in \code{data} that contains end dates.
#' Default: \emph{end}.
#' @param col.group (optional, character) the column name in \code{data} to be used for
#' grouping. Default: \emph{group}.
#' @param col.color (optional, character) the column name in \code{data} that contains colors
#' for events. Default: \emph{color}, if not present, colors are chosen via
#' \code{RColorBrewer}.
#' @param col.fontcolor (optional, character) the column name in \code{data} that contains the
#' font color for event labels. Default: \emph{fontcolor}, if not present,
#' color will be black.
#' @param col.tooltip (optional, character) the column name in \code{data} that contains the
#' mouseover tooltips for the events. Default: \emph{tooltip}, if not present,
#' then tooltips are built from event name and date.
#' @param optimize_y (optional, logical) distribute events on y-axis by smart heuristic
#' (default), otherwise use order of input data.
#' @param linewidth (optional, numeric) the linewidth (in pixel) for the events
#' (typically used for large amount of parallel events). Default: heuristic value.
#' @param title (optional, character) the title to be shown on top of the timeline.
#' Default: \code{NULL}.
#' @param show_labels (optional, boolean) choose whether or not event labels shall be
#' visible. Default: \code{TRUE}.
#' @param background_lines (optional, integer) the number of vertical lines to draw in the
#' background to demonstrate structure (default: 10). Less means more memory-efficient plot.
#' @param ... for deprecated arguments up to vistime 1.1.0 (like events, colors, ...)
#' @seealso Functions \code{?hc_vistime} and \code{?gg_vistime} for different charting engines (Highcharts and ggplot2).
#' @export
#' @return \code{vistime} returns an object of class \code{plotly} and \code{htmlwidget}.
#' @examples
#' # presidents and vice presidents
#' pres <- data.frame(
#' Position = rep(c("President", "Vice"), each = 3),
#' Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
#' start = c("1789-03-29", "1797-02-03", "1801-02-03"),
#' end = c("1797-02-03", "1801-02-03", "1809-02-03"),
#' color = c("#cbb69d", "#603913", "#c69c6e"),
#' fontcolor = c("black", "white", "black")
#' )
#'
#' vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
#'
#'
#' \dontrun{
#' # Argument`optimize_y` can be used to change the look of the timeline. `TRUE` (the default)
#' # will find a nice heuristic to save `y`-space, distributing the events:
#' data <- read.csv(text="event,start,end
#' Phase 1,2020-12-15,2020-12-24
#' Phase 2,2020-12-23,2020-12-29
#' Phase 3,2020-12-28,2021-01-06
#' Phase 4,2021-01-06,2021-02-02")
#'
#' vistime(data, optimize_y = TRUE)
#'
#' # `FALSE` will plot events as-is, not saving any space:
#' vistime(data, optimize_y = FALSE)
#'
#'
#' # more complex and colorful example
#' data <- read.csv(text = "event,group,start,end,color
#' Phase 1,Project,2018-12-22,2018-12-23,#c8e6c9
#' Phase 2,Project,2018-12-23,2018-12-29,#a5d6a7
#' Phase 3,Project,2018-12-29,2019-01-06,#fb8c00
#' Phase 4,Project,2019-01-06,2019-02-02,#DD4B39
#' Room 334,Team 1,2018-12-22,2018-12-28,#DEEBF7
#' Room 335,Team 1,2018-12-28,2019-01-05,#C6DBEF
#' Room 335,Team 1,2019-01-05,2019-01-23,#9ECAE1
#' Group 1,Team 2,2018-12-22,2018-12-28,#E5F5E0
#' Group 2,Team 2,2018-12-28,2019-01-23,#C7E9C0
#' 3-200,category 1,2018-12-25,2018-12-25,#1565c0
#' 3-330,category 1,2018-12-25,2018-12-25,#1565c0
#' 3-223,category 1,2018-12-28,2018-12-28,#1565c0
#' 3-225,category 1,2018-12-28,2018-12-28,#1565c0
#' 3-226,category 1,2018-12-28,2018-12-28,#1565c0
#' 3-226,category 1,2019-01-19,2019-01-19,#1565c0
#' 3-330,category 1,2019-01-19,2019-01-19,#1565c0
#' 1-217.0,category 2,2018-12-27,2018-12-27,#90caf9
#' 3-399.7,moon rising,2019-01-13,2019-01-13,#f44336
#' 8-831.0,sundowner drink,2019-01-17,2019-01-17,#8d6e63
#' 9-984.1,birthday party,2018-12-22,2018-12-22,#90a4ae
#' F01.9,Meetings,2018-12-26,2018-12-26,#e8a735
#' Z71,Meetings,2019-01-12,2019-01-12,#e8a735
#' B95.7,Meetings,2019-01-15,2019-01-15,#e8a735
#' T82.7,Meetings,2019-01-15,2019-01-15,#e8a735")
#'
#' vistime(data)
#'
#' # ------ It is possible to change all attributes of the timeline using plotly_build(),
#' # ------ which generates a list which can be inspected using str
#' p <- vistime(data.frame(event = 1:4, start = c("2019-01-01", "2019-01-10")))
#' pp <- plotly_build(p) # transform into a list
#'
#' # Example 1: change x axis font size:
#' pp$x$layout$xaxis$tickfont <- list(size = 28)
#' pp
#'
#' # Example 2: change y axis font size:
#' pp$x$layout[["yaxis"]]$tickfont <- list(size = 28)
#' pp
#'
#' # Example 3: Changing events font size
#' for (i in 1:length(pp$x$data)) {
#' if (pp$x$data[[i]]$mode == "text") pp$x$data[[i]]$textfont$size <- 28
#' }
#' pp
#'
#' # or, using purrr:
#' text_idx <- which(purrr::map_chr(pp$x$data, "mode") == "text")
#' for(i in text_idx) pp$x$data[[i]]$textfont$size <- 28
#' pp
#'
#' # Example 4: change marker size
#' # loop over pp$x$data, and change the marker size of all text elements to 50px
#' for (i in 1:length(pp$x$data)) {
#' if (pp$x$data[[i]]$mode == "markers") pp$x$data[[i]]$marker$size <- 40
#' }
#' pp
#'
#' # or, using purrr:
#' marker_idx <- which(purrr::map_chr(pp$x$data, "mode") == "markers")
#' for(i in marker_idx) pp$x$data[[i]]$marker$size <- 40
#' pp
#' }
#'
vistime <- function(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
col.tooltip = "tooltip",
optimize_y = TRUE, linewidth = NULL, title = NULL,
show_labels = TRUE, background_lines = NULL, ...) {
checked_dat <- validate_input(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor, col.tooltip, optimize_y, linewidth, title,
show_labels, background_lines, list(...))
cleaned_dat <- vistime_data(checked_dat$data, checked_dat$col.event, checked_dat$col.start,
checked_dat$col.end, checked_dat$col.group, checked_dat$col.color,
checked_dat$col.fontcolor, checked_dat$col.tooltip, optimize_y)
total <- plot_plotly(cleaned_dat, linewidth, title, show_labels, background_lines)
return(total)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/vistime.R
|
#' Standardize data to plot on a timeline plot
#'
#' @param data \code{data.frame} that contains the data to be normalized
#' @param col.event (optional, character) the column name in \code{data} that contains event
#' names. Default: \emph{event}.
#' @param col.start (optional, character) the column name in \code{data} that contains start
#' dates. Default: \emph{start}.
#' @param col.end (optional, character) the column name in \code{data} that contains end dates.
#' Default: \emph{end}.
#' @param col.group (optional, character) the column name in \code{data} to be used for
#' grouping. Default: \emph{group}.
#' @param col.color (optional, character) the column name in \code{data} that contains colors
#' for events. Default: \emph{color}, if not present, colors are chosen via
#' \code{RColorBrewer}.
#' @param col.fontcolor (optional, character) the column name in \code{data} that contains the
#' font color for event labels. Default: \emph{fontcolor}, if not present,
#' color will be black.
#' @param col.tooltip (optional, character) the column name in \code{data} that contains the
#' mouseover tooltips for the events. Default: \emph{tooltip}, if not present,
#' then tooltips are built from event name and date.
#' @param optimize_y (optional, logical) distribute events on y-axis by smart heuristic (default), otherwise use order of input data.
#' @param ... for deprecated arguments up to vistime 1.1.0 (like events, colors, ...)
#' @export
#' @return \code{vistime_data} returns a data.frame with the following columns: event, start, end, group, tooltip, label, col, fontcol, subplot, y
#' @examples
#' # presidents and vice presidents
#' pres <- data.frame(
#' Position = rep(c("President", "Vice"), each = 3),
#' Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
#' start = c("1789-03-29", "1797-02-03", "1801-02-03"),
#' end = c("1797-02-03", "1801-02-03", "1809-02-03"),
#' color = c("#cbb69d", "#603913", "#c69c6e"),
#' fontcolor = c("black", "white", "black")
#' )
#'
#' vistime_data(pres, col.event = "Position", col.group = "Name")
vistime_data <- function(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
col.tooltip = "tooltip",
optimize_y = TRUE, ...) {
checked_dat <- validate_input(data, col.event, col.start, col.end, col.group, col.color,
col.fontcolor, col.tooltip, optimize_y, linewidth = 0, title="",
show_labels = T, background_lines = 0, list(...))
data <-
fix_columns(
checked_dat$data,
checked_dat$col.event,
checked_dat$col.start,
checked_dat$col.end,
checked_dat$col.group,
checked_dat$col.color,
checked_dat$col.fontcolor,
checked_dat$col.tooltip
)
data <- set_order(data)
data <- set_y_values(data, optimize_y)
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/vistime/R/vistime_data.R
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
## ----gg_vistime_basic_ex, warning=FALSE, fig.width=5, fig.height=1.5----------
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
gg_vistime(timeline_data)
## ----eval=FALSE---------------------------------------------------------------
# install.packages("vistime")
## ----eval = FALSE-------------------------------------------------------------
# gg_vistime(data,
# col.event = "event",
# col.start = "start",
# col.end = "end",
# col.group = "group",
# col.color = "color",
# col.fontcolor = "fontcolor",
# optimize_y = TRUE,
# linewidth = NULL,
# title = NULL,
# show_labels = TRUE,
# background_lines = NULL)
#
## ----presidents example, fig.height = 2.5, fig.width=5------------------------
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
gg_vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
## ----project planning example, fig.height = 4.5, fig.width=10-----------------
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
gg_vistime(data)
## ----gantt_true, fig.height = 2.3, fig.width=6--------------------------------
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
gg_vistime(data, optimize_y = TRUE, linewidth = 25)
## ----gantt_false, fig.height = 3.7, fig.width=6-------------------------------
gg_vistime(data, optimize_y = FALSE, linewidth = 25)
## ----eval=FALSE---------------------------------------------------------------
# chart <- vistime(pres, col.event = "Position")
# ggplot2::ggsave("presidents.png", timeline)
## ----eval=FALSE---------------------------------------------------------------
# library(vistime)
#
# pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
# Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
# start = c("1789-03-29", "1797-02-03", "1801-02-03"),
# end = c("1797-02-03", "1801-02-03", "1809-02-03"),
# color = c('#cbb69d', '#603913', '#c69c6e'),
# fontcolor = c("black", "white", "black"))
#
# shinyApp(
# ui = plotOutput("myVistime"),
# server = function(input, output) {
# output$myVistime <- renderPlot({
# vistime(pres, col.event = "Position", col.group = "Name")
# })
# }
# )
## ----gg_customization, fig.height=2.5, fig.width=5, message=FALSE-------------
library(vistime)
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
p <- gg_vistime(data, optimize_y = T, col.group = "event", title = "ggplot customization example")
library(ggplot2)
p + ggplot2::theme(
plot.title = element_text(hjust = 0, size=10),
axis.text.x = element_text(size = 10, color = "violet"),
axis.text.y = element_text(size = 10, color = "red", angle = 30),
panel.border = element_rect(linetype = "dashed", fill=NA),
panel.background = element_rect(fill = 'green')) +
coord_cartesian(ylim = c(0.7, 3.5))
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/gg_vistime-vignette.R
|
---
title: "Static timeline plots with gg_vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Static timeline plots with gg_vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
`gg_vistime()` produces **ggplot2** charts. For interactive **Plotly** output, see `vistime()`, for interactive **Highcharts** output, see `hc_vistime()`.
```{r gg_vistime_basic_ex, warning=FALSE, fig.width=5, fig.height=1.5}
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
gg_vistime(timeline_data)
```
## 2. Installation
To install the package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function using the `col.` arguments. You can also tweak the y positions, linewidth, title, label visibility and number of lines in the background.
```{r eval = FALSE}
gg_vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
optimize_y = TRUE,
linewidth = NULL,
title = NULL,
show_labels = TRUE,
background_lines = NULL)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.fontcolor | optional | character | the column name in data that contains the font color for event labels. Default: *fontcolor*, if not present, color will be black.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
linewidth | optional | numeric | override the calculated linewidth for events. Default: heuristic value.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
background_lines | optional | integer | the number of vertical lines to draw in the background to demonstrate structure. Default: 10.
## 5. Value
* `gg_vistime` returns an object of class `gg` and `ggplot`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, fig.height = 2.5, fig.width=5}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
gg_vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
```
### Ex. 2: Project Planning
```{r project planning example, fig.height = 4.5, fig.width=10}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
gg_vistime(data)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height = 2.3, fig.width=6}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
gg_vistime(data, optimize_y = TRUE, linewidth = 25)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height = 3.7, fig.width=6}
gg_vistime(data, optimize_y = FALSE, linewidth = 25)
```
## 7. Export of vistime as PNG
Once created, you can use `ggplot2::ggsave()` for saving your vistime chart as PNG:
```{r eval=FALSE}
chart <- vistime(pres, col.event = "Position")
ggplot2::ggsave("presidents.png", timeline)
```
## 8. Usage in Shiny apps
- `gg_vistime()` objects can be integrated into Shiny via `plotOutput()` and `renderPlot()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = plotOutput("myVistime"),
server = function(input, output) {
output$myVistime <- renderPlot({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
Since every `gg_vistime()` output is a `ggplot` object, you can customize and override literally everything:
```{r gg_customization, fig.height=2.5, fig.width=5, message=FALSE}
library(vistime)
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
p <- gg_vistime(data, optimize_y = T, col.group = "event", title = "ggplot customization example")
library(ggplot2)
p + ggplot2::theme(
plot.title = element_text(hjust = 0, size=10),
axis.text.x = element_text(size = 10, color = "violet"),
axis.text.y = element_text(size = 10, color = "red", angle = 30),
panel.border = element_rect(linetype = "dashed", fill=NA),
panel.background = element_rect(fill = 'green')) +
coord_cartesian(ylim = c(0.7, 3.5))
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/gg_vistime-vignette.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
library(highcharter)
hc_vistime <- function(...) hc_size(vistime::hc_vistime(...), width=700, height=150)
## ----hc_vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"-------
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
hc_vistime(timeline_data)
## ----eval=FALSE---------------------------------------------------------------
# install.packages("vistime")
## ----eval=FALSE---------------------------------------------------------------
# install.packages("highcharter")
## ----eval = FALSE-------------------------------------------------------------
# hc_vistime(data,
# col.event = "event",
# col.start = "start",
# col.end = "end",
# col.group = "group",
# col.color = "color",
# optimize_y = TRUE,
# title = NULL,
# show_labels = TRUE)
## ----presidents example, eval = FALSE-----------------------------------------
# pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
# Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
# start = c("1789-03-29", "1797-02-03", "1801-02-03"),
# end = c("1797-02-03", "1801-02-03", "1809-02-03"),
# color = c('#cbb69d', '#603913', '#c69c6e'),
# fontcolor = c("black", "white", "black"))
#
# hc_vistime(pres,
# col.event = "Position",
# col.group = "Name",
# title = "Presidents of the USA") %>%
# hc_size(width = 700, height = 300)
## ----presidents example code, echo = FALSE------------------------------------
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
hc_vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA") %>%
hc_size(width = 700, height = 300)
## ----project planning example, eval = FALSE-----------------------------------
# data <- read.csv(text="event,group,start,end,color
# Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
# Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
# Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
# Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
# Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
# Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
# Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
# Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
# Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
# 3-200,category 1,2016-12-25,2016-12-25,#1565c0
# 3-330,category 1,2016-12-25,2016-12-25,#1565c0
# 3-223,category 1,2016-12-28,2016-12-28,#1565c0
# 3-225,category 1,2016-12-28,2016-12-28,#1565c0
# 3-226,category 1,2016-12-28,2016-12-28,#1565c0
# 3-226,category 1,2017-01-19,2017-01-19,#1565c0
# 3-330,category 1,2017-01-19,2017-01-19,#1565c0
# 1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
# 4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
# 8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
# 9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
# F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
# Z71,Meetings,2017-01-12,2017-01-12,#e8a735
# B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
# T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
#
# hc_vistime(data)
## ----project planning example code, echo = F----------------------------------
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
hc_vistime(data) %>%
hc_size(width = 700, height = 500)
## ----gantt_true, fig.height=1.8, out.width="100%"-----------------------------
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
hc_vistime(data, optimize_y = TRUE)
## ----gantt_false, fig.height=2.5, out.width="100%"----------------------------
hc_vistime(data, optimize_y = FALSE)
## ----eval=FALSE---------------------------------------------------------------
# library(vistime)
#
# pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
# Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
# start = c("1789-03-29", "1797-02-03", "1801-02-03"),
# end = c("1797-02-03", "1801-02-03", "1809-02-03"),
# color = c('#cbb69d', '#603913', '#c69c6e'),
# fontcolor = c("black", "white", "black"))
#
# shinyApp(
# ui = highcharter::highchartOutput("myVistime"),
# server = function(input, output) {
# output$myVistime <- highcharter::renderHighchart({
# vistime(pres, col.event = "Position", col.group = "Name")
# })
# }
# )
## ----hc_customization, message=FALSE------------------------------------------
library(highcharter)
p3 <- hc_vistime(data,
optimize_y = T,
col.group = "event",
title = "Highcharts customization example")
p3 %>% hc_title(style = list(fontSize = 30)) %>%
hc_yAxis(labels = list(style = list(fontSize=30, color="violet"))) %>%
hc_xAxis(labels = list(style = list(fontSize=30, color="red"), rotation=30)) %>%
hc_chart(backgroundColor = "lightgreen") %>%
hc_size(width = 700, height = 300)
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/hc_vistime-vignette.R
|
---
title: "Interactive timeline plots with hc_vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Interactive timeline plots with hc_vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
library(highcharter)
hc_vistime <- function(...) hc_size(vistime::hc_vistime(...), width=700, height=150)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
```{r hc_vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"}
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
hc_vistime(timeline_data)
```
## 2. Installation
To install `vistime` package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
For interactive `hc_vistime()` plots, you need to install the `highcharter` package. This package is free for non-commercial and non-governmental use:
```{r eval=FALSE}
install.packages("highcharter")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function. You can also tweak the y positions, title and label visibility.
```{r eval = FALSE}
hc_vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
optimize_y = TRUE,
title = NULL,
show_labels = TRUE)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.tooltip | optional | character | the column name in data that contains the mouseover tooltips for the events. Default: *tooltip*, if not present, then tooltips are build from event name and date. [Basic HTML](https://plotly.com/chart-studio-help/adding-HTML-and-links-to-charts/#step-2-the-essentials) is allowed.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
## 5. Value
* `hc_vistime` returns an object of class `highchart` and `htmlwidget`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, eval = FALSE}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
hc_vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA") %>%
hc_size(width = 700, height = 300)
```
```{r presidents example code, echo = FALSE}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
hc_vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA") %>%
hc_size(width = 700, height = 300)
```
### Ex. 2: Project Planning
```{r project planning example, eval = FALSE}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
hc_vistime(data)
```
```{r project planning example code, echo = F}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
hc_vistime(data) %>%
hc_size(width = 700, height = 500)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height=1.8, out.width="100%"}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
hc_vistime(data, optimize_y = TRUE)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height=2.5, out.width="100%"}
hc_vistime(data, optimize_y = FALSE)
```
## 8. Usage in Shiny apps
- `hc_vistime()` objects can be integrated into [Shiny](https://shiny.posit.co/) via `highchartOutput()` and `renderHighchart()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = highcharter::highchartOutput("myVistime"),
server = function(input, output) {
output$myVistime <- highcharter::renderHighchart({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
Since every `hc_vistime()` output is a `highchart` object, you can customize and override literally everything using its functions. See `?hc_xAxis`, `?hc_chart` etc. and the official [Highcharts API reference](https://api.highcharts.com/highcharts/title) for details.
```{r hc_customization, message=FALSE}
library(highcharter)
p3 <- hc_vistime(data,
optimize_y = T,
col.group = "event",
title = "Highcharts customization example")
p3 %>% hc_title(style = list(fontSize = 30)) %>%
hc_yAxis(labels = list(style = list(fontSize=30, color="violet"))) %>%
hc_xAxis(labels = list(style = list(fontSize=30, color="red"), rotation=30)) %>%
hc_chart(backgroundColor = "lightgreen") %>%
hc_size(width = 700, height = 300)
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/hc_vistime-vignette.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
## ----vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"----------
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
vistime(timeline_data)
## ----eval=FALSE---------------------------------------------------------------
# install.packages("vistime")
## ----eval = FALSE-------------------------------------------------------------
# vistime(data,
# col.event = "event",
# col.start = "start",
# col.end = "end",
# col.group = "group",
# col.color = "color",
# col.fontcolor = "fontcolor",
# col.tooltip = "tooltip",
# optimize_y = TRUE,
# linewidth = NULL,
# title = NULL,
# show_labels = TRUE,
# background_lines = NULL)
## ----presidents example, fig.height=3, out.width="100%"-----------------------
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
## ----project planning example, fig.height=5, out.width="100%"-----------------
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
vistime(data)
## ----gantt_true, fig.height=1.8, out.width="100%"-----------------------------
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
vistime(data, optimize_y = TRUE, linewidth = 25)
## ----gantt_false, fig.height=2.5, out.width="100%"----------------------------
vistime(data, optimize_y = FALSE, linewidth = 25)
## ----eval=FALSE---------------------------------------------------------------
# # webshot::install_phantomjs()
# chart <- vistime(pres, col.event = "Position")
# plotly::export(chart, file = "presidents.pdf")
## ----eval=FALSE---------------------------------------------------------------
# library(vistime)
#
# pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
# Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
# start = c("1789-03-29", "1797-02-03", "1801-02-03"),
# end = c("1797-02-03", "1801-02-03", "1809-02-03"),
# color = c('#cbb69d', '#603913', '#c69c6e'),
# fontcolor = c("black", "white", "black"))
#
# shinyApp(
# ui = plotly::plotlyOutput("myVistime"),
# server = function(input, output) {
# output$myVistime <- plotly::renderPlotly({
# vistime(pres, col.event = "Position", col.group = "Name")
# })
# }
# )
## ----plotly_customization, fig.height=2.5, out.width="100%", message=FALSE----
library(plotly)
p2 <- vistime(data,
optimize_y = T,
col.group = "event",
title = "Plotly customization example")
p2 %>% layout(xaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="violet")),
yaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="red"), tickangle=30,
mirror = FALSE, range = c(0.7, 3.5), showgrid = T),
plot_bgcolor = "lightgreen")
## ----plotly_build1, fig.height=3, out.width="100%"----------------------------
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: change the font size
pp$x$layout$xaxis$tickfont <- list(size = 28)
pp
## ----plotly_build2, fig.height=3, out.width="100%"----------------------------
pp$x$layout[["yaxis"]]$tickfont <- list(size = 28)
pp
## ----plotly_build3, fig.height=3, out.width="100%"----------------------------
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA",
linewidth=30)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the font size of all text elements to 28
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "text") pp$x$data[[i]]$textfont$size <- 28
}
#' # or, using purrr:
#' text_idx <- which(purrr::map_chr(pp$x$data, "mode") == "text")
#' for(i in text_idx) pp$x$data[[i]]$textfont$size <- 28
#' pp
pp
## ----plotly_build4, fig.height=2, out.width="100%"----------------------------
dat <- data.frame(event = 1:4, start = c("2019-01-01", "2019-01-10"))
p <- vistime(dat)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the marker size of all text elements to 50px
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "markers") pp$x$data[[i]]$marker$size <- 20
}
# or, using purrr:
# marker_idx <- which(purrr::map_chr(pp$x$data, "mode") == "markers")
# for(i in marker_idx) pp$x$data[[i]]$marker$size <- 20
# pp
pp
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/vistime-vignette.R
|
---
title: "Interactive timeline plots with vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Interactive timeline plots with vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
`vistime()` produces **Plotly** charts. For interactive **Highcharts** output, see `hc_vistime()`, for static **ggplot2** charts, see `gg_vistime()`.
```{r vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"}
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
vistime(timeline_data)
```
## 2. Installation
To install the package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function. You can also tweak the y positions, linewidth, title, label visibility and number of lines in the background.
```{r eval = FALSE}
vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
col.tooltip = "tooltip",
optimize_y = TRUE,
linewidth = NULL,
title = NULL,
show_labels = TRUE,
background_lines = NULL)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.fontcolor | optional | character | the column name in data that contains the font color for event labels. Default: *fontcolor*, if not present, color will be black.
col.tooltip | optional | character | the column name in data that contains the mouseover tooltips for the events. Default: *tooltip*, if not present, then tooltips are build from event name and date. [Basic HTML](https://plotly.com/chart-studio-help/adding-HTML-and-links-to-charts/#step-2-the-essentials) is allowed.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
linewidth | optional | numeric | override the calculated linewidth for events. Default: heuristic value.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
background_lines | optional | integer | the number of vertical lines to draw in the background to demonstrate structure. Default: heuristic.
## 5. Value
* `vistime` returns an object of class `plotly` and `htmlwidget`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
```
### Ex. 2: Project Planning
```{r project planning example, fig.height=5, out.width="100%"}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
vistime(data)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height=1.8, out.width="100%"}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
vistime(data, optimize_y = TRUE, linewidth = 25)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height=2.5, out.width="100%"}
vistime(data, optimize_y = FALSE, linewidth = 25)
```
## 7. Export of vistime as PDF or PNG
Once created, you can use `plotly::export()` for saving your vistime chart as PDF, PNG or JPEG:
```{r eval=FALSE}
# webshot::install_phantomjs()
chart <- vistime(pres, col.event = "Position")
plotly::export(chart, file = "presidents.pdf")
```
Note that export requires the `webshot` package and `phantomjs` on your OS. Additional arguments like width or height can be used (`?webshot` for the details). You can also download the plot as PNG by using the toolbar on the upper right side of the generated plot.
## 8. Usage in Shiny apps
- `vistime()` objects can be integrated into [Shiny](https://shiny.posit.co/) via `plotlyOutput()` and `renderPlotly()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = plotly::plotlyOutput("myVistime"),
server = function(input, output) {
output$myVistime <- plotly::renderPlotly({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
### Using `plotly::layout()`
See `?plotly::layout` and the official [Plotly API reference](https://plotly.com/r/reference/#Layout_and_layout_style_objects) for details.
```{r plotly_customization, fig.height=2.5, out.width="100%", message=FALSE}
library(plotly)
p2 <- vistime(data,
optimize_y = T,
col.group = "event",
title = "Plotly customization example")
p2 %>% layout(xaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="violet")),
yaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="red"), tickangle=30,
mirror = FALSE, range = c(0.7, 3.5), showgrid = T),
plot_bgcolor = "lightgreen")
```
### List manipulation
#### Changing x-axis tick font size
The following example creates the presidents example and manipulates the font size of the x axis ticks:
```{r plotly_build1, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: change the font size
pp$x$layout$xaxis$tickfont <- list(size = 28)
pp
```
#### Changing y-axis tick font size
We need to change the font size of the y-axis:
```{r plotly_build2, fig.height=3, out.width="100%"}
pp$x$layout[["yaxis"]]$tickfont <- list(size = 28)
pp
```
#### Changing events font size
The following example creates the presidents example and manipulates the font size of the events:
```{r plotly_build3, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA",
linewidth=30)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the font size of all text elements to 28
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "text") pp$x$data[[i]]$textfont$size <- 28
}
#' # or, using purrr:
#' text_idx <- which(purrr::map_chr(pp$x$data, "mode") == "text")
#' for(i in text_idx) pp$x$data[[i]]$textfont$size <- 28
#' pp
pp
```
#### Changing marker size
The following example a simple example using markers and manipulates the size of the markers:
```{r plotly_build4, fig.height=2, out.width="100%"}
dat <- data.frame(event = 1:4, start = c("2019-01-01", "2019-01-10"))
p <- vistime(dat)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the marker size of all text elements to 50px
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "markers") pp$x$data[[i]]$marker$size <- 20
}
# or, using purrr:
# marker_idx <- which(purrr::map_chr(pp$x$data, "mode") == "markers")
# for(i in marker_idx) pp$x$data[[i]]$marker$size <- 20
# pp
pp
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/inst/doc/vistime-vignette.Rmd
|
---
title: "Static timeline plots with gg_vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Static timeline plots with gg_vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
`gg_vistime()` produces **ggplot2** charts. For interactive **Plotly** output, see `vistime()`, for interactive **Highcharts** output, see `hc_vistime()`.
```{r gg_vistime_basic_ex, warning=FALSE, fig.width=5, fig.height=1.5}
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
gg_vistime(timeline_data)
```
## 2. Installation
To install the package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function using the `col.` arguments. You can also tweak the y positions, linewidth, title, label visibility and number of lines in the background.
```{r eval = FALSE}
gg_vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
optimize_y = TRUE,
linewidth = NULL,
title = NULL,
show_labels = TRUE,
background_lines = NULL)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.fontcolor | optional | character | the column name in data that contains the font color for event labels. Default: *fontcolor*, if not present, color will be black.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
linewidth | optional | numeric | override the calculated linewidth for events. Default: heuristic value.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
background_lines | optional | integer | the number of vertical lines to draw in the background to demonstrate structure. Default: 10.
## 5. Value
* `gg_vistime` returns an object of class `gg` and `ggplot`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, fig.height = 2.5, fig.width=5}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
gg_vistime(pres, col.event = "Position", col.group = "Name", title = "Presidents of the USA")
```
### Ex. 2: Project Planning
```{r project planning example, fig.height = 4.5, fig.width=10}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
gg_vistime(data)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height = 2.3, fig.width=6}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
gg_vistime(data, optimize_y = TRUE, linewidth = 25)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height = 3.7, fig.width=6}
gg_vistime(data, optimize_y = FALSE, linewidth = 25)
```
## 7. Export of vistime as PNG
Once created, you can use `ggplot2::ggsave()` for saving your vistime chart as PNG:
```{r eval=FALSE}
chart <- vistime(pres, col.event = "Position")
ggplot2::ggsave("presidents.png", timeline)
```
## 8. Usage in Shiny apps
- `gg_vistime()` objects can be integrated into Shiny via `plotOutput()` and `renderPlot()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = plotOutput("myVistime"),
server = function(input, output) {
output$myVistime <- renderPlot({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
Since every `gg_vistime()` output is a `ggplot` object, you can customize and override literally everything:
```{r gg_customization, fig.height=2.5, fig.width=5, message=FALSE}
library(vistime)
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
p <- gg_vistime(data, optimize_y = T, col.group = "event", title = "ggplot customization example")
library(ggplot2)
p + ggplot2::theme(
plot.title = element_text(hjust = 0, size=10),
axis.text.x = element_text(size = 10, color = "violet"),
axis.text.y = element_text(size = 10, color = "red", angle = 30),
panel.border = element_rect(linetype = "dashed", fill=NA),
panel.background = element_rect(fill = 'green')) +
coord_cartesian(ylim = c(0.7, 3.5))
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/vignettes/gg_vistime-vignette.Rmd
|
---
title: "Interactive timeline plots with hc_vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Interactive timeline plots with hc_vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
library(highcharter)
hc_vistime <- function(...) hc_size(vistime::hc_vistime(...), width=700, height=150)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
```{r hc_vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"}
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
hc_vistime(timeline_data)
```
## 2. Installation
To install `vistime` package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
For interactive `hc_vistime()` plots, you need to install the `highcharter` package. This package is free for non-commercial and non-governmental use:
```{r eval=FALSE}
install.packages("highcharter")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function. You can also tweak the y positions, title and label visibility.
```{r eval = FALSE}
hc_vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
optimize_y = TRUE,
title = NULL,
show_labels = TRUE)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.tooltip | optional | character | the column name in data that contains the mouseover tooltips for the events. Default: *tooltip*, if not present, then tooltips are build from event name and date. [Basic HTML](https://plotly.com/chart-studio-help/adding-HTML-and-links-to-charts/#step-2-the-essentials) is allowed.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
## 5. Value
* `hc_vistime` returns an object of class `highchart` and `htmlwidget`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, eval = FALSE}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
hc_vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA") %>%
hc_size(width = 700, height = 300)
```
```{r presidents example code, echo = FALSE}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
hc_vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA") %>%
hc_size(width = 700, height = 300)
```
### Ex. 2: Project Planning
```{r project planning example, eval = FALSE}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
hc_vistime(data)
```
```{r project planning example code, echo = F}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
hc_vistime(data) %>%
hc_size(width = 700, height = 500)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height=1.8, out.width="100%"}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
hc_vistime(data, optimize_y = TRUE)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height=2.5, out.width="100%"}
hc_vistime(data, optimize_y = FALSE)
```
## 8. Usage in Shiny apps
- `hc_vistime()` objects can be integrated into [Shiny](https://shiny.posit.co/) via `highchartOutput()` and `renderHighchart()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = highcharter::highchartOutput("myVistime"),
server = function(input, output) {
output$myVistime <- highcharter::renderHighchart({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
Since every `hc_vistime()` output is a `highchart` object, you can customize and override literally everything using its functions. See `?hc_xAxis`, `?hc_chart` etc. and the official [Highcharts API reference](https://api.highcharts.com/highcharts/title) for details.
```{r hc_customization, message=FALSE}
library(highcharter)
p3 <- hc_vistime(data,
optimize_y = T,
col.group = "event",
title = "Highcharts customization example")
p3 %>% hc_title(style = list(fontSize = 30)) %>%
hc_yAxis(labels = list(style = list(fontSize=30, color="violet"))) %>%
hc_xAxis(labels = list(style = list(fontSize=30, color="red"), rotation=30)) %>%
hc_chart(backgroundColor = "lightgreen") %>%
hc_size(width = 700, height = 300)
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/vignettes/hc_vistime-vignette.Rmd
|
---
title: "Interactive timeline plots with vistime()"
date: "`r format(Sys.Date(), '%B %Y')`"
output:
prettydoc::html_pretty:
theme: architect
highlight: github
toc: true
vignette: >
%\VignetteIndexEntry{Interactive timeline plots with vistime()}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
library(vistime)
```
[](https://www.buymeacoffee.com/shosaco)
**Feedback welcome:** <a href = "mailto:[email protected]">[email protected]</a>
## 1. Basic example
`vistime()` produces **Plotly** charts. For interactive **Highcharts** output, see `hc_vistime()`, for static **ggplot2** charts, see `gg_vistime()`.
```{r vistime_basic_ex, warning=FALSE, fig.height=1, out.width="100%"}
library(vistime)
timeline_data <- data.frame(event = c("Event 1", "Event 2"),
start = c("2020-06-06", "2020-10-01"),
end = c("2020-10-01", "2020-12-31"),
group = "My Events")
vistime(timeline_data)
```
## 2. Installation
To install the package from CRAN, type the following in your R console:
```{r eval=FALSE}
install.packages("vistime")
```
## 3. Usage and default arguments
The simplest way to create a timeline is by providing a data frame with `event` and `start` columns. If your columns are named otherwise, you need to tell the function. You can also tweak the y positions, linewidth, title, label visibility and number of lines in the background.
```{r eval = FALSE}
vistime(data,
col.event = "event",
col.start = "start",
col.end = "end",
col.group = "group",
col.color = "color",
col.fontcolor = "fontcolor",
col.tooltip = "tooltip",
optimize_y = TRUE,
linewidth = NULL,
title = NULL,
show_labels = TRUE,
background_lines = NULL)
```
## 4. Arguments
parameter | optional? | data type | explanation
--------- |----------- | -------- | -----------
data | mandatory | data.frame | data.frame that contains the data to be visualized
col.event | optional | character | the column name in data that contains event names. Default: *event*
col.start | optional | character | the column name in data that contains start dates. Default: *start*
col.end | optional | character | the column name in data that contains end dates. Default: *end*
col.group | optional | character | the column name in data to be used for grouping. Default: *group*
col.color | optional | character | the column name in data that contains colors for events. Default: *color*, if not present, colors are chosen via RColorBrewer.
col.fontcolor | optional | character | the column name in data that contains the font color for event labels. Default: *fontcolor*, if not present, color will be black.
col.tooltip | optional | character | the column name in data that contains the mouseover tooltips for the events. Default: *tooltip*, if not present, then tooltips are build from event name and date. [Basic HTML](https://plotly.com/chart-studio-help/adding-HTML-and-links-to-charts/#step-2-the-essentials) is allowed.
optimize_y | optional | logical | distribute events on y-axis by smart heuristic (default) or use order of input data.
linewidth | optional | numeric | override the calculated linewidth for events. Default: heuristic value.
title | optional | character | the title to be shown on top of the timeline. Default: empty.
show_labels | optional | logical | choose whether or not event labels shall be visible. Default: `TRUE`.
background_lines | optional | integer | the number of vertical lines to draw in the background to demonstrate structure. Default: heuristic.
## 5. Value
* `vistime` returns an object of class `plotly` and `htmlwidget`
## 6. Examples
### Ex. 1: Presidents
```{r presidents example, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
```
### Ex. 2: Project Planning
```{r project planning example, fig.height=5, out.width="100%"}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
vistime(data)
```
### Ex. 3: Gantt Charts
The argument `optimize_y` can be used to change the look of the timeline. `TRUE` (the default) will find a nice heuristic to save `y`-space, distributing the events:
```{r gantt_true, fig.height=1.8, out.width="100%"}
data <- read.csv(text="event,start,end
Phase 1,2020-12-15,2020-12-24
Phase 2,2020-12-23,2020-12-29
Phase 3,2020-12-28,2021-01-06
Phase 4,2021-01-06,2021-02-02")
vistime(data, optimize_y = TRUE, linewidth = 25)
```
`FALSE` will plot events as-is, not saving any space:
```{r gantt_false, fig.height=2.5, out.width="100%"}
vistime(data, optimize_y = FALSE, linewidth = 25)
```
## 7. Export of vistime as PDF or PNG
Once created, you can use `plotly::export()` for saving your vistime chart as PDF, PNG or JPEG:
```{r eval=FALSE}
# webshot::install_phantomjs()
chart <- vistime(pres, col.event = "Position")
plotly::export(chart, file = "presidents.pdf")
```
Note that export requires the `webshot` package and `phantomjs` on your OS. Additional arguments like width or height can be used (`?webshot` for the details). You can also download the plot as PNG by using the toolbar on the upper right side of the generated plot.
## 8. Usage in Shiny apps
- `vistime()` objects can be integrated into [Shiny](https://shiny.posit.co/) via `plotlyOutput()` and `renderPlotly()`
```{r eval=FALSE}
library(vistime)
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
shinyApp(
ui = plotly::plotlyOutput("myVistime"),
server = function(input, output) {
output$myVistime <- plotly::renderPlotly({
vistime(pres, col.event = "Position", col.group = "Name")
})
}
)
```
## 9. Customization
### Using `plotly::layout()`
See `?plotly::layout` and the official [Plotly API reference](https://plotly.com/r/reference/#Layout_and_layout_style_objects) for details.
```{r plotly_customization, fig.height=2.5, out.width="100%", message=FALSE}
library(plotly)
p2 <- vistime(data,
optimize_y = T,
col.group = "event",
title = "Plotly customization example")
p2 %>% layout(xaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="violet")),
yaxis=list(fixedrange=TRUE, tickfont=list(size=30, color="red"), tickangle=30,
mirror = FALSE, range = c(0.7, 3.5), showgrid = T),
plot_bgcolor = "lightgreen")
```
### List manipulation
#### Changing x-axis tick font size
The following example creates the presidents example and manipulates the font size of the x axis ticks:
```{r plotly_build1, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA")
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: change the font size
pp$x$layout$xaxis$tickfont <- list(size = 28)
pp
```
#### Changing y-axis tick font size
We need to change the font size of the y-axis:
```{r plotly_build2, fig.height=3, out.width="100%"}
pp$x$layout[["yaxis"]]$tickfont <- list(size = 28)
pp
```
#### Changing events font size
The following example creates the presidents example and manipulates the font size of the events:
```{r plotly_build3, fig.height=3, out.width="100%"}
pres <- data.frame(Position = rep(c("President", "Vice"), each = 3),
Name = c("Washington", rep(c("Adams", "Jefferson"), 2), "Burr"),
start = c("1789-03-29", "1797-02-03", "1801-02-03"),
end = c("1797-02-03", "1801-02-03", "1809-02-03"),
color = c('#cbb69d', '#603913', '#c69c6e'),
fontcolor = c("black", "white", "black"))
p <- vistime(pres,
col.event = "Position",
col.group = "Name",
title = "Presidents of the USA",
linewidth=30)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the font size of all text elements to 28
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "text") pp$x$data[[i]]$textfont$size <- 28
}
#' # or, using purrr:
#' text_idx <- which(purrr::map_chr(pp$x$data, "mode") == "text")
#' for(i in text_idx) pp$x$data[[i]]$textfont$size <- 28
#' pp
pp
```
#### Changing marker size
The following example a simple example using markers and manipulates the size of the markers:
```{r plotly_build4, fig.height=2, out.width="100%"}
dat <- data.frame(event = 1:4, start = c("2019-01-01", "2019-01-10"))
p <- vistime(dat)
# step 1: transform into a list
pp <- plotly::plotly_build(p)
# step 2: loop over pp$x$data, and change the marker size of all text elements to 50px
for(i in seq_along(pp$x$data)){
if(pp$x$data[[i]]$mode == "markers") pp$x$data[[i]]$marker$size <- 20
}
# or, using purrr:
# marker_idx <- which(purrr::map_chr(pp$x$data, "mode") == "markers")
# for(i in marker_idx) pp$x$data[[i]]$marker$size <- 20
# pp
pp
```
|
/scratch/gouwar.j/cran-all/cranData/vistime/vignettes/vistime-vignette.Rmd
|
ew_cut<-function(bins)
function(x) factor(paste('l',cut(x,breaks=bins,labels=FALSE),sep=""))
es_cut<-function(bins)
function(x) ew_cut(bins)(rank(x,na.last=FALSE))
#' Basic discretisation of numerical features
#'
#' One can use this function for a quick, ad hoc discretisation of numerical features in a data frame, so that it could be passed to \code{\link{vistla}} using the maximal likelihood estimation (mle, the default).
#' This can be used to simulate legacy behaviour of vistla, which was to automatically perform such conversion with 10 equal-width bins.
#' The non-numeric columns are left as they were, hence this function is idempotent and does nothing when given fully discrete data.
#' @param x Data frame to be converted.
#' @param bins Number of bins to cut each numerical column into.
#' @param equal If given \code{"width"}, function performs cuts into bins of an equal width, which may thus contain substantially different number of objects.
#' One the other hand, when given \code{"size"} (default), cuts are done according to quantiles, hence provide bins with approximately the same number of objects, yet with different widths.
#' Both options are asymptotically equivalent when the distribution of a given column is uniform.
#' @return A copy of \code{x}, in which numerical columns have been discretised.
#' @note While convenient, this function does not necessary provide optimal quantisation of the data (in terms of future vistla performance); especially the bins parameter should be adjusted to the input data, either via optimisation or based on the known properties of the input or mechanisms behind it.
#' @examples
#' \dontrun{
#' data(cchain)
#' vistla(Y~.,data=mle_coerce(cchain,3,"size"))
#' }
#' @export
mle_coerce<-function(x,bins=3,equal=c("size","width")){
stopifnot(is.data.frame(x))
equal<-match.arg(equal)
qf<-if(equal=="width") ew_cut(bins) else
if(equal=="size") es_cut(bins) else stop("Unknown value of the `equal` argument")
for(e in 1:ncol(x))
if(is.numeric(x[,e])) x[,e]<-qf(x[,e])
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/coerce.R
|
#' Synthetic data representing a simple mediator chain
#'
#' Chain is generated from a simple Bayes network,
#' \deqn{X\rightarrow M_1 \rightarrow M_2 \rightarrow M_3 \rightarrow M_4 \rightarrow Y}
#' where every variable is binary.
#' The set consists of 11 observations, and is tuned to be easily deciphered.
#' @format A data set with six binary factor columns.
#' @usage data(chain)
"chain"
#' Synthetic continuous data representing a simple mediator chain
#'
#' Chain is generated from an uniform variable X by progressively adding gaussian noise, producing a mediator chain identical to this of the \code{\link{chain}} data, i.e.,
#' \deqn{X\rightarrow M_1 \rightarrow M_2 \rightarrow M_3 \rightarrow M_4 \rightarrow Y}
#' The set consists of 20 observations, and is tuned to be easily deciphered.
#' @format A data set with six numerical columns.
#' @usage data(cchain)
"cchain"
#' Synthetic data representing a junction
#'
#' Junction is a model of a multimodal agent, a variable that is an element of multiple separate paths.
#' Here, these paths are \eqn{A_1\rightarrow X \rightarrow A_2} and
#' \eqn{B_1\rightarrow X \rightarrow B_2,}
#' while \eqn{X} is the junction.
#' The set consists of 12 observations, and is tuned to be easily deciphered.
#' @format A data set with five factor columns.
#' @usage data(junction)
"junction"
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/data.R
|
#' Export tree to a Graphviz DOT format
#'
#' Exports the vistla tree in a DOT format, which can be later layouted and rendered by Graphviz programs like dot or neato.
#' @param x vistla object.
#' @param con connection; passed to \code{writeLines}.
#' If missing, the DOT code is returned as a character vector.
#' @param vstyle vertex attribute list --- should be a named list of Graphviz attributes like \code{shape} or \code{penwidth}.
#' For elements which are strings or numbers, the value is copied as is as an attribute value.
#' For elements which functions, though, the function is called on a \code{vistla_tree} object and should return a vector of values.
#' @param estyle edge attribute list, behaves exactly like \code{vstyle}.
#' When functions are called, the Y-vertex is not present.
#' @param gstyle graph attribute list. Functions are not supported here.
#' @param direction when set to \code{"none"}, graph is undirected, otherwise directed, for \code{"fromY"}, root is a source, while for \code{"intoY"}, a sink.
#' @return For a missing \code{con} argument, a character vector with the graph in the DOT format, invisible \code{NULL} otherwise.
#' @references "An open graph visualization system and its applications to software engineering" E.R. Gansner, S.C. North. Software: Practice and Experience 30:1203-1233 (2000).
#' @note Graphviz attribute values can be either strings, like \code{"some vertex"} in \code{label}, or atoms, like \code{box} for \code{shape}.
#' When returning a string value, you must supply quotes, otherwise it will be included as an atom.
#'
#' The default value of \code{gstyle} may invoke long layout calculations in Graphviz.
#' Change to \code{list()} for a fast but less aesthetic layout.
#'
#' The function does no validation whether provided attributes or values are correct.
#' @export
write.dot<-function(x,con,
vstyle=list(
shape=function(x) ifelse(x$depth<0,"egg",ifelse(x$leaf,"box","ellipse")),
label=function(x) sprintf("\"%s\"",x$name)
),
estyle=list(penwidth=function(x) sprintf("%0.3f",0.5+x$score/max(x$score)*2.5)),
gstyle=list(overlap='"prism"',splines='true'),
direction=c('none','fromY','intoY')
){
stopifnot(inherits(x,"vistla"))
direction<-match.arg(direction)
hierarchy(x)->tr
sl2txt<-function(x,tr){
if(length(x)==0) return(rep("",nrow(tr)))
do.call(paste,lapply(names(x),function(key){
gen<-x[[key]]
val<-if(is.function(gen)) gen(tr) else rep(gen,nrow(tr))
sprintf("%s=%s",key,val)
}
))->kv
sprintf(" [%s]",kv)
}
gsub('\\.','__',make.names(tr$name,unique=TRUE))->tr$id
sl2txt(vstyle,tr)->vs
tre<-tr[tr$depth>=0,]
sl2txt(estyle,tre)->es
sprintf("\t%s=%s;",names(gstyle),gstyle)->gr
vtx<-with(tr,sprintf("\t%s%s;",id,vs))
dr<-ifelse(direction=="none","--","->")
edg<-if(direction=="intoY") with(tre,sprintf("\t%s %s %s%s;",id,dr,tr$id[prv],es)) else
with(tre,sprintf("\t%s %s %s%s;",tr$id[prv],dr,id,es))
code<-c(ifelse(direction=="none",'graph {','digraph {'),gr,vtx,edg,'}')
if(!missing(con)) writeLines(code,con) else return(code)
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/export.R
|
#' Extract the vertex hierarchy from the vistla tree
#'
#' Traverses the vistla tree in a depth-first order and
#' lists the visited vertices as a data frame.
#' @param x vistla object.
#' @return A data frame of a class \code{vistla_hierarchy}.
#' @note This function effectively prunes the tree off suboptimal paths.
#' @export
hierarchy<-function(x){
stopifnot(inherits(x,"vistla"))
if(sum(x$tree$leaf)==0){
Q<-data.frame(
name=x$yn,
score=NA_real_,
depth=-1,
leaf=FALSE,
prv=NA_integer_
)
names(Q)<-c("name","score","depth","leaf","prv")
class(Q)<-c("vistla_hierarchy","data.frame")
return(Q)
}
Q<-subset_tree(x$tree,x$tree$used)
which(is.na(Q$a))->ti
Qt<-Q[ti,]
Qt[Qt$used,]->Qt
Qt[!duplicated(Qt$b),]->Qt
nt<-nrow(Qt)
Qy<-data.frame(a=NA,b=NA,c=NA,score=NA,depth=-1,leaf=FALSE,used=TRUE,prv=NA)
Qh<-data.frame(
a=rep(NA,nt),
b=rep(NA,nt),
c=Qt$b,
score=Qt$score,
depth=0,
leaf=FALSE,
used=TRUE,
prv=1
)
Q$prv<-Q$prv+nt+1
Q$prv[ti]<-match(Q$b[ti],Qh$c)+1
rbind(Qy,Qh,Q)->Q
Q$firstsub<-Q$lastsub<-Q$nxtsib<-rep(NA,nrow(Q))
for(e in 1:nrow(Q)){
prv<-Q$prv[e]
if(!is.na(prv)){
if(is.na(Q$firstsub[prv])) Q$firstsub[prv]<-e
if(!is.na(Q$lastsub[prv])) Q$nxtsib[Q$lastsub[prv]]<-e
Q$lastsub[prv]<-e
}
}
Q$trord<-rep(NA,nrow(Q))
Q$visited<-rep(FALSE,nrow(Q))
cur<-1
ord<-1
while(!is.na(cur))
cur<-if(Q$visited[cur]){
if(!is.na(Q$nxtsib[cur])) Q$nxtsib[cur] else Q$prv[cur]
}else{
Q$trord[ord]<-cur
Q$visited[cur]<-TRUE
ord<-ord+1
if(!is.na(Q$firstsub[cur]))
Q$firstsub[cur] else
if(!is.na(Q$nxtsib[cur])) Q$nxtsib[cur] else Q$prv[cur]
}
Q<-subset_tree(Q,Q$trord)
Q[,c("c","score","depth","leaf","prv")]->Q
names(Q)[1]<-"name"
Q$name<-colnames(x$mi)[Q$name]
Q$name[is.na(Q$name)]<-x$yn
rownames(Q)<-NULL
class(Q)<-c("vistla_hierarchy","data.frame")
return(Q)
}
#' @rdname print.vistla
#' @method print vistla_hierarchy
#' @export
print.vistla_hierarchy<-function(x,...){
cat("\n\tVistla hierarchy\n\n")
V<-'| '
J<-'+'
cat(sprintf(
"%s%s%s%s",
sapply(x$depth+1,function(dc) paste(rep(V,dc),collapse="")),
J,x$name,
ifelse(x$depth>0,sprintf(" (%0.2g)",x$score),"")
),sep="\n")
cat("\n")
invisible(x)
}
#' Extract mutual information score matrix
#'
#' Produces a matrix \eqn{S} where \eqn{S_{ij}} is a
#' value of \eqn{I(X_i;X_j)}.
#' This matrix is always calculated as an initial step of the
#' vistla algorithm and stored in the vistla object.
#' @param x vistla object.
#' @return A symmetric square matrix with mutual information scores between features and root.
#' @export
mi_scores<-function(x){
stopifnot(inherits(x,"vistla"))
rbind(cbind(x$mi,x$miY),c(x$miY,NA))->ans
colnames(ans)[length(x$miY)+1]<-x$yn
rownames(ans)[length(x$miY)+1]<-x$yn
ans
}
#' Extract leaf scores of vertex pairs
#'
#' Produces a matrix \eqn{S} where \eqn{S_{ij}} is a score
#' of the path ending in vertices \eqn{i} and \eqn{j}.
#' Since vistla works on vertex pairs, this value is unique.
#' This can be interpreted as a feature similarity matrix
#' in context of the current vistla root.
#' @note This function should be called on an unpruned vistla tree,
#' otherwise the result will be mostly composed of zeroes.
#' @param x vistla object.
#' @return A square matrix with leaf scores of all feature pairs.
#' @export
leaf_scores<-function(x){
stopifnot(inherits(x,"vistla"))
x$mi*0->ans
ans[as.matrix(x$tree[,c("b","c")])]<-x$tree$score
ans
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/extract.R
|
make_df<-function(formula,data,enc){
if(missing(enc)) enc<-parent.frame()
if(missing(data)){
env<-enc
have<-c()
}else{
if(!is.data.frame(data)) stop("Data must be a data.frame")
env<-data
have<-names(data)
}
to_delete<-c()
to_add<-c()
new_features<-list()
has_dot<-FALSE
f<-stats::as.formula(formula)
Ye<-f[[2]]
Y<-eval(Ye,env,enc)
Yn<-deparse(Ye)
if(is.symbol(Ye)&&(Yn%in%have)) to_delete<-Yn
f[[3]]->f
while(TRUE){
if(length(f)==3){
oper<-deparse(f[[1]])
element<-f[[3]]
if(length(element)!=1)
if(!identical(element[[1]],quote(I)))
stop("Invalid sub-expression ",deparse(element))
}else{
#This is the last element
oper<-'+'
element<-f
}
if(oper=='-'){
if(!is.symbol(element))
stop(sprintf("Cannot omit something that is not a feature name (%s)",deparse(element)))
element<-deparse(element)
if(!(element%in%have))
stop(sprintf("Cannot omit %s which is not in data",element))
to_delete<-c(to_delete,element)
}else if(oper=='+'){
if(is.symbol(element)){
deparse(element)->en
if(en=='.'){
if(missing(data)) stop("Cannot use `.` without data")
has_dot<-TRUE
}else{
if(en%in%have){
to_add<-c(to_add,en)
}else{
eval(element,env,enc)->val
new_features<-c(new_features,stats::setNames(list(val),en))
}
}
}else{
eval(element,env,enc)->val
new_features<-c(new_features,stats::setNames(list(val),deparse(element)))
}
}else
stop(sprintf("Invalid operator `%s`; only `+` & `-` allowed",oper))
if(length(f)<3) break
f<-f[[2]]
}
if(has_dot){
to_delete<-setdiff(to_delete,to_add)
X<-data
if(length(to_delete)>0)
X<-X[,setdiff(names(X),to_delete),drop=FALSE]
if(length(new_features)>0)
X<-data.frame(X,new_features)
}else{
if(!missing(data)){
X<-data[,setdiff(to_add,to_delete),drop=FALSE]
if(length(new_features)>0)
X<-data.frame(X,new_features)
}else if(length(new_features)>0){
X<-data.frame(new_features)
} #else can't happen because of formula syntax properties; Y~ is invalid
}
list(X=X,Y=Y,yn=Yn)
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/formula.R
|
#' Extract all branches of the Vistla tree
#'
#' Gives access to a list of all branches in the tree.
#' @param x vistla object.
#' @param suboptimal if TRUE, sub-optimal branches are included.
#' @note Pruned trees (obtained with \code{\link{prune}} and using \code{targets} argument
#' in the \code{\link{vistla}} call) have no suboptimal branches.
#' @return A data frame collecting all branches traced by vistla.
#' Each row corresponds to a single branch, i.e., edge between feature pairs.
#' This way it is a triplet of original features, names of which are stored in \code{a},
#' \code{b} and \code{c} columns.
#' For instance, path \eqn{I \rightarrow J \rightarrow K \rightarrow L \rightarrow M}
#' would be stored in three rows, for \eqn{(a,b,c)}=\eqn{(I,J,K)}, \eqn{(J,K,L)}
#' and \eqn{(K,L,M)}.
#' The width of a path (minimal \eqn{\iota} value) between root and feature pair \eqn{(b,c)} is
#' stored in the \code{score} column.
#' \code{depth} stores the path depth, starting from 1 for pairs directly connected to the root,
#' and increasing by one for each additional feature.
#' Final column, \code{leaf}, is a logical path indicating whether the edge is a final segment
#' of the widest path between root and \eqn{c}.
#' @export
branches<-function(x,suboptimal=FALSE){
stopifnot(inherits(x,"vistla"))
tree<-x$tree[x$tree$used|suboptimal,c('a','b','c','score','depth','leaf')]
tree$a<-colnames(x$mi)[tree$a]
tree$a[is.na(tree$a)]<-x$yn
tree$b<-colnames(x$mi)[tree$b]
tree$c<-colnames(x$mi)[tree$c]
rownames(tree)<-NULL
tree
}
#' @rdname branches
#' @method as.data.frame vistla
#' @param row.names passed to \code{as.data.frame}.
#' @param optional passed to \code{as.data.frame}.
#' @param ... ignored.
#' @export
as.data.frame.vistla<-function(x,row.names=NULL,optional=FALSE,suboptimal=FALSE,...)
as.data.frame(branches(x,suboptimal),row.names=row.names,optional=optional)
#' Extract a single path
#'
#' Gives access to a vector of feature names over a path to a certain target feature.
#' @param x vistla object.
#' @param detailed if \code{TRUE}, suppresses default output and presents the same paths as a data frame featuring score.
#' @param target target feature name.
#' @return By default, a character vector with names of features along the path from \code{target} into root.
#' When \code{detailed} is set to \code{TRUE}, a \code{data.frame} in a format identical to this produced by
#' \code{\link{branches}}, yet without the \code{leaf} column.
#' @export
path_to<-function(x,target,detailed=FALSE){
stopifnot(inherits(x,"vistla"))
colnames(x$mi)->n
which(n==target)->idx
if(length(idx)!=1) stop(sprintf("Target feature %s was not in the training set",target))
which((x$tree$c==idx) & (x$tree$leaf))->br
if(length(br)>0){
ans<-integer(x$tree$depth[br])
for(e in 1:length(ans)){
ans[e]<-br
br<-x$tree$prv[br]
}
}else{
ans<-integer()
}
if(detailed){
x$tree[ans,c('a','b','c','score')]->ans
ans$a<-n[ans$a]
ans$a[is.na(ans$a)]<-x$yn
ans$b<-n[ans$b]
ans$c<-n[ans$c]
rownames(ans)<-NULL
}else{
if(length(ans)==0) return(character())
n[c(x$tree$c[ans[1]],x$tree$b[ans],x$tree$a[ans[length(ans)]])]->ans
ans[is.na(ans)]<-x$yn
}
ans
}
#' List all paths
#'
#' Executes \code{\link{path_to}} for all path possible targets and returns
#' a list with the results.
#' @param x vistla object.
#' @param targets_only if \code{TRUE}, only paths to targets are extracted.
#' By default, turned on when \code{x} has targets, and off otherwise.
#' @param detailed passed to \code{\link{path_to}}. If \code{TRUE},
#' suppresses default output and presents the same paths in a form of
#' data frames featuring score.
#' @return A named list with one element per leaf or target, containing
#' the path between this feature and root, in a format identical
#' to this used by the \code{\link{path_to}} function.
#' @export
paths<-function(x,targets_only=!is.null(x$targets),detailed=FALSE){
targets<-if(targets_only) c(x$targets) else x$tree$c[x$tree$leaf&x$tree$used]
colnames(x$mi)->n
targets<-n[targets]
stats::setNames(lapply(targets,function(t) path_to(x,t,detailed=detailed)),targets)
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/paths.R
|
#' Overview plot of the vistla tree
#'
#' Plots a vistla tree, using layout derived by a Buchheim et al. extension of the standard Reingold-Tilford method.
#' The tree root is placed on the left, while the paths extend to the right, with all branches of the same depth at the same horizontal coordinate.
#' The path are sorted vertically, from strongest on top to weakest on the bottom.
#' Link weight indicates, by default, the link's score.
#' A feature name in parentheses indicates that is is only a way-point in a path to some other feature.
#' @note The graph is rendered using the grid graphics system, in a manner similar to \code{ggplot2}; the output of the \code{plot.vistla} function is only a grid graphical object, while the actual plotting is done when this object is printed or plotted.
#' Yet, said object can be used with other functions in the grid ecosystem for rendering into files, being edited, combined with other plots, etc.
#' @method plot vistla
#' @param x vistla, vistla hierarchy or vistla plot object.
#' @param slant arrange vertices in a slanted way.
#' Can be given as a number, possibly negative, indicating the amount of slant, or as \code{TRUE}, for an auto value.
#' No slant is applied when set to 0 or omitted.
#' @param circular if given \code{TRUE}, switches to circular layout; alternatively, can be given two numbers, then the first one will be interpreted as an angle to fit the whole graph in (\code{2*pi} when using \code{TRUE}), and the second one as an initial angle offset (0 when using \code{TRUE}), which can be used to rotate the whole graph around the root.
#' Both angles are expected to be in radians.
#' It is recommended to add \code{asp=TRUE} parameter to make this layout truly circular, otherwise lines of equal depth are going to be elliptical.
#' When \code{FALSE}, linear layout is enforced.
#' @param edge_col edge colour; can be given as vector, then mapping order adheres to the one in hierarchy object; please note that the edge towards first feature, the root, is not drawn, so the first element is effectively ignored.
#' If given as a function, it is called on the internally generated extended hierarchy object, and the result is used as an aesthetic.
#' @param edge_lwd edge width; behaves similarly to \code{edge_col}, yet also accepts special value \code{'scale'}, which triggers default scaling of edge width to be proportional to score.
#' @param edge_lty edge line-type; behaves similarly to \code{edge_col}.
#' @param label_text vertex label text, feature name by default.
#' Behaves similarly to \code{edge_col}.
#' @param label_border_col vertex label border colour; behaves similarly to \code{edge_col}, can be set to 0 for no border.
#' @param label_border_lty vertex label border line-type; behaves similarly to \code{edge_col}, can be set to 0 for no border.
#' @param label_fill vertex label fill colour; behaves similarly to \code{edge_col}, can be set to 0 for no fill.
#' @param ... ignored.
#' @param asp1 if \code{TRUE}, scales on both axes are the same, like with \code{asp=1} in base graphics.
#' @param pmar Specifies margins as a fraction of graph size; expects a 4-element vector, in standard R bottom-left-top-right order.
#' @return Grid object with the graph.
#' @references "Drawing rooted trees in linear time" C. Buchheim, M. Jünger, S. Leipert. Software: Practice and Experience 36(6):651-665 (2006).
#' @export
plot.vistla<-function(
x,...,
slant,
circular,
asp1=FALSE,
pmar=c(0.05,0.05,0.05,0.05),
edge_col=1,
edge_lwd='scale',
edge_lty=1,
label_text=function(x) x$name,
label_border_col=1,
label_border_lty=function(x) ifelse(x$leaf,1,2),
label_fill='white'
){
#Plot layout planning
organise_plot(x)->trg
#Vertex and edge generators
wmar<-grid::unit(1,"strwidth","m")
hmar<-grid::unit(1,"strheight","m")
uu<-ifelse(asp1,'snpc','npc')
vertex<-function(x,y,lab,lty,fill,col){
if(asp1){
x<-grid::unit(.5,'npc')+grid::unit(x-0.5,'snpc')
y<-grid::unit(.5,'npc')+grid::unit(y-0.5,'snpc')
}else{
x<-grid::unit(x,'npc')
y<-grid::unit(y,'npc')
}
lb<-grid::textGrob(label=lab,x=x,y=y)
bkg<-grid::rectGrob(
x=x,y=y,
width=grid::unit(1,"grobwidth",lb)+wmar,
height=grid::unit(1,"grobheight",lb)+hmar,
gp=grid::gpar(fill=fill,col=col,lty=lty))
grid::grobTree(bkg,lb)
}
edge<-function(x0,y0,x1,y1,lwd,lty,col){
if(asp1){
hh<-grid::unit(.5,'npc')+grid::unit(c(x0,x1)-0.5,'snpc')
vv<-grid::unit(.5,'npc')+grid::unit(c(y0,y1)-0.5,'snpc')
}else{
hh<-grid::unit(c(x0,x1),'npc')
vv<-grid::unit(c(y0,y1),'npc')
}
grid::linesGrob(
hh,
vv,
gp=grid::gpar(lwd=lwd,col=col))
}
#Slant layout modifier
if(missing(slant)) slant<-0
if(identical(slant,TRUE)) slant<-0.5/max(trg$cidx)
if(slant!=0) trg$x<-trg$x-slant*trg$cidx
#Circular layout modifier
if(missing(circular)) circular<-FALSE
if(identical(circular,TRUE)) circular<-c(2*pi,0)
if(is.numeric(circular) && length(circular)==2){
trg$r<-trg$x+1
#Add 0.5 units of margin on both sides on the tree
trg$phi<-(trg$y-min(trg$y)+.5)/(diff(range(trg$y))+1)*circular[1]+circular[2]
trg$x<-trg$r*cos(trg$phi)
trg$y<-trg$r*sin(trg$phi)
}
stopifnot(is.numeric(pmar))
stopifnot(length(pmar)==4)
trg$x<-trg$x-min(trg$x)
trg$x<-if(max(trg$x)>0) trg$x/max(trg$x) else 0.5
trg$x<-trg$x*(1-pmar[2]-pmar[4])+pmar[2]
trg$y<-trg$y-min(trg$y)
trg$y<-if(max(trg$y)>0) trg$y/max(trg$y) else 0.5
trg$y<-trg$y*(1-pmar[1]-pmar[3])+pmar[1]
#Vertex styling
trg$lab<-if(is.function(label_text)) label_text(trg) else label_text
trg$label_border_col<-if(is.function(label_border_col)) label_border_col(trg) else label_border_col
trg$label_border_lty<-if(is.function(label_border_lty)) label_border_lty(trg) else label_border_lty
trg$label_fill<-if(is.function(label_fill)) label_fill(trg) else label_fill
#Special case for root only
if(nrow(trg)==1)
return(
as_vistla_plot(grid::grobTree(
vertex(.5,.5,trg$lab,trg$lty,trg$fill,trg$col)
))
)
#Edge styling
trg$wd<-(trg$score-min(trg$score,na.rm=TRUE))/(max(trg$score,na.rm=TRUE)-min(trg$score,na.rm=TRUE))*3+1
trg$wd[!is.finite(trg$wd)]<-1
trg$edge_col<-if(is.function(edge_col)) edge_col(trg) else edge_col
trg$edge_lty<-if(is.function(edge_lty)) edge_lty(trg) else edge_lty
trg$edge_lwd<-if(is.function(edge_lwd))
edge_lwd(trg) else if(identical(edge_lwd,'scale')) trg$wd else edge_lwd
#Edge ends
trg$xp<-trg$x[trg$prv]
trg$yp<-trg$y[trg$prv]
#Order by score to have important branches on top
trg<-trg[order(trg$score,na.last=FALSE),]
trg$prv<-NULL
#Make a grid object
V<-do.call(grid::gList,lapply(1:nrow(trg),function(e){
vertex(
trg$x[e],trg$y[e],
lab=trg$lab[e],
col=trg$label_border_col[e],
lty=trg$label_border_lty[e],
fill=trg$label_fill[e])
}))
E<-do.call(grid::gList,lapply(2:nrow(trg),function(e){
edge(trg$x[e],trg$y[e],trg$xp[e],trg$yp[e],col=trg$edge_col[e],lty=trg$edge_lty[e],lwd=grid::unit(trg$edge_lwd[e],'mm'))
}))
as_vistla_plot(grid::grobTree(E,V))
}
as_vistla_plot<-function(x){
class(x)<-c("vistla_plot",class(x))
x
}
#' @rdname plot.vistla
#' @method plot vistla_plot
#' @export
plot.vistla_plot<-function(x,...){
grid::grid.newpage()
grid::grid.draw(x)
}
#' @rdname plot.vistla
#' @method print vistla_plot
#' @export
print.vistla_plot<-function(x,...)
plot.vistla_plot(x,...)
#' @method plot vistla_hierarchy
#' @export
plot.vistla_hierarchy<-function(x,...)
plot.vistla(x,...)
organise_plot<-function(x){
if(inherits(x,"vistla")) x<-hierarchy(x)
stopifnot(inherits(x,"vistla_hierarchy"))
x$prv[is.na(x$prv)]<-0
x$idx<-1:nrow(x)
split(x,x$prv)->xs
xs<-lapply(xs,function(x){
x$cidx<-1:nrow(x)
x$nxtu<-c(0,x$idx[-length(x$idx)]) #Neighbour up
x$nxtd<-c(x$idx[-1],0) #Neighbour down
x$nxtf<-0 #First sub
x$nxtfd<-0 #Last sub
x
})
unsplit(xs,x$prv)->x
for(e in xs) #Try xs here
if(e$prv[1]!=0){
x$nxtf[e$prv[1]]<-e$idx[1]
x$nxtfd[e$prv[1]]<-e$idx[nrow(e)]
}
x<-TreeLayout(x,distance=1)
x<-x[,c("name","score","depth","leaf","prv","cidx","y")]
x$prv[1]<-NA
#Flip vertically
x$y<--x$y+x$y[1]
x$x<-x$depth
x
}
#R implementation of the pseudo-code from
# Buchheim, C., Jünger, M. and Leipert, S. (2006), Drawing rooted trees in linear time.
# Softw: Pract. Exper., 36: 651-665. https://doi.org/10.1002/spe.713
TreeLayout<-function(x,distance=1){
x$mod<-0
x$thread<-0
x$ancestor<-x$idx
x$shift<-0
x$change<-0
x$prelim<-0
defaultAncestor<-0
x$y<-0
NextUp<-function(v)
if(x$nxtf[v]>0) x$nxtf[v] else x$thread[v]
NextDown<-function(v)
if(x$nxtfd[v]) x$nxtfd[v] else x$thread[v]
Ancestor<-function(vim,v)
if(x$prv[x$ancestor[vim]]==x$prv[v]) x$ancestor[vim] else defaultAncestor
MoveSubtree<-function(wm,wp,shift){
subtrees<-(x$cidx[wp]-x$cidx[wm])
x$change[wp]<<-x$change[wp]-shift/subtrees
x$shift[wp]<<-x$shift[wp]+shift
x$change[wm]<<-x$change[wm]+shift/subtrees
x$prelim[wp]<<-x$prelim[wp]+shift
x$mod[wp]<<-x$mod[wp]+shift
}
Apportion<-function(v){
w<-x$nxtu[v]
if(w>0){
vip<-v0p<-v
vim<-w
v0m<-x$nxtf[x$prv[vip]]
sip<-x$mod[vip]
s0p<-x$mod[v0p]
sim<-x$mod[vim]
s0m<-x$mod[v0m]
while(NextDown(vim)!=0 && NextUp(vip)!=0){
vim<-NextDown(vim)
vip<-NextUp(vip)
v0m<-NextUp(v0m)
v0p<-NextDown(v0p)
x$ancestor[v0p]<<-v
shift<-(x$prelim[vim]+sim)-(x$prelim[vip]+sip)+distance
if(shift>0){
MoveSubtree(Ancestor(vim,v),v,shift)
sip<-sip+shift
s0p<-s0p+shift
}
sim<-sim+x$mod[vim]
sip<-sip+x$mod[vip]
s0m<-s0m+x$mod[v0m]
s0p<-s0p+x$mod[v0p]
}
if(NextDown(vim)!=0 && NextDown(v0p)==0){
x$thread[v0p]<<-NextDown(vim)
x$mod[v0p]<<-x$mod[v0p]+sim-s0p
}
if(NextUp(vip)!=0 && NextUp(v0m)==0){
x$thread[v0m]<<-NextUp(vip)
x$mod[v0m]<<-x$mod[v0m]+sip-s0m
defaultAncestor<<-v
}
}
}
ExecuteShifts<-function(v){
shift<-0
change<-0
w<-x$nxtfd[v]
while(w>0){
x$prelim[w]<<-x$prelim[w]+shift
x$mod[w]<<-x$mod[w]+shift
change<-change+x$change[w]
shift<-shift+x$shift[w]+change
w<-x$nxtd[w]
}
}
FirstWalk<-function(v){
if(x$nxtf[v]==0){
x$prelim[v]<<-0
w<-x$nxtu[v]
if(w>0)
x$prelim[v]<<-x$prelim[w]+distance
}else{
w<-defaultAncestor<<-x$nxtf[v]
while(w!=0){
FirstWalk(w)
Apportion(w)
w<-x$nxtd[w]
}
ExecuteShifts(v)
midpoint<-.5*(x$prelim[x$nxtf[v]]+x$prelim[x$nxtfd[v]])
w<-x$nxtu[v]
if(w>0){
x$prelim[v]<<-x$prelim[w]+distance
x$mod[v]<<-x$prelim[v]-midpoint
}else{
x$prelim[v]<<-midpoint
}
}
}
SecondWalk<-function(v,m){
x$y[v]<<-x$prelim[v]+m
w<-x$nxtf[v]
while(w!=0){
SecondWalk(w,m+x$mod[v])
w<-x$nxtd[w]
}
}
FirstWalk(1)
SecondWalk(1,x$prelim[1])
x
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/plot.R
|
#' Prune the vistla tree
#'
#' This function allows to filter out suboptimal branches, as well as weak ones or these not in particular paths of interest.
#' @param x vistla object.
#' @param targets a character vector of features.
#' When not missing, all branches not on lying paths to these targets are pruned.
#' Unreachable targets are ignored, while names not present in the analysed set cause an error.
#' @param iomin a single numerical value.
#' When given, it effectively overrides the value of \code{iomin} given to the \code{vistla} invocation; to this end, it can only be higher then the original value, since prune only modifies the output and cannot re-run the pathfinding.
#' @return Pruned \code{x}; if both arguments are missing, this function still removes suboptimal branches.
#' @examples
#' \dontrun{
#' data(chain)
#' v<-vistla(Y~.,data=chain)
#' print(v)
#' print(prune(v,targets="M3"))
#' print(prune(v,iomin=0.3))
#' }
#' @export
prune<-function(x,targets,iomin){
stopifnot(inherits(x,"vistla"))
if(!missing(iomin)){
if(iomin<x$iomin) stop("Prune can only increase iomin")
subset_tree(x$tree,x$tree$score>iomin)->x$tree
x$iomin<-iomin
}
if(!missing(targets)){
match(targets,colnames(x$mi))->ti
if(any(is.na(ti))) stop("Unknown names in targets")
if(!is.null(x$targets)){
#Tree was already pruned; are we trying to extend?
if(!all((ti%in%x$targets)|(ti%in%(x$tree$c[x$tree$leaf&x$tree$used])))) stop("Prune can only remove targets")
}
return(prune_targets(x,ti))
}
prune_targets(x)
}
#Internal engine of prune, used by vistla.data.frame as well
prune_targets<-function(x,ti){
tree<-x$tree
to_keep<-if(missing(ti))
which(tree$leaf) else which((tree$c%in%ti)&tree$leaf)
keep<-rep(FALSE,nrow(tree))
while(length(to_keep)>0){
keep[to_keep]<-TRUE
tree$prv[to_keep]->to_keep
unique(to_keep[!is.na(to_keep)])->to_keep
}
x$tree<-subset_tree(tree,keep)
if(nrow(x$tree)>0)
x$tree$used<-TRUE
if(!missing(ti)) x$targets<-ti
x
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/prune.R
|
subset_links<-function(links,subset)
match(
links,
(1:length(links))[subset],
)[subset]
subset_tree<-function(tree,subset){
st<-tree[subset,]
st$prv<-subset_links(tree$prv,subset)
st
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/tools.R
|
#' @useDynLib vistla, .registration=TRUE
NULL
#' @rdname vistla
#' @export
vistla<-function(x,...)
UseMethod("vistla")
#' @rdname vistla
#' @param formula alternatively, formula describing the task, in a form \code{root~predictors}, which adheres to standard R behaviours.
#' Accepts \code{+} to add a predictor, \code{-} to omit one, and \code{.} to import whole \code{data}.
#' Use \code{\link{I}} to calculate new predictors.
#' When present in \code{data}, response is getting omitted from predictors.
#' @param data \code{data.frame} in context of which the formula will be executed; can be omitted when not using \code{.}.
#' @export
#' @method vistla formula
vistla.formula<-function(formula,data,...,yn){
make_df(formula,data,parent.frame())->x
if(missing(yn)) yn<-x$yn
vistla.data.frame(x$X,x$Y,yn=yn,...)
}
#' Influence path identification with the Vistla algorithm
#'
#' Detects influence paths.
#' @rdname vistla
#' @param x data frame of predictors.
#' @param y vistla tree root, a feature from which influence paths will be traced.
#' @param flow algorithm mode, specifying the iota function which gives local score to an edge of an edge graph.
#' If in doubt, use the default, \code{"fromdown"}.
#' @param iomin score threshold below which path is not considered further.
#' The higher value the less paths are generated, which also lowers the time taken by the function.
#' The default value of 0 turns of this filtering.
#' The same effect can be later achieved with the \code{\link{prune}} function.
#' @param targets a vector of target feature names.
#' If given, the algorithm will stop just after reaching the last of them, rather than after tracing all paths from the root.
#' The same effect can be later achieved with the \code{\link{prune}} function.
#' This is a simple method to remove irrelevant paths, yet it comes with a substantial increase in computational burden.
#' @param verbose when set to \code{TRUE}, turns on reporting of the algorithm progress.
#' @param estimator mutual information estimator to use.
#' \code{"mle"} --- maximal likelihood, requires all features to be discrete (factors or booleans).
#' \code{"kt"} --- Kendall transformation, requires all features to be either ordinal (numeric, integer or ordered factor) or bi-valued (two-level factors or booleans).
#' @param yn name of the root (\code{Y} value), used in result pretty-printing and plots.
#' Must be a single-element character vector.
#' @param threads number of threads to use.
#' When missing or set to 0, vistla uses all available cores.
#' @param ... pass-through arguments, ignored.
#' @return The tracing results represented as an object of a class \code{vistla}.
#' Use \code{\link{paths}} and \code{\link{path_to}} functions to extract individual paths,
#' \code{\link{branches}} to get the whole tree and \code{\link{mi_scores}} to get the basic score matrix.
#' @references "Kendall transformation brings a robust categorical representation of ordinal data" M.B. Kursa. SciRep 12, 8341 (2022).
#' @method vistla data.frame
#' @export
vistla.data.frame<-function(x,y,...,flow,iomin,targets,estimator=c("mle","kt"),verbose=FALSE,yn="Y",threads){
targets<-if(!missing(targets))
unique(match(targets,names(x))) else integer(0)
if(any(is.na(targets))) stop("Unknown variables specified as targets")
if(missing(flow)) flow<-1L+8L
if(is.character(flow)) flow<-vistla::flow(flow)
if(missing(iomin)) iomin<-0
if(missing(threads)) threads<-0L
#Prepare input
estimator<-match.arg(estimator)
ec<-if(estimator=="mle") 1L else if(estimator=="kt") 2L else 17L;
#Execute
ans<-.Call(
C_vistla,x,y,
as.integer(flow)[1],ec,
iomin,targets,verbose,
as.integer(threads)
)
#Enhance the output
ans$yn<-yn
ans$iomin<-iomin
stats::setNames(
data.frame(ans$tree),
c("a","b","c","score","depth","leaf","used","prv")
)->ans$tree
class(ans)<-"vistla"
ans$flow<-flow
class(ans$flow)<-"vistla_flow"
if(length(targets)>0)
ans<-prune_targets(ans,targets)
ans
}
#' Construct the value for the flow
#'
#' Vistla builds the tree by optimising the influence score over path, which is given by the iota function.
#' The \code{flow} argument of the vistla function can be used to modify the default iota and some associated behaviours.
#' This function can be used to construct the proper value of this argument.
#' @param code Character code of the flow parameter, like \code{"fromdown"}.
#' If given, overrides other arguments.
#' @param from if \code{TRUE}, paths must satisfy data processing inequality as going from the root.
#' @param into if \code{TRUE}, paths must satisfy data processing inequality as going into the root.
#' @param down if \code{TRUE}, subsequent features on the path must have lower mutual information with the root; by default, true when \code{from} is true but if both \code{from} and \code{into} are true.
#' Can't be true together with \code{up}.
#' @param up if \code{TRUE}, subsequent features on the path must have higher mutual information with the root; by default, true when \code{into} is true but if both \code{from} and \code{into} are true.
#' Can't be true together with \code{down}.
#' @param forcepath when neither \code{up} or \code{down} is true, vistla may output walks rather than paths, i.e., sequences of features which are not unique.
#' Yet, when this argument is set to \code{TRUE}, additional condition is checked to forbid such self-intersections.
#' One should note that this check is computationally expensive, though.
#' By default true when both \code{up} and \code{down} are false.
#' @param ... ignored.
#' @return A \code{vistla_flow} object which can be passed to the \code{vistla} function;
#' in practice, a single integer value.
#' @export
flow<-function(code,...,from=TRUE,into=FALSE,down,up,forcepath){
codes<-c('from'=1L,'from!'=17L,'into'=2L,'into!'=18L,'spread'=0L,'spread!'=16L,
'fromdown'=1L+8L,'both'=3L,'both!'=3L+16L,'intoup'=2L+4L,'down'=8L,'up'=4L)
if(!missing(code)){
ans<-if(is.integer(code)) code else {
if(is.character(code)){
codes[code]
}else stop("Wrong value of code ")
}
if(!is.integer(ans) || is.na(ans)) stop("Unknown code ",code)
}else{
if(missing(down)) down<-from & !into
if(missing(up)) up<-into & !from
if(missing(forcepath)) forcepath<-!up & !down
ans<-as.integer(sum(
c(from,into,up,down,forcepath)*
2^(0:4)
))
}
class(ans)<-"vistla_flow"
ans
}
flow2char<-function(x)
paste(
c("spread","from","into","both")[bitwAnd(x,3L)+1],
ifelse(bitwAnd(x,4L)>0,"up",""),
ifelse(bitwAnd(x,8L)>0,"down",""),
ifelse(bitwAnd(x,16L)>0,"!",""),
sep=""
)
#' @rdname flow
#' @method print vistla_flow
#' @param x flow value to print.
#' @export
print.vistla_flow<-function(x,...){
cat(paste(
"Vistla flow: ",
flow2char(x),
"\n",
sep=""))
invisible(x)
}
#' @rdname vistla
#' @method vistla default
#' @export
vistla.default<-function(x,...)
stop("Expecting a formula or a data.frame as an input, got ",paste(class(x),collapse="/"))
#' Print vistla objects
#'
#' Utility functions to print vistla objects.
#' @method print vistla
#' @param x vistla object.
#' @param n maximal number of paths to preview.
#' @param ... ignored.
#' @return Invisible copy of \code{x}.
#' @export
print.vistla<-function(x,n=7L,...){
stopifnot(inherits(x,"vistla"))
stopifnot(n>0)
pruned<-(x$iomin>0)||(!is.null(x$targets))
cat(sprintf("\n\tVistla tree rooted in %s%s\n\n",x$yn,ifelse(pruned,", pruned","")))
nl<-sum(x$tree$leaf)
if(nl==0){
cat("No paths.\n\n")
return(invisible(x))
}
prev<-if(is.null(x$targets)){
x$tree[x$tree$leaf & x$tree$used,c("c","score","depth")]
}else{
x$tree[(x$tree$c%in%x$targets) & x$tree$leaf & x$tree$used,c("c","score","depth")]
}
pn<-nrow(prev)
if(pn>n) prev<-prev[1:n,]
cat(
if(is.null(x$targets)){
if(pn==1) "Path:" else "Paths:"
}else{
if(pn==1) "Path to specified target:" else "Paths to specified targets:"
}
)
prev$c<-colnames(x$mi)[prev$c]
for(e in 1:nrow(prev)){
pp<-path_to(x,prev$c[e])[-1]
if(pn>1) pp[-length(pp)]->pp
pp<-paste(pp,collapse=" ~ ")
cat(paste(strwrap(sprintf(
if(e==1) "%s (score %0.2g) ~ %s" else "%s (%0.2g) ~ %s",
prev$c[e],prev$score[e],pp),initial='\n - ',prefix=' '),collapse="\n"))
}
if(pn>n) cat(sprintf("\n\t[%d more]",pn-nrow(prev)))
if(pn>1) cat(sprintf("\n\t\t ... ~ %s\n\n",x$yn)) else cat("\n\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vistla/R/vistla.R
|
#' @title Launch shiny app
#' @description Launches shiny app for visualizing distributions.
#' @examples
#' \dontrun{
#' vdist_launch_app ()
#' }
#' @export
#'
vdist_launch_app <- function() {
xplorerr::app_descriptive()
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-app.R
|
#' Visualize binomial distribution
#'
#' Visualize how changes in number of trials and the probability of
#' success affect the shape of the binomial distribution. Compute & visualize
#' probability from a given quantile and quantiles out of given probability.
#'
#' @param n Number of trials.
#' @param p Aggregate probability.
#' @param s Number of success.
#' @param type Lower/upper/exact/interval.
#' @param tp Probability of success in a trial.
#' @param print_plot logical; if \code{TRUE}, prints the plot else returns a plot object.
#'
#' @examples
#' # visualize binomial distribution
#' vdist_binom_plot(10, 0.3)
#'
#' # visualize probability from a given quantile
#' vdist_binom_prob(10, 0.3, 4, type = 'exact')
#' vdist_binom_prob(10, 0.3, 4, type = 'lower')
#' vdist_binom_prob(10, 0.3, 4, type = 'upper')
#' vdist_binom_prob(10, 0.3, c(4, 6), type = 'interval')
#'
#'
#' # visualize quantiles out of given probability
#' vdist_binom_perc(10, 0.5, 0.05)
#' vdist_binom_perc(10, 0.5, 0.05, "upper")
#'
#' @seealso \code{\link[stats]{Binomial}}
#'
#'
#' @export
#'
vdist_binom_plot <- function(n = 10, p = 0.3, print_plot = TRUE) {
check_numeric(n)
check_numeric(p, "p")
check_range(p)
n <- as.integer(n)
x <- seq(0, n, 1)
xn <- n / 40
bm <- round(n * p, 2)
bsd <- round(sqrt((1 - p) * bm) , 2)
data <- dbinom(x, n, p)
plot_data <- data.frame(n = seq(0, n), df = data)
pp <-
ggplot(plot_data) +
geom_col(aes(x = n, y = df), fill = "blue") +
ylab("Probability") + xlab("No. of success") +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste("Mean =", bm, ", Std. Dev. =", bsd)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
scale_x_continuous(breaks = seq(0, n))
if (print_plot) {
print(pp)
} else {
return(pp)
}
}
#' @rdname vdist_binom_plot
#' @export
#'
vdist_binom_prob <- function(n = 10, p = 0.3, s = 4,
type = c("lower", "upper", "exact", "interval"),
print_plot = TRUE) {
check_range(p)
check_numeric(n)
check_numeric(p, "p")
check_numeric(s, "s")
method <- match.arg(type)
if (method == "interval") {
if (length(s) != 2) {
stop("Please specify an interval for s.", call. = FALSE)
}
}
if (any(s > n)) {
stop("s must be less than or equal to n.", call. = FALSE)
}
n <- as.integer(n)
s <- as.integer(s)
x <- seq(0, n, 1)
bm <- round(n * p, 2)
bsd <- round(sqrt((1 - p) * bm), 2)
if (method == "lower") {
k <- round(pbinom(s, n, p), 3)
cols <- ifelse(cumsum(round(dbinom(x, n, p), 3)) <= k, "#0000CD", "#6495ED")
} else if (method == "upper") {
k <- round(1 - pbinom((s - 1), n, p), 3)
cols <- ifelse(cumsum(round(dbinom(x, n, p), 3)) >= k, "#0000CD", "#6495ED")
} else if (method == "exact") {
k <- pbinom(s, n, p) - pbinom((s - 1), n, p)
cols <- ifelse(round(dbinom(x, n, p), 5) == round(k, 5), "#0000CD", "#6495ED")
} else {
k1 <- pbinom((s[1] - 1), n, p)
k2 <- pbinom(s[2], n, p)
k <- pbinom(s[2], n, p) - pbinom((s[1] - 1), n, p)
cols <- ifelse((round(cumsum(dbinom(x, n, p)), 6) > round(k1, 6) &
round(cumsum(dbinom(x, n, p)), 6) <= round(k2, 6)), "#0000CD", "#6495ED")
}
data <- dbinom(x, n, p)
plot_data <- data.frame(n = seq(0, n), df = data)
pp <-
ggplot(plot_data) +
geom_col(aes(x = n, y = df), fill = cols) +
ylab("Probability") +
xlab(paste("No. of success\n", "Mean =", bm, ", Std. Dev. =", bsd)) +
scale_x_continuous(breaks = seq(0, n)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste("P(X) <=", s, "=", round(k, 3)))
} else if (method == "upper") {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste("P(X) >=", s, "=", round(k, 3)))
} else if (method == "exact") {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste("P(X) =", s, "=", round(k, 3)))
} else {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste0("P(", s[1], " <= X <= ", s[2], ")", " = ", round(k, 3)))
}
if (print_plot) {
print(pp)
} else {
return(pp)
}
}
#' @rdname vdist_binom_plot
#' @export
#'
vdist_binom_perc <- function(n = 10, p = 0.5, tp = 0.05, type = c("lower", "upper"),
print_plot = TRUE) {
check_numeric(n)
check_numeric(p, "p")
check_numeric(tp, "tp")
check_range(p)
check_range(tp, 0, 0.5, "tp")
n <- as.integer(n)
method <- match.arg(type)
x <- seq(0, n, 1)
if (method == "lower") {
k <- round(qbinom(tp, n, p), 3)
cols <- ifelse(cumsum(dbinom(x, n, p)) <= pbinom(k, n, p), "#0000CD", "#6495ED")
} else {
k <- round(qbinom(tp, n, p, lower.tail = F), 3)
cols <- ifelse(cumsum(dbinom(x, n, p)) > pbinom((k + 1), n, p), "#0000CD", "#6495ED")
}
data <- dbinom(x, n, p)
plot_data <- data.frame(n = seq(0, n), df = data)
pp <-
ggplot(plot_data) +
geom_col(aes(x = n, y = df), fill = cols) +
ylab("Probability") + xlab("No. of success") +
scale_x_continuous(breaks = seq(0, n)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste0("P(X <= ", k, ") <= ", tp, ", but P(X <= ", (k + 1),
") > ", tp))
} else {
pp +
ggtitle(label = paste("Binomial Distribution: n =", n, ", p =", p),
subtitle = paste0("P(X >= ", (k + 1), ") <= ", tp, ", but P(X >= ", k,
") > ", tp))
}
if (print_plot) {
print(pp)
} else {
return(pp)
}
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-binomial.R
|
#' Visualize chi square distribution
#'
#' Visualize how changes in degrees of freedom affect the shape of
#' the chi square distribution. Compute & visualize quantiles out of given
#' probability and probability from a given quantile.
#'
#' @param df Degrees of freedom.
#' @param probs Probability value.
#' @param perc Quantile value.
#' @param type Lower tail or upper tail.
#' @param normal If \code{TRUE}, normal curve with same \code{mean} and
#' \code{sd} as the chi square distribution is drawn.
#' @param xaxis_range The upper range of the X axis.
#' @param print_plot logical; if \code{TRUE}, prints the plot else returns a plot object.
#'
#' @examples
#' # visualize chi square distribution
#' vdist_chisquare_plot()
#' vdist_chisquare_plot(df = 5)
#' vdist_chisquare_plot(df = 5, normal = TRUE)
#'
#' # visualize quantiles out of given probability
#' vdist_chisquare_perc(0.165, 8, 'lower')
#' vdist_chisquare_perc(0.22, 13, 'upper')
#'
#' # visualize probability from a given quantile.
#' vdist_chisquare_prob(13.58, 11, 'lower')
#' vdist_chisquare_prob(15.72, 13, 'upper')
#'
#' @seealso \code{\link[stats]{Chisquare}}
#'
#' @export
#'
vdist_chisquare_plot <- function(df = 3, normal = FALSE,
xaxis_range = 25, print_plot = TRUE) {
check_numeric(df, "df")
check_logical(normal)
df <- as.integer(df)
chim <- round(df, 3)
chisd <- round(sqrt(2 * df), 3)
x <- seq(0, xaxis_range, 0.01)
data <- dchisq(x, df)
plot_data <- data.frame(x = x, chi = data)
poly_data <- data.frame(y = c(0, seq(0, 25, 0.01), 25),
z = c(0, dchisq(seq(0, 25, 0.01), df), 0))
point_data <- data.frame(x = chim, y = min(data))
nline_data <- data.frame(x = x, y = dnorm(x, chim, chisd))
pp <-
ggplot(plot_data) +
geom_line(aes(x, chi), color = '#4682B4', size = 2) +
ggtitle(label = "Chi Square Distribution",
subtitle = paste("df =", df)) +
ylab('') +
xlab(paste("Mean =", chim, " Std Dev. =", chisd)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
scale_x_continuous(breaks = seq(0, xaxis_range, 2)) +
geom_polygon(data = poly_data,
mapping = aes(x = y, y = z),
fill = '#4682B4') +
geom_point(data = point_data,
mapping = aes(x = x, y = y),
shape = 4,
color = 'red',
size = 3)
if (normal) {
pp <-
pp +
geom_line(data = nline_data, mapping = aes(x = x, y = y),
color = '#FF4500')
}
if (print_plot) {
print(pp)
} else {
return(pp)
}
}
#' @rdname vdist_chisquare_plot
#' @export
#'
vdist_chisquare_perc <- function(probs = 0.95, df = 3,
type = c("lower", "upper"),
print_plot = TRUE) {
check_numeric(probs, "probs")
check_numeric(df, "df")
check_range(probs, 0, 1, "probs")
df <- as.integer(df)
method <- match.arg(type)
chim <- round(df, 3)
chisd <- round(sqrt(2 * df), 3)
l <- vdist_chiseql(chim, chisd)
ln <- length(l)
if (method == "lower") {
pp <- round(qchisq(probs, df), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
pp <- round(qchisq(probs, df, lower.tail = F), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
}
xm <- vdist_xmm(chim, chisd)
plot_data <- data.frame(x = l, y = dchisq(l, df))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = "blue") +
xlab(paste("Mean =", chim, " Std Dev. =", chisd)) +
ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = paste("Chi Square Distribution: df =", df),
subtitle = paste0("P(X < ", pp, ") = ", probs * 100, "%")) +
annotate("text",
label = paste0(probs * 100, "%"),
x = pp - chisd,
y = max(dchisq(l, df)) + 0.02,
color = "#0000CD",
size = 3) +
annotate("text",
label = paste0((1 - probs) * 100, "%"),
x = pp + chisd,
y = max(dchisq(l, df)) + 0.02,
color = "#6495ED",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = paste("Chi Square Distribution: df =", df),
subtitle = paste0("P(X > ", pp, ") = ", probs * 100, "%")) +
annotate("text",
label = paste0((1 - probs) * 100, "%"),
x = pp - chisd,
y = max(dchisq(l, df)) + 0.02,
color = "#6495ED",
size = 3) +
annotate("text",
label = paste0(probs * 100, "%"),
x = pp + chisd,
y = max(dchisq(l, df)) + 0.02,
color = "#0000CD",
size = 3)
}
for (i in seq_len(length(l1))) {
pol_data <- vdist_pol_chi(lc[l1[i]], lc[l2[i]], df)
gplot <-
gplot +
geom_polygon(data = pol_data,
mapping = aes(x = x, y = y),
fill = col[i])
}
point_data <- data.frame(x = pp, y = min(dchisq(l, df)))
gplot <-
gplot +
geom_vline(xintercept = pp,
linetype = 2,
size = 1) +
geom_point(data = point_data,
mapping = aes(x = x, y = y),
shape = 4,
color = 'red',
size = 3) +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = seq(0, xm[2], by = 5))
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_chisquare_plot
#' @export
#'
vdist_chisquare_prob <- function(perc = 13, df = 11, type = c("lower", "upper"),
print_plot = TRUE) {
check_numeric(df, "df")
check_numeric(perc, "perc")
method <- match.arg(type)
chim <- round(df, 3)
chisd <- round(sqrt(2 * df), 3)
l <- if (perc < 25) {
seq(0, 25, 0.01)
} else {
seq(0, (perc + (3 * chisd)), 0.01)
}
ln <- length(l)
if (method == "lower") {
pp <- round(pchisq(perc, df), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
pp <- round(pchisq(perc, df, lower.tail = F), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
}
plot_data <- data.frame(x = l, y = dchisq(l, df))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = "blue") +
xlab(paste("Mean =", chim, " Std Dev. =", chisd)) +
ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = paste("Chi Square Distribution: df =", df),
subtitle = paste0("P(X < ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc - chisd, y = max(dchisq(l, df)) + 0.02, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc + chisd, y = max(dchisq(l, df)) + 0.02, color = "#6495ED",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = paste("Chi Square Distribution: df =", df),
subtitle = paste0("P(X > ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc - chisd, y = max(dchisq(l, df)) + 0.02, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc + chisd, y = max(dchisq(l, df)) + 0.02, color = "#0000CD",
size = 3)
}
for (i in seq_len(length(l1))) {
pol_data <- vdist_pol_chi(lc[l1[i]], lc[l2[i]], df)
gplot <-
gplot +
geom_polygon(data = pol_data,
mapping = aes(x = x, y = y),
fill = col[i])
}
point_data <- data.frame(x = perc,
y = min(dchisq(l, df)))
gplot <-
gplot +
geom_vline(xintercept = perc,
linetype = 2,
size = 1) +
geom_point(data = point_data,
mapping = aes(x = x, y = y),
shape = 4,
color = 'red',
size = 3) +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = seq(0, l[ln], by = 5))
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
vdist_chiseql <- function(mean, sd) {
lmin <- mean - (5 * sd)
lmax <- mean + (5 * sd)
seq(lmin, lmax, 0.01)
}
vdist_xmm <- function(mean, sd) {
xmin <- mean - (5 * sd)
xmax <- mean + (5 * sd)
c(xmin, xmax)
}
vdist_pol_chi <- function(l1, l2, df) {
x <- c(l1, seq(l1, l2, 0.01), l2)
y <- c(0, dchisq(seq(l1, l2, 0.01), df), 0)
data.frame(x = x, y = y)
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-chisquare.R
|
#' Visualize f distribution
#'
#' @description Visualize how changes in degrees of freedom affect the
#' shape of the F distribution. Compute & visualize quantiles out of given
#' probability and probability from a given quantile.
#'
#' @param num_df Degrees of freedom associated with the numerator of f statistic.
#' @param den_df Degrees of freedom associated with the denominator of f statistic.
#' @param normal If \code{TRUE}, normal curve with same \code{mean} and
#' \code{sd} as the F distribution is drawn.
#' @param probs Probability value.
#' @param perc Quantile value.
#' @param type Lower tail or upper tail.
#' @param print_plot logical; if \code{TRUE}, prints the plot else returns a plot object.
#'
#' @examples
#' # visualize F distribution
#' vdist_f_plot()
#' vdist_f_plot(6, 10, normal = TRUE)
#'
#' # visualize probability from a given quantile
#' vdist_f_perc(0.95, 3, 30, 'lower')
#' vdist_f_perc(0.125, 9, 35, 'upper')
#'
#' # visualize quantiles out of given probability
#' vdist_f_prob(2.35, 5, 32)
#' vdist_f_prob(1.5222, 9, 35, type = "upper")
#'
#' @seealso \code{\link[stats]{FDist}}
#'
#' @export
#'
vdist_f_plot <- function(num_df = 4, den_df = 30, normal = FALSE,
print_plot = TRUE) {
check_numeric(num_df, "num_df")
check_numeric(den_df, "den_df")
check_logical(normal)
num_df <- as.integer(num_df)
den_df <- as.integer(den_df)
fm <- round(den_df / (den_df - 2), 3)
fsd <- round(sqrt((2 * (fm ^ 2) * (num_df + den_df - 2)) / (num_df * (den_df - 4))), 3)
x <- seq(0, 4, 0.01)
nx <- seq(-2, 4, 0.01)
plot_data <- data.frame(x = x, y = df(x, num_df, den_df))
poly_data <- data.frame(y = c(0, seq(0, 4, 0.01), 4),
z = c(0, df(seq(0, 4, 0.01), num_df, den_df), 0))
point_data <- data.frame(x = fm, y = 0)
nline_data <- data.frame(x = nx, y = dnorm(nx, fm, fsd))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = "blue") +
geom_polygon(data = poly_data, mapping = aes(x = y, y = z),
fill = '#4682B4') +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3) +
xlab(paste("Mean =", fm, " Std Dev. =", fsd)) + ylab('') +
ggtitle(label = 'f Distribution',
subtitle = paste("Num df =", num_df, " Den df =", den_df)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
scale_x_continuous(breaks = c(-2:4)) +
scale_y_continuous(breaks = NULL)
if (normal) {
gplot <-
gplot +
geom_line(data = nline_data, mapping = aes(x = x, y = y),
color = '#FF4500')
}
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_f_plot
#' @export
#'
vdist_f_perc <- function(probs = 0.95, num_df = 3, den_df = 30,
type = c("lower", "upper"), print_plot = TRUE) {
check_numeric(num_df, "num_df")
check_numeric(den_df, "den_df")
check_numeric(probs, "probs")
check_range(probs, 0, 1, "probs")
num_df <- as.integer(num_df)
den_df <- as.integer(den_df)
method <- match.arg(type)
fm <- round(den_df / (den_df - 2), 3)
fsd <- round(sqrt((2 * (fm ^ 2) * (num_df + den_df - 2)) / (num_df * (den_df - 4))), 3)
l <- seq(0, 4, 0.01)
ln <- length(l)
if (method == "lower") {
pp <- round(qf(probs, num_df, den_df), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
pp <- round(qf(probs, num_df, den_df, lower.tail = F), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
}
plot_data <- data.frame(x = l, y = df(l, num_df, den_df))
gplot <-
ggplot(plot_data) +
geom_line(data = plot_data, mapping = aes(x = x, y = y),
color = 'blue') + xlab(paste("Mean =", fm, " Std Dev. =", fsd)) +
ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = 'f Distribution',
subtitle = paste0("P(X < ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp - 0.2, y = max(df(l, num_df, den_df)) + 0.02, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp + 0.2, y = max(df(l, num_df, den_df)) + 0.02, color = "#6495ED",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = 'f Distribution',
subtitle = paste0("P(X > ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp - 0.2, y = max(df(l, num_df, den_df)) + 0.02, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp + 0.2, y = max(df(l, num_df, den_df)) + 0.02, color = "#0000CD",
size = 3)
}
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_f(lc[l1[i]], lc[l2[i]], num_df, den_df)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y),
fill = col[i])
}
pln <- length(pp)
for (i in seq_len(pln)) {
point_data <- data.frame(x = pp[i], y = 0)
gplot <-
gplot +
geom_vline(xintercept = pp[i], linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
}
gplot <-
gplot +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = 0:5)
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_f_plot
#' @export
#'
vdist_f_prob <- function(perc = 2.35, num_df = 5, den_df = 32, type = c("lower", "upper"),
print_plot = TRUE) {
check_numeric(perc, "perc")
check_numeric(num_df, "num_df")
check_numeric(den_df, "den_df")
num_df <- as.integer(num_df)
den_df <- as.integer(den_df)
method <- match.arg(type)
fm <- round(den_df / (den_df - 2), 3)
fsd <- round(sqrt((2 * (fm ^ 2) * (num_df + den_df - 2)) / (num_df * (den_df - 4))), 3)
l <- if (perc < 4) {
seq(0, 4, 0.01)
} else {
seq(0, (perc * 1.25), 0.01)
}
ln <- length(l)
if (method == "lower") {
pp <- round(pf(perc, num_df, den_df), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
pp <- round(pf(perc, num_df, den_df, lower.tail = F), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
}
plot_data <- data.frame(x = l, y = df(l, num_df, den_df))
gplot <-
ggplot(plot_data) +
geom_line(data = plot_data, mapping = aes(x = x, y = y),
color = 'blue') + xlab(paste("Mean =", fm, " Std Dev. =", fsd)) +
ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = 'f Distribution',
subtitle = paste0("P(X < ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc - fsd, y = max(df(l, num_df, den_df)) + 0.04, color = "#0000CD",
size = 3) +
annotate("text", label = paste0(round((1 - pp) * 100, 2), "%"),
x = perc + fsd, y = max(df(l, num_df, den_df)) + 0.02, color = "#6495ED",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = 'f Distribution',
subtitle = paste0("P(X > ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0(round((1 - pp) * 100, 2), "%"),
x = perc - fsd, y = max(df(l, num_df, den_df)) + 0.04, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc + fsd, y = max(df(l, num_df, den_df)) + 0.04, color = "#0000CD",
size = 3)
}
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_f(lc[l1[i]], lc[l2[i]], num_df, den_df)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y),
fill = col[i])
}
pln <- length(pp)
for (i in seq_len(pln)) {
point_data <- data.frame(x = perc[i], y = 0)
gplot <-
gplot +
geom_vline(xintercept = perc[i], linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
}
gplot <-
gplot +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = 0:max(l))
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
vdist_pol_f <- function(l1, l2, num_df, den_df) {
x <- c(l1, seq(l1, l2, 0.01), l2)
y <- c(0, df(seq(l1, l2, 0.01), num_df, den_df), 0)
data.frame(x = x, y = y)
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-f.R
|
#' Visualize normal distribution
#'
#' Visualize how changes in mean and standard deviation affect the
#' shape of the normal distribution. Compute & visualize quantiles out of given
#' probability and probability from a given quantile.
#'
#' @param mean Mean of the normal distribution.
#' @param perc Quantile value.
#' @param sd Standard deviation of the normal distribution.
#' @param probs Probability value.
#' @param type Lower tail, upper tail or both.
#' @param print_plot logical; if \code{TRUE}, prints the plot else returns a plot object.
#'
#' @examples
#' # visualize normal distribution
#' vdist_normal_plot()
#' vdist_normal_plot(mean = 2, sd = 0.6)
#'
#' # visualize quantiles out of given probability
#' vdist_normal_perc(0.95, mean = 2, sd = 1.36)
#' vdist_normal_perc(0.3, mean = 2, sd = 1.36, type = 'upper')
#' vdist_normal_perc(0.95, mean = 2, sd = 1.36, type = 'both')
#'
#' # visualize probability from a given quantile
#' vdist_normal_prob(3.78, mean = 2, sd = 1.36)
#' vdist_normal_prob(3.43, mean = 2, sd = 1.36, type = 'upper')
#' vdist_normal_prob(c(-1.74, 1.83), type = 'both')
#'
#' @seealso \code{\link[stats]{Normal}}
#'
#' @export
#'
vdist_normal_plot <- function(mean = 0, sd = 1, print_plot = TRUE) {
check_numeric(mean, "mean")
check_numeric(sd, "sd")
check_positive(sd)
x <- vdist_xax(mean)
l <- vdist_seql(mean, sd)
col <- c("#0000CD", "#4682B4", "#6495ED", "#4682B4", "#6495ED")
l1 <- c(3, 2, 1, 5, 6)
l2 <- c(5, 3, 2, 6, 7)
xm <- vdist_xmm(mean, sd)
plot_data <- data.frame(x = x, y = dnorm(x, mean, sd))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y)) +
xlab('') + ylab('') +
ggtitle(label = "Normal Distribution",
subtitle = paste("Mean:", mean, " Standard Deviation:", sd)) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
ll <- l[3:9]
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_cord(ll[l1[i]], ll[l2[i]], mean, sd)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y), fill = col[i])
}
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_normal_plot
#' @export
#'
vdist_normal_perc <- function(probs = 0.95, mean = 0, sd = 1,
type = c("lower", "upper", "both"),
print_plot = TRUE) {
check_numeric(mean, "mean")
check_numeric(sd, "sd")
check_positive(sd)
check_numeric(probs, "probs")
check_range(probs, 0, 1, "probs")
x <- vdist_xax(mean)
method <- match.arg(type)
l <- vdist_seql(mean, sd)
ln <- length(l)
if (method == "lower") {
pp <- round(qnorm(probs, mean, sd), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else if (method == "upper") {
pp <- round(qnorm(probs, mean, sd, lower.tail = F), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
alpha <- (1 - probs) / 2
pp1 <- round(qnorm(alpha, mean, sd), 3)
pp2 <- round(qnorm(alpha, mean, sd, lower.tail = F), 3)
pp <- c(pp1, pp2)
lc <- c(l[1], pp1, pp2, l[ln])
col <- c("#6495ED", "#0000CD", "#6495ED")
l1 <- c(1, 2, 3)
l2 <- c(2, 3, 4)
}
xm <- vdist_xmm(mean, sd)
plot_data <- data.frame(x = x, y = dnorm(x, mean, sd))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y)) +
xlab(paste("Mean:", mean, " Standard Deviation:", sd)) + ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(X < ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp - sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp + sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#6495ED",
size = 3)
} else if (method == "upper") {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(X > ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp - sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp + sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#0000CD",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(", pp[1], " < X < ", pp[2], ") = ", probs * 100, "%")) +
annotate("text", label = paste0(probs * 100, "%"),
x = mean, y = max(dnorm(x, mean, sd)) + 0.025, color = "#0000CD",
size = 3) +
annotate("text", label = paste0(alpha * 100, "%"),
x = pp[1] - sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(alpha * 100, "%"),
x = pp[2] + sd, y = max(dnorm(x, mean, sd)) + 0.025, color = "#6495ED",
size = 3)
}
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_cord(lc[l1[i]], lc[l2[i]], mean, sd)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y), fill = col[i])
}
pln <- length(pp)
for (i in seq_len(pln)) {
point_data <- data.frame(x = pp[i], y = 0)
gplot <-
gplot +
geom_vline(xintercept = pp[i], linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
}
gplot <-
gplot +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = l)
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_normal_plot
#' @export
#'
vdist_normal_prob <- function(perc = 3, mean = 0, sd = 1,
type = c("lower", "upper", "both"),
print_plot = TRUE) {
method <- match.arg(type)
if (length(perc) == 2) {
method <- "both"
}
check_numeric(mean, "mean")
check_numeric(sd, "sd")
check_numeric(perc, "perc")
check_positive(sd)
if (length(perc) > 2) {
stop("Please do not specify more than 2 percentile values.", call. = FALSE)
}
if ((method == "both") & (length(perc) != 2)) {
stop("Specify two percentile values.", call. = FALSE)
}
el <- max(abs(perc - mean)) / sd + 1
x <- vdist_xaxp(mean, el)
l <- vdist_seqlp(mean, sd, el)
ln <- length(l)
if (method == "lower") {
pp <- round(pnorm(perc, mean, sd), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else if (method == "upper") {
pp <- round(pnorm(perc, mean, sd, lower.tail = F), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
pp1 <- round(pnorm(perc[1], mean, sd), 3)
pp2 <- round(pnorm(perc[2], mean, sd, lower.tail = F), 3)
pp <- c(pp1, pp2)
lc <- c(l[1], perc[1], perc[2], l[ln])
col <- c("#6495ED", "#0000CD", "#6495ED")
l1 <- c(1, 2, 3)
l2 <- c(2, 3, 4)
}
xm <- vdist_xmmp(mean, sd, el)
plot_data <- data.frame(x = x, y = dnorm(x, mean, sd))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y)) +
xlab(paste("Mean:", mean, " Standard Deviation:", sd)) + ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(X < ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc - sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc + sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#6495ED",
size = 3)
} else if (method == "upper") {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(X > ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc - sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc + sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#0000CD",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = "Normal Distribution",
subtitle = paste0("P(", perc[1], " < X < ", perc[2], ") = ", (1 - (pp1 + pp2)) * 100, "%")) +
annotate("text", label = paste0((1 - (pp1 + pp2)) * 100, "%"),
x = mean(perc), y = max(dnorm(x, mean, sd)) + 0.07, color = "#0000CD",
size = 3) +
annotate("text", label = paste0(pp[1] * 100, "%"),
x = perc[1] - sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp[2] * 100, "%"),
x = perc[2] + sd, y = max(dnorm(x, mean, sd)) + 0.07, color = "#6495ED",
size = 3)
}
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_cord(lc[l1[i]], lc[l2[i]], mean, sd)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y), fill = col[i])
}
pln <- length(pp)
for (i in seq_len(pln)) {
point_data <- data.frame(x = perc[i], y = 0)
gplot <-
gplot +
geom_vline(xintercept = perc[i], linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
}
gplot <-
gplot +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = l)
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
vdist_xax <- function(mean) {
xl <- mean - 3
xu <- mean + 3
seq(xl, xu, 0.01)
}
vdist_seql <- function(mean, sd) {
lmin <- mean - (5 * sd)
lmax <- mean + (5 * sd)
seq(lmin, lmax, sd)
}
vdist_pol_cord <- function(l1, l2, mean, sd) {
x <- c(l1, seq(l1, l2, 0.01), l2)
y <- c(0, dnorm(seq(l1, l2, 0.01), mean, sd), 0)
data.frame(x = x, y = y)
}
vdist_xaxp <- function(mean, el) {
xl <- mean - el
xu <- mean + el
seq(xl, xu, 0.01)
}
vdist_seqlp <- function(mean, sd, el) {
if (el > 4) {
lmin <- mean - (el * sd)
lmax <- mean + (el * sd)
} else {
lmin <- mean - (4 * sd)
lmax <- mean + (4 * sd)
}
seq(lmin, lmax, sd)
}
vdist_xmmp <- function(mean, sd, el) {
if (el > 4) {
xmin <- mean - (el * sd)
xmax <- mean + (el * sd)
} else {
xmin <- mean - (4 * sd)
xmax <- mean + (4 * sd)
}
c(xmin, xmax)
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-normal.R
|
#' Visualize t distribution
#'
#' Visualize how degrees of freedom affect the shape of t
#' distribution, visualize quantiles out of given probability and
#' probability from a given quantile.
#'
#' @param df Degrees of freedom.
#' @param probs Probability value.
#' @param perc Quantile value.
#' @param type Lower tail, upper tail, interval or both.
#' @param print_plot logical; if \code{TRUE}, prints the plot else returns a plot object.
#'
#' @examples
#' # visualize t distribution
#' vdist_t_plot()
#' vdist_t_plot(6)
#' vdist_t_plot(df = 8)
#'
#' # visualize quantiles out of given probability
#' vdist_t_perc(probs = 0.95, df = 4, type = 'lower')
#' vdist_t_perc(probs = 0.35, df = 4, type = 'upper')
#' vdist_t_perc(probs = 0.69, df = 7, type = 'both')
#'
#' # visualize probability from a given quantile
#' vdist_t_prob(2.045, 7, 'lower')
#' vdist_t_prob(0.945, 7, 'upper')
#' vdist_t_prob(1.445, 7, 'interval')
#' vdist_t_prob(1.6, 7, 'both')
#'
#' @seealso \code{\link[stats]{TDist}}
#'
#' @name vdist_t
NULL
#' @export
#' @rdname vdist_t
#'
vdist_t_plot <- function(df = 3, print_plot = TRUE) {
check_numeric(df, "df")
df <- as.integer(df)
x <- seq(-4, 4, 0.01)
plot_data <- data.frame(x = x, y = dt(x, df))
poly_data <- data.frame(y = c(-4, seq(-4, 4, 0.01), 4),
z = c(0, dt(seq(-4, 4, 0.01), df), 0))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = 'blue') +
ggtitle(label = 't Distribution', subtitle = paste("df =", df)) +
xlab('') + ylab('') +
geom_polygon(data = poly_data, mapping = aes(x = y, y = z),
fill = '#4682B4') +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = -4:4) +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_t
#' @export
#'
vdist_t_perc <- function(probs = 0.95, df = 4,
type = c("lower", "upper", "both"),
print_plot = TRUE) {
check_numeric(probs, "probs")
check_numeric(df, "df")
check_range(probs, 0, 1, "probs")
df <- as.integer(df)
method <- match.arg(type)
l <- seq(-5, 5, 0.01)
ln <- length(l)
if (method == "lower") {
pp <- round(qt(probs, df), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else if (method == "upper") {
pp <- round(qt(probs, df, lower.tail = F), 3)
lc <- c(l[1], pp, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else {
alpha <- (1 - probs) / 2
pp1 <- round(qt(alpha, df), 3)
pp2 <- round(qt(alpha, df, lower.tail = F), 3)
pp <- c(pp1, pp2)
lc <- c(l[1], pp1, pp2, l[ln])
col <- c("#6495ED", "#0000CD", "#6495ED")
l1 <- c(1, 2, 3)
l2 <- c(2, 3, 4)
}
plot_data <- data.frame(x = l, y = dt(l, df))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = 'blue') +
xlab(paste("df =", df)) + ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))
if (method == "lower") {
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(X < ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp - 0.3, y = max(dt(l, df)) + 0.025, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp + 0.3, y = max(dt(l, df)) + 0.025, color = "#6495ED",
size = 3)
} else if (method == "upper") {
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(X > ", pp, ") = ", probs * 100, "%")) +
annotate("text", label = paste0((1 - probs) * 100, "%"),
x = pp - 0.3, y = max(dt(l, df)) + 0.025, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(probs * 100, "%"),
x = pp + 0.3, y = max(dt(l, df)) + 0.025, color = "#0000CD",
size = 3)
} else {
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(", pp[1], " < X < ", pp[2], ") = ", probs * 100, "%")) +
annotate("text", label = paste0(probs * 100, "%"),
x = mean(l), y = max(dt(l, df)) + 0.025, color = "#0000CD",
size = 3) +
annotate("text", label = paste0(alpha * 100, "%"),
x = pp[1] - 0.3, y = max(dt(l, df)) + 0.025, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(alpha * 100, "%"),
x = pp[2] + 0.3, y = max(dt(l, df)) + 0.025, color = "#6495ED",
size = 3)
}
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_t(lc[l1[i]], lc[l2[i]], df)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y), fill = col[i])
}
pln <- length(pp)
for (i in seq_len(pln)) {
point_data <- data.frame(x = pp[i], y = 0)
gplot <-
gplot +
geom_vline(xintercept = pp[i], linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
}
gplot <-
gplot +
scale_y_continuous(breaks = NULL) +
scale_x_continuous(breaks = -5:5)
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
#' @rdname vdist_t
#' @export
#'
vdist_t_prob <- function(perc = 1.6, df = 7,
type = c("lower", "upper", "interval", "both"),
print_plot = TRUE) {
check_numeric(perc, "perc")
check_numeric(df, "df")
df <- as.integer(df)
method <- match.arg(type)
l <- if (abs(perc) < 5) {
seq(-5, 5, 0.01)
} else {
seq(-(perc + 1), (perc + 1), 0.01)
}
ln <- length(l)
if (method == "lower") {
pp <- round(pt(perc, df), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#0000CD", "#6495ED")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else if (method == "upper") {
pp <- round(pt(perc, df, lower.tail = F), 3)
lc <- c(l[1], perc, l[ln])
col <- c("#6495ED", "#0000CD")
l1 <- c(1, 2)
l2 <- c(2, 3)
} else if (method == "interval") {
if (perc < 0) {
perc <- -perc
}
pp1 <- round(pt(-perc, df), 3)
pp2 <- round(pt(perc, df, lower.tail = F), 3)
pp <- c(pp1, pp2)
lc <- c(l[1], -perc, perc, l[ln])
col <- c("#6495ED", "#0000CD", "#6495ED")
l1 <- c(1, 2, 3)
l2 <- c(2, 3, 4)
} else {
if (perc < 0) {
perc <- -perc
}
pp1 <- round(pt(-perc, df), 3)
pp2 <- round(pt(perc, df, lower.tail = F), 3)
pp <- c(pp1, pp2)
lc <- c(l[1], -perc, perc, l[ln])
col <- c("#0000CD", "#6495ED", "#0000CD")
l1 <- c(1, 2, 3)
l2 <- c(2, 3, 4)
}
plot_data <- data.frame(x = l, y = dt(l, df))
gplot <-
ggplot(plot_data) +
geom_line(aes(x = x, y = y), color = 'blue') +
xlab(paste("df =", df)) + ylab('') +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)) +
scale_x_continuous(breaks = min(l):max(l)) +
scale_y_continuous(breaks = NULL)
for (i in seq_len(length(l1))) {
poly_data <- vdist_pol_t(lc[l1[i]], lc[l2[i]], df)
gplot <-
gplot +
geom_polygon(data = poly_data, mapping = aes(x = x, y = y), fill = col[i])
}
if (method == "lower") {
point_data <- data.frame(x = perc, y = 0)
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(X < ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc - 1, y = max(dt(l, df)) + 0.07, color = "#0000CD",
size = 3) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc + 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
geom_vline(xintercept = perc, linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
} else if (method == "upper") {
point_data <- data.frame(x = perc, y = 0)
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(X > ", perc, ") = ", pp * 100, "%")) +
annotate("text", label = paste0((1 - pp) * 100, "%"),
x = perc - 1, y = max(dt(l, df)) + 0.07, color = "#0000CD",
size = 3) +
annotate("text", label = paste0(pp * 100, "%"),
x = perc + 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
geom_vline(xintercept = perc, linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x, y = y),
shape = 4, color = 'red', size = 3)
} else if (method == "interval") {
point_data <- data.frame(x1 = perc, x2 = -perc, y = 0)
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(", -perc, " < X < ", perc, ") = ", (1 - (pp1 + pp2)) * 100, "%")) +
annotate("text", label = paste0((1 - (pp1 + pp2)) * 100, "%"),
x = 0, y = max(dt(l, df)) + 0.07, color = "#0000CD", size = 3) +
annotate("text", label = paste0(pp[1] * 100, "%"),
x = perc + 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp[2] * 100, "%"),
x = -perc - 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
geom_vline(xintercept = perc, linetype = 2, size = 1) +
geom_vline(xintercept = -perc, linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x1, y = y),
shape = 4, color = 'red', size = 3) +
geom_point(data = point_data, mapping = aes(x = x2, y = y),
shape = 4, color = 'red', size = 3)
} else {
point_data <- data.frame(x1 = perc, x2 = -perc, y = 0)
gplot <-
gplot +
ggtitle(label = "t Distribution",
subtitle = paste0("P(|X| > ", perc, ") = ", (pp1 + pp2) * 100, "%")) +
annotate("text", label = paste0((1 - (pp1 + pp2)) * 100, "%"),
x = 0, y = max(dt(l, df)) + 0.07, color = "#0000CD", size = 3) +
annotate("text", label = paste0(pp[1] * 100, "%"),
x = perc + 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
annotate("text", label = paste0(pp[2] * 100, "%"),
x = -perc - 1, y = max(dt(l, df)) + 0.07, color = "#6495ED",
size = 3) +
geom_vline(xintercept = perc, linetype = 2, size = 1) +
geom_vline(xintercept = -perc, linetype = 2, size = 1) +
geom_point(data = point_data, mapping = aes(x = x1, y = y),
shape = 4, color = 'red', size = 3) +
geom_point(data = point_data, mapping = aes(x = x2, y = y),
shape = 4, color = 'red', size = 3)
}
if (print_plot) {
print(gplot)
} else {
return(gplot)
}
}
vdist_pol_t <- function(l1, l2, df) {
x <- c(l1, seq(l1, l2, 0.01), l2)
y <- c(0, dt(seq(l1, l2, 0.01), df), 0)
data.frame(x = x, y = y)
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-t.R
|
#' @import utils
#' @import ggplot2
check_suggests <- function(pkg) {
pkg_flag <- tryCatch(packageVersion(pkg), error = function(e) NA)
if (is.na(pkg_flag)) {
msg <- message(paste0('\n', pkg, ' must be installed for this functionality.'))
if (interactive()) {
message(msg, "\nWould you like to install it?")
if (menu(c("Yes", "No")) == 1) {
install.packages(pkg)
} else {
stop(msg, call. = FALSE)
}
} else {
stop(msg, call. = FALSE)
}
}
}
check_numeric <- function(val, var = "n") {
if (!is.numeric(val)) {
stop(paste(var, "must be numeric."), call. = FALSE)
}
}
check_logical <- function(val, var = "normal") {
if (!is.logical(val)) {
stop(paste(var, "must be a logical value."), call. = FALSE)
}
}
check_positive <- function(val, var = "sd") {
if (val < 0) {
stop(paste(var, "must be a positive value."), call. = FALSE)
}
}
check_range <- function(val, min = 0, max = 1, var = "p") {
if ((val < min) | (val > max)) {
stop(paste(var, "must be between", min, "and", max, "only."), call. = FALSE)
}
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vdist-utils.R
|
#' \code{vistributions} package
#'
#' Visualize probability distributions.
#'
#' @docType package
#' @name vistributions
NULL
## quiets concerns of R CMD check re: the .'s that appear in pipelines
if (getRversion() >= "2.15.1") {
globalVariables(c(
".", "df", "chi", "x", "y", "z", "x1", "x2"
))
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/vistributions.R
|
#' @import magrittr
#' @import stats
.onAttach <- function(...) {
if (!interactive() || runif(1) > 0.1) return()
pkgs <- available.packages()
cran_version <-
pkgs %>%
extract("vistributions", "Version") %>%
package_version()
local_version <- packageVersion("vistributions")
behind_cran <- cran_version > local_version
tips <- c(
"Learn more about vistributions at https://github.com/rsquaredacademy/vistributions/.",
"Use suppressPackageStartupMessages() to eliminate package startup messages.",
"You might like our blog. Visit: https://blog.rsquaredacademy.com",
"Check out all our R packages. Visit: https://pkgs.rsquaredacademy.com/."
)
tip <- sample(tips, 1)
if (interactive()) {
if (behind_cran) {
msg <- "A new version of vistributions is available with bug fixes and new features."
packageStartupMessage(msg, "\nWould you like to install it?")
if (menu(c("Yes", "No")) == 1) {
update.packages("vistributions")
}
} else {
packageStartupMessage(paste(strwrap(tip), collapse = "\n"))
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/vistributions/R/zzz.R
|
## ---- echo=FALSE, message=FALSE-----------------------------------------------
library(vistributions)
## ----norm_plot, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_normal_plot(mean = 2, sd = 0.6)
## ----norm_per1, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_normal_perc(0.10, 60, 3, 'upper')
## ----norm_per2, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_normal_perc(0.85, 60, 3, 'lower')
## ----norm_per3, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_normal_perc(0.5, 60, 3, 'both')
## ----norm_prob1, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_normal_prob(80, mean = 90, sd = 4)
## ----norm_prob2, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_normal_prob(100, mean = 90, sd = 4, type = 'upper')
## ----norm_prob3, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_normal_prob(c(85, 100), mean = 90, sd = 4, type = 'both')
## ----binom_plot, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_binom_plot(10, 0.3)
## ----binom_per1, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_binom_perc(10, 0.5, 0.05)
## ----binom_per2, fig.width=7, fig.height=7, fig.align='centre'----------------
vdist_binom_perc(10, 0.5, 0.05, 'upper')
## ----binom_prob1, fig.width=7, fig.height=7, fig.align='centre'---------------
vdist_binom_prob(12, 0.2, 4, type = 'exact')
## ----binom_prob2, fig.width=7, fig.height=7, fig.align='centre'---------------
vdist_binom_prob(12, 0.2, 1, 'lower')
## ----binom_prob3, fig.width=7, fig.height=7, fig.align='centre'---------------
vdist_binom_prob(12, 0.2, 8, 'upper')
## ----binom_prob4, fig.width=7, fig.height=7, fig.align='centre'---------------
vdist_binom_prob(12, 0.2, c(0, 4), 'interval')
## ----chi_plot, fig.width=7, fig.height=7, fig.align='centre'------------------
vdist_chisquare_plot(df = 5)
vdist_chisquare_plot(df = 5, normal = TRUE)
## ----chi_per1, fig.width=7, fig.height=7, fig.align='centre'------------------
vdist_chisquare_perc(0.05, 8, 'upper')
## ----chi_per2, fig.width=7, fig.height=7, fig.align='centre'------------------
vdist_chisquare_perc(0.10, 8, 'lower')
## ----chi_prob1, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_chisquare_prob(8.79, 12, 'upper')
## ----chi_prob2, fig.width=7, fig.height=7, fig.align='centre'-----------------
vdist_chisquare_prob(8.62, 12, 'lower')
## ----f_plot, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_f_plot()
vdist_f_plot(6, 10, normal = TRUE)
## ----f_per1, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_f_perc(0.20, 4, 5, 'upper')
## ----f_per2, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_f_perc(0.35, 4, 5, 'lower')
## ----f_prob1, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_f_prob(3.89, 4, 5, 'upper')
## ----f_prob2, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_f_prob(2.63, 4, 5, 'lower')
## ----t_plot, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_t_plot(df = 8)
## ----t_per1, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_t_perc(0.15, 8, 'upper')
## ----t_per2, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_t_perc(0.11, 8, 'lower')
## ----t_per3, fig.width=7, fig.height=7, fig.align='centre'--------------------
vdist_t_perc(0.8, 8, 'both')
## ----t_prob1, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_t_prob(2, 6, 'lower')
## ----t_prob2, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_t_prob(2, 6, 'upper')
## ----t_prob3, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_t_prob(2, 6, 'both')
## ----t_prob4, fig.width=7, fig.height=7, fig.align='centre'-------------------
vdist_t_prob(2, 6, 'interval')
|
/scratch/gouwar.j/cran-all/cranData/vistributions/inst/doc/introduction-to-vistributions.R
|
---
title: "Exploring Distributions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Exploring Distributions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, echo=FALSE, message=FALSE}
library(vistributions)
```
In exploring statistical distributions, we focus on the following:
- what influences the shape of a distribution
- calculate probability from a given quantile
- calculate quantiles out of given probability
To explore the above 3 concepts, we have defined functions for the following
distributions:
- Normal
- Binomial
- Chi Square
- F
- t
## Normal Distribution
### Distribution Shape
Visualize how changes in mean and standard deviation affect the shape of the
normal distribution.
##### Input
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
##### Output
- Normal distribution plot
```{r norm_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_plot(mean = 2, sd = 0.6)
```
### Percentiles
#### Calculate and visualize quantiles out of given probability.
##### Input
- probs: a probability value
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
- type: lower/upper tail
Suppose X, the grade on a exam, is normally distributed with mean 60
and standard deviation 3. The teacher wants to give 10% of the class an A.
What should be the cutoff to determine who gets an A?
```{r norm_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.10, 60, 3, 'upper')
```
The teacher wants to give lower 15% of the class a D. What cutoff should the
teacher use to determine who gets an D?
```{r norm_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.85, 60, 3, 'lower')
```
The teacher wants to give middle 50% of the class a B. What cutoff should the
teacher use to determine who gets an B?
```{r norm_per3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.5, 60, 3, 'both')
```
### Probabilities
#### Calculate and visualize probability from a given quantile
##### Input
- perc: a quantile value
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
- type: lower/upper/both tail
Let X be the IQ of a randomly selected student of a school. Assume X ~ N(90, 4).
What is the probability that a randomly selected student has an IQ below 80?
```{r norm_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(80, mean = 90, sd = 4)
```
What is the probability that a randomly selected student has an IQ above 100?
```{r norm_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(100, mean = 90, sd = 4, type = 'upper')
```
What is the probability that a randomly selected student has an IQ
between 85 and 100?
```{r norm_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(c(85, 100), mean = 90, sd = 4, type = 'both')
```
## Binomial Distribution
### Distribution Shape
Visualize how changes in number of trials and the probability of success affect
the shape of the binomial distribution.
```{r binom_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_plot(10, 0.3)
```
### Percentiles
#### Calculate and visualize quantiles out of given probability
##### Input
- p: a single aggregated probability of multiple trials
- n: the number of trials
- tp: the probability of success in a trial
- type: lower/upper tail
```{r binom_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_perc(10, 0.5, 0.05)
```
```{r binom_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_perc(10, 0.5, 0.05, 'upper')
```
### Probabilities
#### Calculate and visualize probability from a given quantile
##### Input
- p: probability of success
- n: the number of trials
- s: number of success in a trial
- type: lower/upper/interval/exact tail
Assume twenty-percent (20%) of Magemill have no health insurance. Randomly
sample n = 12 Magemillians. Let X denote the number in the sample with no
health insurance. What is the probability that exactly 4 of the 15 sampled
have no health insurance?
```{r binom_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 4, type = 'exact')
```
What is the probability that at most one of those sampled has no health
insurance?
```{r binom_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 1, 'lower')
```
What is the probability that more than seven have no health insurance?
```{r binom_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 8, 'upper')
```
What is the probability that fewer than 5 have no health insurance?
```{r binom_prob4, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, c(0, 4), 'interval')
```
## Chi Square Distribution
### Distribution Shape
Visualize how changes in degrees of freedom affect the shape of the chi square
distribution.
```{r chi_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_plot(df = 5)
vdist_chisquare_plot(df = 5, normal = TRUE)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- df: degrees of freedom
- type: lower/upper tail
Let X be a chi-square random variable with 8 degrees of freedom. What is the
upper fifth percentile?
```{r chi_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_perc(0.05, 8, 'upper')
```
What is the tenth percentile?
```{r chi_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_perc(0.10, 8, 'lower')
```
### Probability
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- df: degrees of freedom
- type: lower/upper tail
What is the probability that a chi-square random variable with 12 degrees of
freedom is greater than 8.79?
```{r chi_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_prob(8.79, 12, 'upper')
```
What is the probability that a chi-square random variable with 12 degrees of
freedom is greater than 8.62?
```{r chi_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_prob(8.62, 12, 'lower')
```
## F Distribution
### Distribution Shape
Visualize how changes in degrees of freedom affect the shape of the F
distribution.
```{r f_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_plot()
vdist_f_plot(6, 10, normal = TRUE)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- num_df: nmerator degrees of freedom
- den_df: denominator degrees of freedom
- type: lower/upper tail
Let X be an F random variable with 4 numerator degrees of freedom and 5
denominator degrees of freedom. What is the upper twenth percentile?
```{r f_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_perc(0.20, 4, 5, 'upper')
```
What is the 35th percentile?
```{r f_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_perc(0.35, 4, 5, 'lower')
```
### Probabilities
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- num_df: nmerator degrees of freedom
- den_df: denominator degrees of freedom
- type: lower/upper tail
What is the probability that an F random variable with 4 numerator degrees of
freedom and 5 denominator degrees of freedom is greater than 3.89?
```{r f_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_prob(3.89, 4, 5, 'upper')
```
What is the probability that an F random variable with 4 numerator degrees of
freedom and 5 denominator degrees of freedom is less than 2.63?
```{r f_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_prob(2.63, 4, 5, 'lower')
```
## t Distribution
### Distribution Shape
Visualize how degrees of freedom affect the shape of t distribution.
```{r t_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_plot(df = 8)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- df: degrees of freedom
- type: lower/upper/both tail
What is the upper fifteenth percentile?
```{r t_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.15, 8, 'upper')
```
What is the eleventh percentile?
```{r t_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.11, 8, 'lower')
```
What is the area of the curve that has 95% of the t values?
```{r t_per3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.8, 8, 'both')
```
### Probabilities
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- df: degrees of freedom
- type: lower/upper/interval/both tail
Let T follow a t-distribution with r = 6 df.
What is the probability that the value of T is less than 2?
```{r t_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'lower')
```
What is the probability that the value of T is greater than 2?
```{r t_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'upper')
```
What is the probability that the value of T is between -2 and 2?
```{r t_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'both')
```
What is the probability that the absolute value of T is greater than 2?
```{r t_prob4, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'interval')
```
|
/scratch/gouwar.j/cran-all/cranData/vistributions/inst/doc/introduction-to-vistributions.Rmd
|
---
title: "Exploring Distributions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Exploring Distributions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, echo=FALSE, message=FALSE}
library(vistributions)
```
In exploring statistical distributions, we focus on the following:
- what influences the shape of a distribution
- calculate probability from a given quantile
- calculate quantiles out of given probability
To explore the above 3 concepts, we have defined functions for the following
distributions:
- Normal
- Binomial
- Chi Square
- F
- t
## Normal Distribution
### Distribution Shape
Visualize how changes in mean and standard deviation affect the shape of the
normal distribution.
##### Input
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
##### Output
- Normal distribution plot
```{r norm_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_plot(mean = 2, sd = 0.6)
```
### Percentiles
#### Calculate and visualize quantiles out of given probability.
##### Input
- probs: a probability value
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
- type: lower/upper tail
Suppose X, the grade on a exam, is normally distributed with mean 60
and standard deviation 3. The teacher wants to give 10% of the class an A.
What should be the cutoff to determine who gets an A?
```{r norm_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.10, 60, 3, 'upper')
```
The teacher wants to give lower 15% of the class a D. What cutoff should the
teacher use to determine who gets an D?
```{r norm_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.85, 60, 3, 'lower')
```
The teacher wants to give middle 50% of the class a B. What cutoff should the
teacher use to determine who gets an B?
```{r norm_per3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_perc(0.5, 60, 3, 'both')
```
### Probabilities
#### Calculate and visualize probability from a given quantile
##### Input
- perc: a quantile value
- mean: mean of the normal distribution
- sd: standard deviation of the normal distribution
- type: lower/upper/both tail
Let X be the IQ of a randomly selected student of a school. Assume X ~ N(90, 4).
What is the probability that a randomly selected student has an IQ below 80?
```{r norm_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(80, mean = 90, sd = 4)
```
What is the probability that a randomly selected student has an IQ above 100?
```{r norm_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(100, mean = 90, sd = 4, type = 'upper')
```
What is the probability that a randomly selected student has an IQ
between 85 and 100?
```{r norm_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_normal_prob(c(85, 100), mean = 90, sd = 4, type = 'both')
```
## Binomial Distribution
### Distribution Shape
Visualize how changes in number of trials and the probability of success affect
the shape of the binomial distribution.
```{r binom_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_plot(10, 0.3)
```
### Percentiles
#### Calculate and visualize quantiles out of given probability
##### Input
- p: a single aggregated probability of multiple trials
- n: the number of trials
- tp: the probability of success in a trial
- type: lower/upper tail
```{r binom_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_perc(10, 0.5, 0.05)
```
```{r binom_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_perc(10, 0.5, 0.05, 'upper')
```
### Probabilities
#### Calculate and visualize probability from a given quantile
##### Input
- p: probability of success
- n: the number of trials
- s: number of success in a trial
- type: lower/upper/interval/exact tail
Assume twenty-percent (20%) of Magemill have no health insurance. Randomly
sample n = 12 Magemillians. Let X denote the number in the sample with no
health insurance. What is the probability that exactly 4 of the 15 sampled
have no health insurance?
```{r binom_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 4, type = 'exact')
```
What is the probability that at most one of those sampled has no health
insurance?
```{r binom_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 1, 'lower')
```
What is the probability that more than seven have no health insurance?
```{r binom_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, 8, 'upper')
```
What is the probability that fewer than 5 have no health insurance?
```{r binom_prob4, fig.width=7, fig.height=7, fig.align='centre'}
vdist_binom_prob(12, 0.2, c(0, 4), 'interval')
```
## Chi Square Distribution
### Distribution Shape
Visualize how changes in degrees of freedom affect the shape of the chi square
distribution.
```{r chi_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_plot(df = 5)
vdist_chisquare_plot(df = 5, normal = TRUE)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- df: degrees of freedom
- type: lower/upper tail
Let X be a chi-square random variable with 8 degrees of freedom. What is the
upper fifth percentile?
```{r chi_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_perc(0.05, 8, 'upper')
```
What is the tenth percentile?
```{r chi_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_perc(0.10, 8, 'lower')
```
### Probability
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- df: degrees of freedom
- type: lower/upper tail
What is the probability that a chi-square random variable with 12 degrees of
freedom is greater than 8.79?
```{r chi_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_prob(8.79, 12, 'upper')
```
What is the probability that a chi-square random variable with 12 degrees of
freedom is greater than 8.62?
```{r chi_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_chisquare_prob(8.62, 12, 'lower')
```
## F Distribution
### Distribution Shape
Visualize how changes in degrees of freedom affect the shape of the F
distribution.
```{r f_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_plot()
vdist_f_plot(6, 10, normal = TRUE)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- num_df: nmerator degrees of freedom
- den_df: denominator degrees of freedom
- type: lower/upper tail
Let X be an F random variable with 4 numerator degrees of freedom and 5
denominator degrees of freedom. What is the upper twenth percentile?
```{r f_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_perc(0.20, 4, 5, 'upper')
```
What is the 35th percentile?
```{r f_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_perc(0.35, 4, 5, 'lower')
```
### Probabilities
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- num_df: nmerator degrees of freedom
- den_df: denominator degrees of freedom
- type: lower/upper tail
What is the probability that an F random variable with 4 numerator degrees of
freedom and 5 denominator degrees of freedom is greater than 3.89?
```{r f_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_prob(3.89, 4, 5, 'upper')
```
What is the probability that an F random variable with 4 numerator degrees of
freedom and 5 denominator degrees of freedom is less than 2.63?
```{r f_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_f_prob(2.63, 4, 5, 'lower')
```
## t Distribution
### Distribution Shape
Visualize how degrees of freedom affect the shape of t distribution.
```{r t_plot, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_plot(df = 8)
```
### Percentiles
#### Calculate quantiles out of given probability
##### Input
- probs: a probability value
- df: degrees of freedom
- type: lower/upper/both tail
What is the upper fifteenth percentile?
```{r t_per1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.15, 8, 'upper')
```
What is the eleventh percentile?
```{r t_per2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.11, 8, 'lower')
```
What is the area of the curve that has 95% of the t values?
```{r t_per3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_perc(0.8, 8, 'both')
```
### Probabilities
#### Calculate probability from a given quantile.
##### Input
- perc: a quantile value
- df: degrees of freedom
- type: lower/upper/interval/both tail
Let T follow a t-distribution with r = 6 df.
What is the probability that the value of T is less than 2?
```{r t_prob1, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'lower')
```
What is the probability that the value of T is greater than 2?
```{r t_prob2, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'upper')
```
What is the probability that the value of T is between -2 and 2?
```{r t_prob3, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'both')
```
What is the probability that the absolute value of T is greater than 2?
```{r t_prob4, fig.width=7, fig.height=7, fig.align='centre'}
vdist_t_prob(2, 6, 'interval')
```
|
/scratch/gouwar.j/cran-all/cranData/vistributions/vignettes/introduction-to-vistributions.Rmd
|
#' @rdname drasdolut
#' @title Precomputed X and Y displacement of ganglion cell bodies for any given X and Y location on the retina
#' @description It contains a first list with two LUTs for the X and Y displacement of ganglion cell bodies
#' for arbitrary locations in the retina (in mm assuming 24 mm axial length). The other two elements of the list
#' contain precomputed vectors of degrees and mm on the retina for the same schematic eye, used for conversions.
#' These are used by the function vf2gc().
#' @format A large list containing
#' \describe{
#' \item{Drasdo_LUT}{a list of four elements: xlut and ylut are 2d matrices
#' containing X and Y ganglion cell positions for any given location.
#' Xv and Yv are vectors defining the corresponding locations for the matrices along the X and Y axis.}
#' \item{Degs}{A vector of degrees from the fovea, using a schematic eye. Corresponds to distances on the retina stored in MM}
#' \item{MM}{A vector of MM distance from the fovea, using a schematic eye. Corresponds to distances in degrees stored in Degs}
#' }
#' @references
#' G. Montesano, G. Ometto, R. E. Hogg, L. M. Rossetti, D. F. Garway-Heath,
#' and D. P. Crabb. \emph{Revisiting the Drasdo Model: Implications for
#' Structure-Function Analysis of the Macular Region}.
#' Translational Vision Science and Technology,
#' 9(10):15, 2020
#'
#' N. Drasdo, C. L. Millican, C. R. Katholi, and C. A. Curcio. \emph{The
#' length of Henle fibers in the human retina and a model of ganglion
#' receptive field density in the visual field}. Vision Research,
#' 47:2901–2911, 2007
#' @keywords ganglion cell displacement Drasdo
"drasdolut"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-drasdolut.R
|
#' @rdname gpars
#' @title List of graphical parameters
#' @description It contains a list of normative values, including pointwise and
#' smoothed SUNY-IU normative reference values for 24-2 static automated perimetry
#' (\code{sunyiu_24d2_pw} and \code{sunyiu_24d2}) obtained with the dataset
#' \code{\link{vfctrSunyiu24d2}}
#' @format See section \code{Structure of graphical parameters} in \code{\link{vfplot}}
#' @keywords dataset
"gpars"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-gpars.R
|
#' @rdname locmaps
#' @title Location maps
#' @description List of common and some custom location maps, including the
#' 24-2, 10-2, 30-2, 60-4, etc used the the HFA and Octopus, the 24-2 used
#' by the Matrix (FDT), and others used in Swanson's and Wall's labs
#' @format See section \code{Structure of location maps} in \code{\link{setlocmap}}
#' @keywords dataset
"locmaps"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-locmaps.R
|
#' @rdname normals
#' @title List of normative values that can be used for statistical analysis and
#' visualization
#' @description It contains a list of normative values, including pointwise and
#' smoothed SUNY-IU normative reference values for 24-2 static automated perimetry
#' (\code{sunyiu_24d2_pw} and \code{sunyiu_24d2}) obtained with the dataset
#' \code{\link{vfctrSunyiu24d2}}
#' @format See section \code{Structure of normative values} in \code{\link{setnv}}
#' @references
#' H. J. Wyatt, M. W. Dul, and W. H. Swanson. \emph{Variability of visual
#' field measurements is correlated with the gradient of visual
#' sensitivity}. Vision Research, 47, 2007.
#'
#' A. Shafi, W. H. Swanson, and M. W. Dul. \emph{Structure and Function
#' in Patients with Glaucomatous Defects Near Fixation}. Optometry and
#' Vision Science, 88, 2011.
#' @keywords dataset
"normvals"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-normvals.R
|
#' @rdname vfctrIowaPC26
#' @title Central visual field
#' @description Locations of the visual field tested have eccentricities up to 26
#' degrees and were obtained with a custom static automated perimetry.
#' Data are from 98 eyes of 98 ocular healthy subjects. Each subject underwent two
#' visual field tests, one of the central visual field (64 locations within 26 degrees
#' of fixation) and one of the peripheral visual field (64 locations with eccentricity
#' from 26 to up to 81 degrees)
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @details Data are for locations within the central 26 degrees. The data for locations
#' with eccentricity from 26 to up to 81 degrees are in \code{\link{vfctrIowaPeri}}.
#' This dataset of healthy eyes was used to generate the normative values
#' \code{iowa_PC26_pw}, and \code{iowa_PC26_pw_cps} included in \code{\link{normvals}}.
#' @seealso \code{\link{vfpwgSunyiu24d2}}, \code{\link{vfctrIowaPeri}},
#' \code{\link{vfctrSunyiu10d2}}, \code{\link{vfctrSunyiu24d2}},
#' \code{\link{vfpwgRetest24d2}}
#' @references
#' I. Marin-Franch, P. H. Artes, L. X. Chong, A. Turpin, and M. Wall.
#' \emph{Data obtained with an open-source static automated perimetry test
#' of the full visual field in healthy adults}. Data in Brief, 21:75–82, 2018.
#' @keywords dataset
"vfctrIowaPC26"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfctrIowaPC26.R
|
#' @rdname vfctrIowaPeri
#' @title Peripheral visual field
#' @description Locations of the visual field tested have eccentricities from 26
#' to up to 81 degrees and were obtained with a custom static automated perimetry.
#' Data are from 98 eyes of 98 ocular healthy subjects. Each subject underwent two
#' visual field tests, one of the central visual field (64 locations within 26 degrees
#' of fixation) and one of the peripheral visual field (64 locations with eccentricity
#' from 26 to up to 81 degrees)
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @details Data are for locations with eccentricity from 26 to up to 81 degrees.
#' The dataset for locations within the central 26 degrees are in \code{\link{vfctrIowaPC26}}.
#' This dataset of healthy eyes was used to generate the normative values
#' \code{iowa_Peri_pw}, and \code{iowa_Peri_pw_cps} included in \code{\link{normvals}}.
#' @seealso \code{\link{vfpwgSunyiu24d2}}, \code{\link{vfctrIowaPC26}},
#' \code{\link{vfctrSunyiu10d2}}, \code{\link{vfctrSunyiu24d2}},
#' \code{\link{vfpwgRetest24d2}}
#' @references
#' I. Marin-Franch, P. H. Artes, L. X. Chong, A. Turpin, and M. Wall.
#' \emph{Data obtained with an open-source static automated perimetry test
#' of the full visual field in healthy adults}. Data in Brief, 21:75–82, 2018.
#' @keywords dataset
"vfctrIowaPeri"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfctrIowaPeri.R
|
#' @rdname vfctrSunyiu10d2
#' @title SUNY-IU dataset of healthy eyes for 10-2 static automated perimetry
#' @description SUNY-IU dataset of healthy eyes for 10-2 static automated perimetry.
#' Courtesy of William H Swanson.
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @seealso \code{\link{vfpwgSunyiu24d2}}, \code{\link{vfctrIowaPC26}},
#' \code{\link{vfctrIowaPeri}}, \code{\link{vfctrSunyiu24d2}},
#' \code{\link{vfpwgRetest24d2}}
#' @references
#' H. J. Wyatt, M. W. Dul, and W. H. Swanson. \emph{Variability of visual
#' field measurements is correlated with the gradient of visual
#' sensitivity}. Vision Research, 47, 2007.
#'
#' A. Shafi, W. H. Swanson, and M. W. Dul. \emph{Structure and Function
#' in Patients with Glaucomatous Defects Near Fixation}. Optometry and
#' Vision Science, 88, 2011.
#' @keywords dataset
"vfctrSunyiu10d2"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfctrSunyiu10d2.R
|
#' @rdname vfctrSunyiu24d2
#' @title SUNY-IU dataset of healthy eyes for 24-2 static automated perimetry
#' @description This dataset of healthy eyes was used to generate the normative values
#' \code{sunyiu_24d2}, \code{sunyiu_24d2_pw}, \code{sunyiu_24d2}, and
#' \code{sunyiu_24d2_pw_cps} included in \code{\link{normvals}}.
#' Courtesy of William H Swanson and Mitch W Dul
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @seealso \code{\link{vfpwgSunyiu24d2}}, \code{\link{vfctrIowaPC26}},
#' \code{\link{vfctrIowaPeri}}, \code{\link{vfctrSunyiu10d2}},
#' \code{\link{vfpwgRetest24d2}}
#' @references
#' H. J. Wyatt, M. W. Dul, and W. H. Swanson. \emph{Variability of visual
#' field measurements is correlated with the gradient of visual
#' sensitivity}. Vision Research, 47, 2007.
#'
#' A. Shafi, W. H. Swanson, and M. W. Dul. \emph{Structure and Function
#' in Patients with Glaucomatous Defects Near Fixation}. Optometry and
#' Vision Science, 88, 2011.
#' @keywords dataset
"vfctrSunyiu24d2"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfctrSunyiu24d2.R
|
#' @rdname vfpwgRetest24d2
#' @title Short-term retest static automated perimetry data
#' @description Thirty patients recruited from the glaucoma clinics at the
#' Queen Elizabeth Health Sciences Centre in Halifax, Nova Scotia. Each
#' patient underwent 12 visual fields in 12 consecutive weekly sessions.
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @seealso \code{\link{vfpwgSunyiu24d2}}, \code{\link{vfctrIowaPC26}},
#' \code{\link{vfctrIowaPeri}}, \code{\link{vfctrSunyiu10d2}},
#' \code{\link{vfctrSunyiu24d2}}
#' @references
#' P. H. Artes, N. O'Leary, M. T. Nicolela, B. C. Chauhan, and D. P. Crabb.
#' \emph{Visual field progression in glaucoma: What is the specificity of the
#' guided progression analysis?} American Academy of Ophthalmology,
#' 121(10):2023-2027, 2014.
#' @keywords dataset
"vfpwgRetest24d2"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfpwgRetest24d2.R
|
#' @rdname vfpwgSunyiu24d2
#' @title Series of 24-2 static automated perimetry data for a patient with glaucoma
#' @description This is real data for the right and left eyes, but the age has been changed
#' to protect anonymity of the subject. Courtesy of William H Swanson and Mitch W Dul
#' @format See section \code{Structure of visual fields data} in \code{\link{vfdesc}}
#' @seealso \code{\link{vfctrIowaPC26}}, \code{\link{vfctrIowaPeri}},
#' \code{\link{vfctrSunyiu10d2}}, \code{\link{vfctrSunyiu24d2}},
#' \code{\link{vfpwgRetest24d2}}
#' @keywords dataset
"vfpwgSunyiu24d2"
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/data-vfpwgSunyiu24d2.R
|
#' @rdname jansonius
#' @title The Jansonius map for average path of nerve fiber bundles
#' @description Generates a function that renders the average path of
#' a nerve fiber bundle that exits through the optic nerve head (ONH)
#' with a particular angle
#' @details
#' \itemize{
#' \item\code{cart2jpolar} converts the cartesian coordinates to the polar
#' coordinates in the distorted space used in the Jansonius map
#' \item\code{jpolar2cart} converts back from the Jansonius polar
#' coordinates to cartesian coordinates
#' \item\code{bundlePath} returns a function describing the expected fiber
#' path given an angle of incidence on the ONH
#' \item\code{loc2psi} returns the angle of incidence of the average bundle path
#' that passes through specific locations of the visual field
#' \item\code{psi2oct} returns the angle of OCT circular scans corresponding
#' to average bundle paths with specific angle of incidence at the ONH
#' \item\code{vf2gc} calculates ganglion-cell soma locations
#' }
#' @references
#' N. M. Jansonius, J. Nevalainen, B. Selig, L. M. Zangwill,
#' P. A. Sample, W. M. Budde, J. B. Jonas, W. A. Lagreze,
#' P. J. Airaksinen, R. Vonthein, L. A. Levin, J. Paetzold,
#' and U. Schiefer. \emph{A mathematical description of nerve
#' fiber bundle trajectories and their variability in the human
#' retina}. Vision Research, 49(17):2157-2163, 2009
#'
#' N. M. Jansonius, J. Nevalainen, B. Selig, L. M. Zangwill,
#' P. A. Sample, W. M. Budde, J. B. Jonas, W. A. Lagreze,
#' P. J. Airaksinen, R. Vonthein, L. A. Levin, J. Paetzold,
#' and U. Schiefer. \emph{Erratum to "A mathematical description
#' of nerve fiber bundle trajectories and their variability in
#' the human retina"}. Vision Research, 50:1501, 2010
#'
#' N. M. Jansonius, J. Schiefer, J. Nevalainen, J. Paetzold,
#' and U. Schiefer. \emph{A mathematical model for describing
#' the retinal nerve fiber bundle trajectories in the human eye:
#' Average course, variability, and influence of refraction, optic
#' disc size and optic disc position}. Experimental Eye Research,
#' 105:70-78, 2012
#'
#' N. Drasdo, C. L. Millican, C. R. Katholi, and C. A. Curcio. \emph{The
#' length of Henle fibers in the human retina and a model of ganglion
#' receptive field density in the visual field}. Vision Research,
#' 47:2901–2911, 2007
#'
#' D. C. Hood, A. S. Raza, D. M. C. G. V., J. G. Odel, V. C. Greenstein,
#' J. M. Liebmann, and R. Ritch. \emph{Initial arcuate defects within the
#' central 10 degrees in glaucoma}. Investigative Ophthalmology and Visual
#' Science, 52(2):940-946, 2011
#'
#' A. S. Raza, J. Cho, D. M. C. G. V., H. Wang, X. Zhang, R. H. Kardon,
#' J. M. Liebmann, R. Ritch, and D. C. Hood. \emph{Retinal ganglion cell
#' layer thickness and local visual field sensitivity in glaucoma}.
#' Archives of Ophthalmology, 129(12):1529-1536, 2011
#'
#' G. Montesano, G. Ometto, R. E. Hogg, L. M. Rossetti, D. F. Garway-Heath,
#' and D. P. Crabb. \emph{Revisiting the Drasdo Model: Implications for
#' Structure-Function Analysis of the Macular Region}.
#' Translational Vision Science and Technology,
#' 9(10):15, 2020
#' @examples
#' # get ganglion-cell soma locations from visual field locations
#' vf2gc(locmaps$p10d2$coord)
#' # convert to polar of the distorted space used by Jansonius map and back
#' coord <- data.frame(x = c(3, 0, -3), y = c(0, 0, 0))
#' (rpsi <- cart2jpolar(coord))
#' jpolar2cart(rpsi)
#'
#' # get an average bundle path from a specific angle of incidence in the ONH
#' # The object returned is a function that returns polar angles of the
#' # distorted space of the Jansonius map for distances from the ONH center
#' pathFun <- bundlePath(-125)
#' jpolar2cart(data.frame(10:20, pathFun(10:20)))
#'
#' # get angle of incidence in the ONH from locations of the visual field
#' loc2psi(coord)
#'
#' # get the OCT circular scan angles from the angle of incidence in the ONH
#' # for the 10-2 map of locations, ...
#' psi2oct(loc2psi(locmaps$p10d2$coord))
#' # the previous operation was actually fundamentally wrong! We need to
#' # obtain first the
#' psi2oct(loc2psi(vf2gc(locmaps$p10d2$coord)))
#' @param coord coordinates of locations in the visual field
#' @return \code{cart2jpolar}: returns the Jansonius modified polar coordinates
#' @export
cart2jpolar <- function(coord) {
x <- coord[,1]
y <- coord[,2]
xp <- x - 15
yp <- y
yp[x > 0] <- y[x > 0] - 2 * (x[x > 0] / 15)^2
r <- sqrt(xp^2 + yp^2)
psi <- atan2(yp, xp)
return(data.frame(r = r, psi = 180 / pi * psi))
}
#' @rdname jansonius
#' @param rpsi visual field locations in polar coordinates of the
#' distorted space of the Jansonius map
#' @return \code{jpolar2cart}: returns Cartesian coordinates
#' @export
jpolar2cart <- function(rpsi) {
r <- rpsi[,1]
psi <- rpsi[,2]
psi <- (pi / 180 * psi) %% (2 * pi)
x <- sqrt(r^2 / (1 + (tan(psi))^2))
y <- abs(x * tan(psi))
x[psi > (pi / 2) & psi < (3 * pi / 2)] <- -x[psi > (pi / 2) & psi < (3 * pi / 2)]
y[psi > pi] <- -y[psi > pi]
x <- x + 15
y[x > 0] <- y[x > 0] + 2 * (x[x > 0] / 15)^2
return(data.frame(x = round(x, 6), y = round(y, 6)))
}
#' @rdname jansonius
#' @param psi0 angle of incidence at the ONH
#' @param r0 radius of the ONH. Its default value is \code{4}.
#' Changing it changes the calculated average bundle paths.
#' @return \code{bundlePath}: returns a function describing a retinal ganglion cell bundle path
#' @export
bundlePath <- function(psi0, r0 = 4) {
if(!(is.atomic(psi0) && length(psi0) == 1L) ||
!is.numeric(psi0) || abs(psi0) > 180)
stop("input argument psi0 must be a numeric scalar from -180 to 180")
if(psi0 == -180) psi0 <- 180
if(psi0 >= 0 & psi0 < 60) {
b <- 0.00083 * psi0^2 + 0.020 * psi0 - 2.65
c <- 1.9 + 1.4 * tanh((psi0 - 121) / 14)
}
if(psi0 >= 60 & psi0 <= 180) {
b <- exp(-1.9 + 3.9 * tanh(-(psi0 - 121) / 14))
c <- 1.9 + 1.4 * tanh((psi0 - 121) / 14)
}
if(psi0 > -180 & psi0 <= -60) {
b <- -exp(0.7 + 1.5 * tanh(-(-psi0 - 90) / 25))
c <- 1.0 + 0.5 * tanh((-psi0 - 90) / 25)
}
if(psi0 > -60 & psi0 < 0) {
b <- 0.00083 * psi0^2 + 0.020 * psi0 - 2.65
c <- 1.0 + 0.5 * tanh((-psi0 - 90) / 25)
}
fbfun <- function(r) {
return(psi0 + b * (r - r0)^c)
}
return(fbfun)
}
#' @rdname jansonius
#' @param diam diamater in degrees of visual angle of the OCT circular
#' scan centered at the center of the ONH
#' @return \code{loc2psi}: returns the angle of incidence on the ONH
#' @export
loc2psi <- function(coord, r0 = 4) {
coord[,2] <- -coord[,2]
psi0 <- sapply(split(cart2jpolar(coord), seq(nrow(coord))), function(rpsi) {
fbpathinv <- function(psi0) {
fb <- bundlePath(psi0, r0)
psiest <- fb(rpsi$r)
return((psiest - rpsi$psi)^2)}
optimize(fbpathinv, interval = c(-179.99, 180))$minimum})
return(as.numeric(psi0))
}
#' @rdname jansonius
#' @return \code{psi2oct}: returns the corresponding angle in the OCT circular scan
#' @export
psi2oct <- function(psi0, diam = 12) {
radius <- diam / 2
r <- seq(4, 10, 0.001)
return(180 / pi * sapply(psi0, function(psi0) {
fb <- bundlePath(psi0)
coord <- jpolar2cart(data.frame(r = r, phi = fb(r)))
coord <- coord - c(15, 2)
coord <- coord[which.min(abs(coord$x^2 + coord$y^2 - radius^2)),]
oct <- atan2(coord$y, -coord$x)
oct[oct < 0] <- 2 * pi + oct[oct < 0]
return(oct)}))
}
#' @rdname jansonius
#' @param angle fovea-disc angle in degrees
#' @return \code{vf2gc}: returns the ganglion cell soma corresponding to the photoreceptors
#' of a visual field location
#' @export
vf2gc <- function(coord, angle = 0) {
Drasdo_LUT <- visualFields::drasdolut$Drasdo_LUT
Degs <- visualFields::drasdolut$Degs
MM <- visualFields::drasdolut$MM
############################################################################################################
#Input to the function must be in visual field coordinates for a right eye:
# - Negative Y is superior on the retina;
# - Negative X is temporal on the retina
# Fovea is assumed to be at {0, 0}
# The fovea-disc angle is 0 deg in the original Curcio and Allen map. If changed, it needs to be
# in retinal coordinates for a right eye, meaning that a positive angle indicates a positive elevation
# of the optic nerve over the fovea. This angle must be in degrees.
#Assumes an axial length of 24 mm. Displacements in degrees are the same for any axial length
#under the assumption of spherical global expansion and no changes to the anterior chamber of the schematic eye
############################################################################################################
x <- coord[,1]
y <- coord[,2]
#Inverts y axis to convert to retinal coordinates (necessary for next steps)
y <- -y
#Converts Fovea-Disc angle to radians for following calculations
angle <- angle/180*pi
#Rotate so that it matches Drasdo assumptions (Fovea-Optic Nerve angle is 0)
R <- rbind(c(cos(angle), -sin(angle)), c(sin(angle), cos(angle)))
XY <- R%*%rbind(x, y)
x <- XY[1,]
y <- XY[2,]
#Transforms from degrees to mm (using schematic eye from Montesano et al. 2020, axial length = 24 mm)
xmm <- sign(x)*approx(x = Degs, y = MM, abs(x))$y
ymm <- sign(y)*approx(x = Degs, y = MM, abs(y))$y
#Calculates displacement in mm using precalculated two dimensional LUTs
xdispMM <- interp2(x = Drasdo_LUT$Xv, y = Drasdo_LUT$Yv, Z = Drasdo_LUT$xlut, xp = xmm, yp = ymm)
ydispMM <- interp2(x = Drasdo_LUT$Xv, y = Drasdo_LUT$Yv, Z = Drasdo_LUT$ylut, xp = xmm, yp = ymm)
#Unchanged outside diplacement zone (no NAs within 30 degrees)
isNa <- which(is.na(xdispMM))
xdispMM[isNa] <- xmm[isNa]
ydispMM[isNa] <- ymm[isNa]
#Coverts back to degrees using the schematic eye
xdispDeg <- sign(xdispMM)*approx(x = MM, y = Degs, abs(xdispMM))$y
ydispDeg <- sign(ydispMM)*approx(x = MM, y = Degs, abs(ydispMM))$y
#Rerotate to match original input
XY <- inv(R)%*%rbind(x, y)
x <- XY[1,]
y <- XY[2,]
XY <- inv(R)%*%rbind(xdispDeg, ydispDeg)
xdispDeg <- XY[1,]
ydispDeg <- XY[2,]
#Inverts y axis to convert back to visual field coordinates
y <- -y
ydispDeg <- -ydispDeg
#Stores results for output
coord <- data.frame(x = xdispDeg, y = ydispDeg)
return(coord)
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/jansonius.R
|
#' @rdname linreg
#' @title Global and pointwise linear regression analyses
#' @description Functions that compute global and pointwise linear regression analyses:
#' \itemize{
#' \item\code{glr} performs global linear regression analysis
#' \item\code{plr} performs pointwise linear regression (PLR) analysis
#' \item\code{poplr} performs PoPLR analysis as in O'Leary et al (see reference)
#' }
#' @details
#' \itemize{
#' \item\code{poplr} there is a small difference between this implementation of
#' PoPLR and that proposed by O'Leary et al. The combined S statistic in the
#' paper used a natural logarithm. Here we not only use a logarithm of base 10
#' but we also divide by the number of locations. This way the S statistic has
#' a more direct interpretation as the average number of leading zeros in the
#' p-values for pointwise (simple) linear regression. That is, if S = 2, then
#' the p-values have on average 2 leading zeros, if S = 3, then 3 leading zeros,
#' and so on
#' }
#' @return
#' \itemize{
#' \item{\code{glr} and \code{plr} return a list with the following
#' \itemize{
#' \item\code{id} patient ID
#' \item\code{eye} patient eye
#' \item\code{type} type of data analysis. . For \code{glr}, it can be
#' `\code{ms}`, `\code{ss}`, `\code{md}`, `\code{sd}`, `\code{pmd}`,
#' `\code{psd}`, `\code{vfi}`, or `\code{gh}` for mean sensitivity,
#' standard deviation of sensitivities, mean deviation, standard
#' deviation of total deviation values, pattern mean deviation, pattern
#' standard deviation, VFI, and general height, respectively. For \code{plr}
#' and \code{poplr}, it can be `\code{s}`, `\code{td}`, or `\code{pd}` for
#' sensitivities, total deviation values, or pattern deviation values,
#' respectively
#' \item\code{testSlope} slope for \code{glr} or list of slopes for \code{plr}
#' to test as null hypotheses
#' \item\code{nvisits} number of visits
#' \item\code{years} years from baseline. Used for the pointwise linear
#' regression analysis
#' \item\code{data} data analyzed. For \code{glr}, it is the values of the
#' global indes analyzed. For \code{plr}, each column is a location of the
#' visual field used for the analysis. Each row is a visit (as many as years)
#' \item\code{pred} predicted values. Each column is a location of the visual
#' field used for the analysis. Each row is a visit (as many as years)
#' \item\code{sl} slopes estimated at each location for pointwise (simple)
#' linear regression
#' \item\code{int} intercept estimated at each location for pointwise (simple)
#' linear regression
#' \item\code{tval} t-values obtained for the left-tailed-t-tests for the slopes
#' obtained in the pointwise (simple) linear regression at each location
#' \item\code{pval} p-values obtained for the left-tailed t-tests for the slopes
#' obtained
#' }
#' }
#' \item{\code{poplr} returns a list with the following additional fields
#' \itemize{
#' \item\code{csl} the modifed Fisher's S-statistic for the left-tailed permutation test
#' \item\code{cslp} the p-value for the left-tailed permutation test
#' \item\code{csr} the modifed Fisher's S-statistic for the right-tailed permutation test
#' \item\code{csrp} the p-value for the right-tailed permutation test
#' \item\code{pstats} a list with the poinwise slopes (`\code{sl}`), intercepts
#' (`\code{int}`), standard errors (`\code{se}`), and p-values (`\code{pval}`) obtained
#' for the series at each location analyzed and for all \code{nperm} permutations
#' (in `\code{permutations}`)
#' \item\code{cstats} a list with all combined stats:
#' \itemize{
#' \item\code{csl, csr} the combined Fisher S-statistics for the left- and right-tailed
#' permutation tests respectively
#' \item\code{cslp, csrp} the corresponding p-values for the permutation tests
#' \item\code{cslall, csrall} the combined Fisher S-statistics for all permutations
#' }
#' }
#' }
#' }
#' @references
#' N. O'Leary, B. C. Chauhan, and P. H. Artes. \emph{Visual field progression in
#' glaucoma: estimating the overall significance of deterioration with permutation
#' analyses of pointwise linear regression (PoPLR)}. Investigative Ophthalmology
#' and Visual Science, 53, 2012
#' @examples
#' vf <- vffilter(vfpwgRetest24d2, id == 1) # select one patient
#' res <- glr(getgl(vf)) # linear regression with global indices
#' res <- plr(vf) # pointwise linear regression (PLR) with TD values
#' res <- poplr(vf) # Permutation of PLR with TD values
#' @param g global indices
#' @param type type of analysis. For \code{glr}, it can be `\code{ms}`, `\code{ss}`,
#' `\code{md}`, `\code{sd}`, `\code{pmd}`, `\code{psd}`, `\code{vfi}`, or `\code{gh}`
#' for mean sensitivity, standard deviation of sensitivities, mean deviation,
#' standard deviation of total deviation values, pattern mean deviation, pattern
#' standard deviation, VFI, and general height, respectively. For \code{plr} and
#' \code{poplr}, it can be `\code{s}`, `\code{td}`, or `\code{pd}` for sensitivities,
#' total deviation values, or pattern deviation values, respectively
#' @param testSlope slope, or slopes, to test as null hypothesis. Default is 0.
#' if a single value, then the same null hypothesis is used for all locations.
#' If a vector of values, then (for \code{plr} and \code{poplr}) each
#' location of the visual field will have a different null hypothesis. The length of
#' testSlope must be 1 or equal to the number of locations to be used in the PLR or
#' PoPLR analysis
#' @export
glr <- function(g, type = "md", testSlope = 0) {
if(nrow(unique(data.frame(g$id, g$eye))) != 1)
stop("all visual fields must belong to the same subject id and eye")
g <- vfsort(g) # sort just in case
years <- as.numeric(g$date - g$date[1]) / 365.25 # it should be difference in years from baseline date
if(type == "ms") {
y <- g$msens
} else if(type == "ss") {
y <- g$ssens
} else if(type == "md") {
y <- g$tmd
} else if(type == "sd") {
y <- g$tsd
} else if(type == "pmd") {
y <- g$pmd
} else if(type == "psd") {
y <- g$psd
} else if(type == "gh") {
y <- g$gh
} else if(type == "vfi") {
y <- g$vfi
} else stop("wrong type of analysis. It must be 'ms', 'ss', 'md', 'sd', 'pmd', 'psd', 'gh', or 'vfi'")
nvisits <- length(y)
precision <- 1e-6
X <- matrix(c(rep(1, length(years)), years), nvisits, 2)
ssvf <- (nvisits - 1 ) * var(y)
ssyears <- (nvisits - 1) * var(years)
kvyears <- (nvisits - 2) * ssyears
reg <- t(solve(t(X) %*% X) %*% t(X) %*% y)
int <- reg[1]
sl <- reg[2]
v <- (ssvf - ssyears * sl^2) / kvyears
v[v < 0] <- 0
se <- sqrt(v)
if(sd(y) <= precision) {
int <- as.numeric(y[1])
sl <- 0
se <- precision
}
tval <- (sl - testSlope) / se
pval <- pt(tval, nvisits - 2)
pred <- sl * years + int
if(type == "sd" || type == "psd") pval <- 1 - pval
return(list(id = g$id[1], eye = g$eye[1], type = type, testSlope = testSlope,
nvisits = nvisits, dates = g$date, years = years, data = y, pred = pred,
sl = sl, int = int, se = se, tval = tval, pval = pval))
}
#' @rdname linreg
#' @param vf visual fields sensitivity data
#' @export
plr <- function(vf, type = "td", testSlope = 0) {
if(nrow(unique(data.frame(vf$id, vf$eye))) != 1)
stop("all visual fields must belong to the same subject id and eye")
vf <- vfsort(vf) # sort just in case
years <- as.numeric(vf$date - vf$date[1]) / 365.25 # it should be difference in years from baseline date
bs <- getlocmap()$bs
if(type == "td") {
vf <- gettd(vf)
} else if(type == "pd") {
vf <- getpd(gettd(vf))
} else if(type != "s") stop("wrong type of analysis. It must be 's', 'td', or 'pd'")
nvisits <- nrow(vf)
y <- vf[,getvfcols()]
y[,bs] <- NA # ignore blind spot locations in the analysis
precision <- 1e-6
X <- matrix(c(rep(1, length(years)), years), nvisits, 2)
ssvf <- (nvisits - 1 ) * apply(y, 2, var)
ssyears <- (nvisits - 1) * var(years)
kvyears <- (nvisits - 2) * ssyears
reg <- t(solve(t(X) %*% X) %*% t(X) %*% as.matrix(y))
int <- t(reg[,1])
sl <- t(reg[,2])
v <- (ssvf - ssyears * sl^2) / kvyears
v[v < 0] <- 0
se <- sqrt(v)
# get the locations for which sensitivity did not change
invariantloc <- which(apply(y, 2, sd) <= precision)
# locations with non-changing series in sensitivity: slope is zero,
# intercept is not defined, and standard error is nominally very small
int[invariantloc] <- as.numeric(y[1,invariantloc])
sl[invariantloc] <- 0
se[invariantloc] <- precision
tval <- (sl - testSlope) / se
pval <- pt(tval, nvisits - 2)
# convert all to data frames and assign the corresponding column names, then return
sl <- as.data.frame(sl)
int <- as.data.frame(int)
se <- as.data.frame(se)
tval <- as.data.frame(tval)
pval <- as.data.frame(pval)
# predicted values
pred <- sapply(as.list(rbind(int, sl)), function(beta) {beta[1] + beta[2] * years})
return(list(id = vf$id[1], eye = vf$eye[1], type = type, testSlope = testSlope,
nvisits = nvisits, dates = vf$date, years = years, data = vf[,getvfcols()], pred = pred,
sl = sl, int = int, se = se, tval = tval, pval = pval))
}
#' @rdname linreg
#' @param nperm number of permutations. If the number of visits is 7 or less, then
#' \code{nperm = factorial(nrow(vf))}. For series greater than 8 visits, default is
#' factorial(7). For series up to 7 visits, it is the factorial of the number of visits
#' (with less than 7 visits, the number of possible permutations is small and results
#' can be unreliable. For instance, for 5 visits, the number of possible permutations is
#' only 120.)
#' @param trunc truncation value for the Truncated Product Method (see reference)
#' @export
poplr <- function(vf, type = "td", testSlope = 0, nperm = factorial(7), trunc = 1) {
if(nrow(unique(data.frame(vf$id, vf$eye))) != 1)
stop("all visual fields must belong to the same subject id and eye")
vf <- vfsort(vf) # sort just in case
years <- as.numeric(vf$date - vf$date[1]) / 365.25 # it should be difference in years from baseline date
bs <- getlocmap()$bs
if(type == "td") {
vf <- gettd(vf)
} else if(type == "pd") {
vf <- getpd(gettd(vf))
} else if(type != "s") stop("wrong type of analysis. It must be 's', 'td', or 'pd'")
nvisits <- nrow(vf)
y <- vf[,getvfcols()]
y[,bs] <- NA # ignore blind spot locations in the analysis
if(nvisits < 7) warning("random permutation analysis may be imprecise with less than 7 visual fields")
if(nvisits < 8) {
porder <- matrix(unlist(permn(nvisits)), ncol = nvisits, byrow = TRUE)
# is number of permutations is smaller than nrow(porder) do random sampling
if(nperm < nrow(porder))
porder <- rbind(porder[1,], porder[sample(nrow(porder), nperm - 1),])
else nperm <- nrow(porder)
} else {
if(nperm > 10000)
stop("I'm sorry Dave, I'm afraid I can't do that. I think you know what the problem is just as well as I do.")
porder <- t(replicate(factorial(8), c(1:nvisits)[sample(nvisits)]))
porder <- rbind(c(1:nvisits), porder)
porder <- unique(porder)[1:nperm,]
if(nrow(porder) != nperm)
stop("something went wrong and did not get the number of permutations you wanted")
}
# get the p-values from pointwise linear regression for series and all permumtations
pstats <- poplrpvals(y, years, porder, testSlope)
# ... and compute the combined S statistic, after removing the blind spot
pval <- pstats$permutations$pval
if(length(bs) > 0) pval <- pval[,-bs]
cstats <- poplrsstats(pval, trunc = trunc)
# predicted values
pred <- sapply(as.list(rbind(pstats$int, pstats$sl)), function(beta) {beta[1] + beta[2] * years})
return(list(id = vf$id[1], eye = vf$eye[1], type = type, testSlope = testSlope,
nvisits = nvisits, dates = vf$date, years = years, data = vf[,getvfcols()], pred = pred,
sl = pstats$sl, int = pstats$int, se = pstats$se, tval = pstats$tval,
pval = pstats$pval, nperm = nperm,
csl = cstats$csl, cslp = cstats$cslp,
csr = cstats$csr, csrp = cstats$csrp,
pstats = pstats, cstats = cstats))
}
###################################################################################
# INTERNAL FUNCTIONS: routines to ease load on poplr code
###################################################################################
# Internal functions, computes p-values from simple linear regression in all locations (columns)
# in vf for the series and for all permutations in porder
#' @noRd
poplrpvals <- function(vf, years, porder, testSlope = 0) {
if(!is.numeric(testSlope)) stop("testSlope must be numeric")
if(!(length(testSlope) == 1 || length(testSlope) == ncol(vf)))
stop("testSlope must be either a numeric scalar or a vector with the same length as columns there are in vf")
colNames <- names(vf)
vf <- as.matrix(vf)
# number of permutations, locations, and tests
nperm <- nrow(porder)
nloc <- ncol(vf)
nvisits <- nrow(vf)
precision <- 1e-6
sl <- matrix(c( NA ), nrow = nperm, ncol = nloc)
int <- matrix(c( NA ), nrow = nperm, ncol = nloc)
se <- matrix(c( NA ), nrow = nperm, ncol = nloc)
# add defaults for slope hypothesis tests when slr analysis is to be performed
if(length(testSlope) == 1) testSlope <- rep(testSlope, nloc)
# point-wise linear regression over time permutation-invarian values
syears <- sum(years)
myears <- mean(years)
ssyears <- (nvisits - 1) * var(years)
kvyears <- (nvisits - 2) * ssyears
mvf <- apply(vf, 2, mean)
ssvf <- (nvisits - 1 ) * apply(vf, 2, var)
# compute slopes per location, ...
sl <- sapply(1:nloc, function(loc)
(matrix(years[porder], nrow(porder), ncol(porder)) %*% vf[,loc] - syears * mean(vf[,loc])) / ssyears)
# ..., and then intercepts, ...
int <- matrix(rep(mvf, nperm), nrow(sl), ncol(sl), byrow = TRUE) - myears * sl
# ..., and then compute standard errors.
varslope <- (matrix(rep(ssvf, nperm), nrow(sl), ncol(sl), byrow = TRUE) - ssyears * sl^2) / kvyears
varslope[varslope < 0] <- 0
se <- sqrt(varslope)
# get the locations for which sensitivity did not change
invariantloc <- which(apply(vf, 2, sd) <= precision)
# locations with non-changing series in sensitivity: slope is zero,
# intercept is not defined, and standard error is nominally very small
sl[,invariantloc] <- 0
int[,invariantloc] <- vf[1,invariantloc]
se[,invariantloc] <- precision
# Get t-values and the corresponding p-values
tval <- (sl - t(matrix(rep(testSlope, nperm), nloc, nperm))) / se
pval <- pt(tval, nvisits - 2)
pval[pval < precision] <- precision
pval[pval > (1 - precision)] <- 1 - precision
# convert all to data frames and assign the corresponding column names, then return
sl <- as.data.frame(sl)
int <- as.data.frame(int)
se <- as.data.frame(se)
tval <- as.data.frame(tval)
pval <- as.data.frame(pval)
names(sl) <- colNames
names(int) <- colNames
names(se) <- colNames
names(tval) <- colNames
names(pval) <- colNames
return(list(sl = sl[1,], int = int[1,], se = se[1,], tval = tval[1,], pval = pval[1,],
permutations = list(sl = sl, int = int, se = se, tval = tval, pval = pval)))
}
# Internal function: computes the modified Fisher S, applying the Truncated Product Method,
# if requested, from the p-values obtained for the series at each location and for all
# permutations. It returns the p-value based on the observed Fisher S statistic and the
# distribution obtained from the series permutations. It does so for a left-tailed hypothesis
# test and for the right-tailed hypothesis test
#' @noRd
poplrsstats <- function(pval, trunc = 1) {
##############
# input checks
##############
# truncation must be between zero and one
if(trunc <= 0 | trunc > 1)
stop("truncation must be between 0 and 1")
# init
nperm <- nrow(pval)
# Apply the Truncated Product Method if required (i.e. trunc between 0 and 1)
# left-tail analysis
tpl <- apply(pval, 1, min)
tpl[tpl < trunc] <- trunc
kl <- matrix(rep(1, nrow(pval) * ncol(pval)), nrow(pval), ncol(pval))
kl[pval > tpl] <- 0
# right-tail analysis
pvalr <- 1 - pval
tpr <- apply(pvalr, 1, min)
tpr[tpr < trunc] <- trunc
kr <- matrix(rep(1, nrow(pvalr) * ncol(pvalr)), nrow(pvalr), ncol(pvalr))
kr[pvalr > tpr] <- 0
# combine p-value test statistics with a modified Fisher S statistic
csl <- -rowSums(kl * log(pval))
csr <- -rowSums(kr * log(1 - pval))
# observed and permutation test statistics
cslp <- 1 - rank(csl) / nperm
csrp <- 1 - rank(csr) / nperm
return(list(csl = csl[1], cslp = cslp[1], cslall = csl, cslpall = cslp,
csr = csr[1], csrp = csrp[1], csrall = csr, csrpall = csrp))
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/linreg.R
|
#' @rdname locmap
#' @title Locmap management
#' @description Functions to handle location maps, which are lists with x and y
#' coordinates and other importan information about the visual field test
#' locations. Check section \code{Structure of location maps} below for details
#' @details
#' \itemize{
#' \item\code{locread} reads a csv file with location map data
#' \item\code{locwrite} writes a csv file with location map data
#' }
#' @section Structure of location maps:
#' Each element in the list \code{locmaps} is a location map that
#' contains the following fields
#' \itemize{
#' \item\code{name} descriptive name
#' \item\code{desc} brief description
#' \item\code{coord} coordinates of the visual field locations
#' \item\code{bs} if not empty, the locations that ought to be removed
#' for statistical analysis due to their proximity to the blind spot
#' }
#' @examples
#' # write and read location map
#' tf <- tempfile("locmap")
#' locwrite(getlocmap(), file = tf) # save current locmap in a temp file
#' print(locread(tf, name = "name", desc = "desc", bs = c(1, 2))) # read the temp file
#' @param file the name of the file which the data are to be read from
#' @param name to give the location map
#' @param desc brief description for the location map
#' @param bs locations that should be excluded from statistical analysis because
#' of their proximity to the blind spot
#' @param ... arguments to be passed to or from methods
#' @return \code{locread} a list with information about a location map
#' @export
locread <- function(file, name = "", desc = "", bs = numeric(), ...)
return(list(name = name,
desc = desc,
coord = read.csv(file, stringsAsFactors = FALSE, ...),
bs = bs))
#' @rdname locmap
#' @param locmap location map from which to get coordinates to export as csv file
#' @return \code{locwrite} No return value
#' @export
locwrite <- function(locmap, file, ...)
write.csv(locmap$coord, file, row.names = FALSE, ...)
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/locmap.R
|
#' @rdname nv
#' @title Normative values generation and management
#' @description Functions to generate and handle normative values. Check section
#' \code{Structure of normative values} below for details about how to generate
#' functioning normative values
#' @section Structure of normative values:
#' This is one of the most complex structures in visualFields. It is necessary
#' to be able to run statistical analyses of visual fields obtained from
#' perimetry and it requires data from healthy eyes for its generation. The
#' normative values are only as good as the data they are generated from. Two
#' common ways to generate full normative values from a dataset of healthy eyes,
#' are provided in the package, depending on the \code{method} selected. The first
#' one, \code{method="pointwise"}, generates normative values directly from
#' pointwise statistics. The second one, \code{method="smooth"}, uses a 2D
#' quadratic functions to smooth out those pointwise statistics. Variations
#' or improvements can be regenerated by copying the code in those functions and
#' editing it.
#' \itemize{
#' \item\code{info} information regarding normative values. Info is not necessary
#' to carry out statistics, but is useful for the generation of reports. The
#' fields need not be the same as the ones listed here, although these are used
#' in the reports in \code{\link{vfsfa}} for single field analysis and
#' \code{\link{vfspa}} for series progression analysis.
#' \itemize{
#' \item\code{name} name of the normative values
#' \item\code{perimetry} perimetry device for which normative values are intended
#' \item\code{strategy} psychophysical strategy
#' \item\code{size} stimulus size, e.g. Goldmann size III, size V
#' }
#' \item\code{agem} The normative values' age model. The default methods' generate
#' age linear models with coefficients for each location in \code{locmap} in
#' \code{coeff} and the function definining the model in \code{model}
#' \item\code{sd} standard deviations of the sensitivities, \code{s}, total
#' deviation (TD) values, \code{td}, and pattern deviation (PD) values, \code{pd}
#' \item\code{luts} Lookup tables to obtain probability levels for TD and PD values.
#' \itemize{
#' \item\code{probs} probability levels
#' \item\code{td}, \code{pd} lookup tables for TD and PD values at each location
#' in \code{locmaps}
#' \item\code{global} lookup table for the following global visual field indices
#' \itemize{
#' \item\code{ms} mean sensitivity (MS) calculated as the unweithed average
#' over locations' values
#' \item\code{ss} standard deviation of sensitivity calculated as the
#' unweithed standard deviation over locations' values
#' \item\code{md} mean deviation (MD) calculated as the weithed average
#' over locations' values. Weights are the inverse of the standard
#' deviation in \code{sd} for TD at each location.
#' \item\code{sd} standard deviation of total deviation calculated as the
#' weithed standard deviation over locations' values. Weights are the inverse of the standard
#' deviation in \code{sd} for TD at each location.
#' \item\code{pmd} pattern mean deviation calculated as the weithed average
#' over locations' values. Weights are the inverse of the standard
#' deviation in \code{sd} for PD at each location.
#' \item\code{psd} pattern standard deviation calculated as the weithed
#' standard deviation over locations' values. Weights are the inverse
#' of the standard deviation in \code{sd} for PD at each location.
#' \item\code{gh} general height. This is defined traditionally for the 24-2
#' and the 30-2 as the approximatelly the 85th percentile of TD values
#' \item\code{vfi} the oddly defined visual field index
#' }
#' }
#' \item\code{tdfun} a function defining how to obtain the TD values. Typically, it
#' is a function of age and sensitivity values and it is defined as sensitivity
#' values minus the age-corrected mean normal obtained as defined in \code{agem}.
#' Thus, TD values are negative is visual field sensitivity values are below
#' mean normal and positive if they are above mean normal
#' \item\code{ghfun} a function defining how to obtain the general height
#' \item\code{pdfun} a function defining how to obtain the PD values. Tipically, they
#' are obtaines as the TD values minus the general height
#' \item\code{glfun} a function defining how to obtain different global indices
#' \item\code{tdpfun}, \code{pdpfun}, \code{glpfun} mapping functions to get
#' the probability levels corresponding to TD, PD and global indices values and
#' based on the lookup tables defined in \code{luts}
#' }
#' @examples
#' # generate normative values from SUNY-IU dataset of healthy eyes
#' # pointwise
#' sunyiu_24d2_pw <- nvgenerate(vfctrSunyiu24d2, method = "pointwise",
#' name = "SUNY-IU pointwise NVs",
#' perimetry = "static automated perimetry",
#' strategy = "SITA standard",
#' size = "Size III")
#' # smooth
#' sunyiu_24d2 <- nvgenerate(vfctrSunyiu24d2, method = "smooth",
#' name = "SUNY-IU smoothed NVs",
#' perimetry = "static automated perimetry",
#' strategy = "SITA standard",
#' size = "Size III")
#' @param vf visual fields data
#' @param method method to generate normative values, pointwise (`\code{pointwise}`)
#' or smoothed with 2-dimensional quadratic functions (`\code{smooth}`)
#' @param probs numeric vector of probabilities with values in \code{[0,1]}.
#' The values 0 and 1 must be included
#' @param name name for the normative values, e.g., "SUNY-IU pointwise NVs".
#' Default is blank
#' @param perimetry perimetry used to obtain normative data, e.g.,
#' "static automated perimetry" (default)
#' @param strategy psychophysical strategy used to obtain threshold values, e.g.,
#' "SITA standard". Default is blank
#' @param size stimulus size, if the same size was used for all visual field
#' locations or empty (default)
#' @return \code{nvgenerate} returns a list with normative values
#' @export
nvgenerate <- function(vf, method = "pointwise",
probs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 0.98, 0.99, 0.995, 1),
name = "",
perimetry = "static automated perimetry",
strategy = "",
size = "") {
if(method != "pointwise" && method != "smooth")
stop("wrong method for generating normative values")
if(any(probs < 0) || any(probs > 1))
stop("probability values must be between 0 and 1")
if(!any(probs == 0) || !any(probs == 1))
stop("probability values must include values 0 and 1")
probs <- sort(probs)
info <- list(name = name, perimetry = perimetry, strategy = strategy, size = size)
# construct the default age linear model
agem <- agelm(vf)
if(method == "smooth") { # smooth out intercepts and slopes
agem$coeff$intercept <- vfsmooth(agem$coeff$intercept)
agem$coeff$slope <- vfsmooth(agem$coeff$slope)
environment(agem$model)$coeff <- t(as.matrix(agem$coeff))
}
# define the functions for the default methods to compute TD, GH, and PD
tdfun <- tddef(agem)
ghfun <- ghdef(0.85)
pdfun <- pddef(ghfun)
# get TD and PD values, ...
td <- tdfun(vf)
pd <- pdfun(td)
# define mapping functions to get probability levels
luts <- list(probs = probs, td = NA, pd = NA, g = NA) # prepare list to
tdplutfun <- lutdef(td, probs, "quantile")
pdplutfun <- lutdef(pd, probs, "quantile")
luts$td <- tdplutfun$lut
tdpfun <- tdplutfun$fun
luts$pd <- pdplutfun$lut
pdpfun <- pdplutfun$fun
# ... and return probability levels
tdp <- tdpfun(td)
pdp <- pdpfun(pd)
# compute weighted standard deviations. Those for td and pd will be used to
# estimate weighted averages and standard deviations
sdev <- vfsd(vf, td, pd)
if(method == "smooth") { # smooth out standard deviations
sdev$vf <- vfsmooth(sdev$vf)
sdev$td <- vfsmooth(sdev$td)
sdev$pd <- vfsmooth(sdev$pd)
}
# define global indices
glfun <- gdef(agem, sdev$td, sdev$pd)
# ... and return them
gl <- glfun(vf, td, pd, tdp, pdp, ghfun(td))
# define mapping functions to get probability levels for global indices
gplutfun <- lutgdef(gl, probs, "quantile")
luts$g <- gplutfun$lut
glpfun <- gplutfun$fun
# return the list defining the normative values
return(list(info = info, agem = agem, sd = sdev, luts = luts,
tdfun = tdfun, tdpfun = tdpfun, pdfun = pdfun, pdpfun = pdpfun,
ghfun = ghfun, glfun = glfun, glpfun = glpfun))
}
#' @rdname nv
#' @param vf visual field data with sensitivity values
#' @return \code{agelm} returns a list with coefficients and a function defining
#' a linear age model
#' @export
agelm <- function(vf) {
# get weights so that each subject is counted the same as the rest
counts <- table(vf$id)
w <- as.numeric(1 / rep(counts, counts)) / length(unique(vf$id))
# get age and sensitivity values
age <- vf$age # get age
vf <- vf[,.vfenv$locini:ncol(vf)] # get senstivivities
coeff <- sapply(as.list(vf), function(y) lm(y ~ age, weights = w)$coefficients)
if(length(getlocmap()$bs) > 0) # for locations near the blind spot
coeff[,getlocmap()$bs] <- NA # slope and intercept must be undefined
model <- as.function(alist(age = , cbind(rep(1, length(age)), age) %*% coeff))
agem <- list(coeff = as.data.frame(t(coeff)), model = model)
names(agem$coeff) <- c("intercept", "slope")
return(agem)
}
#' @rdname nv
#' @param agem age model to construct the function to obtain TD values
#' @return \code{tddef} returns a function for the computation of TD values
#' @export
tddef <- function(agem)
return(as.function(alist(vf = , {
vf[,getvfcols()] <- vf[,getvfcols()] - agem$model(vf$age)
return(vf)
})))
#' @rdname nv
#' @param perc the percentile to obtain the ranked TD value as
#' reference for the general height (GH) of the visual field.
#' Default is the 85th percentile, thus \code{0.85}
#' @return \code{ghdef} returns a function for the computation of the general height
#' @export
ghdef <- function(perc = 0.85)
as.function(alist(td = , {
# get on the TD values and remove all other information columns
td <- td[,getvfcols()]
# columns with all NA values are removed as they must be those
# too close to the blind spot for analysis
td <- td[,apply(!is.na(td), 2, all)]
pos <- floor((1 - perc) * ncol(td)) # which sorted location to return
### CARE: This works for 24-2, where pos is 7, it works for 10-2 where
### pos is 10, but for 30-2 it returns location 11, not 10. This can be
### fixed if perc = 0.86
return(as.numeric(apply(td, 1, sort, decreasing = TRUE)[pos,]))
}))
#' @rdname nv
#' @param ghfun function used for determination of the GH and PD values
#' @return \code{pddef} returns a function for the computation of PD values
#' @export
pddef <- function(ghfun = ghdef(0.85))
return(as.function(alist(td = , {
td[,getvfcols()] <- td[,getvfcols()] - ghfun(td)
return(td)
})))
#' @rdname nv
#' @param type type of estimation for the weighted quantile values. See
#' \code{\link{wtd.quantile}} for details. Default is `\code{quantile}`
#' @param ... arguments to be passed to or from methods
#' @return \code{lutdef} returns a look up table and a function for the
#' computation of the probability values for TD and PD
#' @export
lutdef <- function(vf, probs, type = "quantile", ...) {
counts <- table(vf$id)
w <- as.numeric(1 / rep(counts, counts))
vf <- vf[,getvfcols()] # remove info fields
nacols <- which(apply(is.na(vf), 2, all)) # awkward patch because wtd.quantile
vf[,nacols] <- 0 # does not tolerate columns with NA
# probability level look up table
lut <- apply(vf, 2, wtd.quantile, type = type, na.rm = TRUE,
weights = w, normwt = FALSE, probs = probs, ...)
row.names(lut) <- as.character(probs)
lut[,nacols] <- as.numeric(NA) # put back NAs in blind spot locations
lut[1,] <- -Inf # theoretical min for quantile 0 is minus infinite
lut[nrow(lut),] <- +Inf # theoretical min for quantile 0 is plus infinite
fun <- as.function(alist(vf = , {
lev <- probs # levels
vals <- vf[,getvfcols()]
valsp <- as.data.frame(matrix(as.numeric(NA), nrow(vals), ncol(vals)))
names(valsp) <- names(vals)
for(i in nrow(lut):2) {
co <- matrix(rep(lut[i,], nrow(vals)), nrow(vals), ncol(vals), byrow = TRUE)
valsp[vals < co] <- lev[i]
}
vf[,getvfcols()] <- valsp
return(vf)
}))
return(list(lut = as.data.frame(lut), fun = fun))
}
#' @rdname nv
#' @param sdtd standard deviations obtained for TD values
#' @param sdpd standard deviations obtained for PD values
#' @return \code{gdef} returns a function to compute global indices
#' @export
gdef <- function(agem, sdtd, sdpd) {
coord <- getlocmap()$coord
bs <- getlocmap()$bs
if(length(bs) > 0) { # remove blind spot
sdtd <- sdtd[-bs]
sdpd <- sdpd[-bs]
coord <- coord[-bs,]
}
wtd <- 1 / sdtd
wpd <- 1 / sdpd
fun <- as.function(alist(vf = , td = , pd = , tdp = , pdp = , gh = , {
vfinfo <- vf[,1:(getlocini() - 1)] # keep key to add to the g table later on
vf <- vf[,getvfcols()] # remove info columns
td <- td[,getvfcols()]
pd <- pd[,getvfcols()]
tdp <- tdp[,getvfcols()]
pdp <- pdp[,getvfcols()]
mnsens <- agem$model(vfinfo$age)
gh <- gh # silly patch so that it check does not complain about gh
if(length(bs) > 0) { # remove blind spot
vf <- vf[,-bs]
td <- td[,-bs]
pd <- pd[,-bs]
tdp <- tdp[,-bs]
pdp <- pdp[,-bs]
mnsens <- mnsens[,-bs]
}
msens <- apply(vf, 1, mean)
ssens <- apply(vf, 1, sd)
tmd <- apply(td, 1, wtd.mean, weights = wtd / sum(wtd))
tsd <- sqrt(apply(td, 1, wtd.var, weights = wtd))
pmd <- apply(pd, 1, wtd.mean, weights = wpd)
psd <- sqrt(apply(pd, 1, wtd.var, weights = wpd))
vfi <- vfcomputevfi(coord, tmd, mnsens, vf, td, pd, tdp, pdp)
g <- data.frame(msens = msens, ssens = ssens, tmd = tmd,
tsd = tsd, pmd = pmd, psd = psd, gh = gh, vfi = vfi)
return(cbind(vfinfo, g))
}))
return(fun)
}
#' @rdname nv
#' @param g a table with global indices
#' @return \code{lutgdef} returns a look up table and a function for the
#' computation of the probability values for global indices
#' @export
lutgdef <- function(g, probs, type = "quantile", ...) {
# CARE the g in the parent and child functions are
# different, the g at parents level is used to compute
# the empirical quantiles. The function then returns another
# function with input argument g, which can be table with any
# TD or PD values, which should be of the same type (perimeter,
# location maps, etc), get weights so that each subject is
# counted the same as the rest
counts <- table(g$id)
w <- as.numeric(1 / rep(counts, counts))
g <- g[,getlocini():ncol(g)] # remove key fields
nacols <- which(apply(is.na(g), 2, all)) # awkward patch because wtd.quantile
g[,nacols] <- 0 # does not tolerate columns with NA
# probability level look up table
lut <- matrix(NA, length(probs), ncol(g))
colnames(lut) <- names(g)
idxm <- c(1, 3, 5, 7, 8)
idxs <- c(2, 4, 6)
lut[,idxm] <- apply(g[,idxm], 2, wtd.quantile,
type = type, na.rm = TRUE, weights = w,
normwt = FALSE, probs = probs, ...)
lut[,idxs] <- apply(g[,idxs], 2, wtd.quantile,
type = type, na.rm = TRUE, weights = w,
normwt = FALSE, probs = 1 - probs, ...)
rownames(lut) <- paste0(probs, "%")
lut[,nacols] <- NA # put back NAs in blind spot locations
lut[1,idxm] <- -Inf # theoretical min for quantile 0 is minus infinite
lut[nrow(lut),idxm] <- +Inf # theoretical min for quantile 0 is plus infinite
lut[1,idxs] <- +Inf # theoretical min for quantile 0 is minus infinite
lut[nrow(lut),idxs] <- -Inf # theoretical min for quantile 0 is plus infinite
fun <- as.function(alist(g = , {
lev <- probs # levels
vfinfo <- g[,1:(getlocini() - 1)]
g <- g[,getlocini():ncol(g)]
gp <- as.data.frame(matrix(NA, nrow(g), ncol(g)))
names(gp) <- names(g)
# analysys for means (greater is better) is different than for SDs (greater is worse)
gm <- g[,idxm]
lutm <- lut[,idxm]
gpm <- gp[,idxm]
gs <- g[,idxs]
luts <- lut[,idxs]
gps <- gp[,idxs]
for(i in nrow(lut):2) {
com <- matrix(rep(lutm[i,], nrow(gm)), nrow(gm), ncol(gm), byrow = TRUE)
cos <- matrix(rep(luts[i,], nrow(gs)), nrow(gs), ncol(gs), byrow = TRUE)
gpm[gm < com] <- lev[i]
gps[gs > cos] <- lev[i]
}
gp[,idxm] <- gpm
gp[,idxs] <- gps
return(cbind(vfinfo, gp))
}))
return(list(lut = as.data.frame(lut), fun = fun))
}
###################################################################################
# INTERNAL FUNCTIONS: routines to ease load on code generating normative values
###################################################################################
#' @noRd
vfsmooth <- function(vals) {
x <- getlocmap()$coord$x
y <- getlocmap()$coord$y
vals[!is.na(vals)] <- predict(lm(vals ~ x + y + I(x^2) + I(y^2)))
return(vals)
}
#' @noRd
vfsd <- function(vf, td, pd) {
counts <- table(vf$id)
w <- as.numeric(1 / rep(counts, counts))
vf <- vf[,getvfcols()] # remove info fields
td <- td[,getvfcols()]
pd <- pd[,getvfcols()]
# get blind spot
bs <- getlocmap()$bs
# blindspot columns to zero, so wtd.var does not crash
if(length(bs) > 0) vf[, bs] <- td[, bs] <- pd[, bs] <- 0
vfsd <- sqrt(apply(vf, 2, wtd.var, weights = w, normwt = FALSE))
tdsd <- sqrt(apply(td, 2, wtd.var, weights = w, normwt = FALSE))
pdsd <- sqrt(apply(pd, 2, wtd.var, weights = w, normwt = FALSE))
# blindspot columns must not have standard deviations
if(length(bs) > 0) vfsd[bs] <- tdsd[bs] <- pdsd[bs] <- NA
return(data.frame(vf = vfsd, td = tdsd, pd = pdsd))
}
#' @noRd
vfcomputevfi <- function(coord, tmd, mnsens, vf, td, pd, tdp, pdp) {
d <- sqrt(apply(coord^2, 1, sum))
w <- 1 / (0.08 * (d + 0.8)) # parameters used for observer J.M. in Figure 14
# which is what seems to be most consistent between Levi et al VR 1985 (see
# page 975). It is also possible that other parameters were used, but I
# cannot figure it out. Here is the logic that led me to use the the current
# formulation to calculate the weights for the VFI.
#
# w0 <- NA
# w0[d < 6] <- 3.29
# w0[d > 6 & d < 12] <- 1.28
# w0[d > 12 & d < 18] <- 0.79
# w0[d > 18 & d < 24] <- 0.57
# w0[d > 24 & d < 30] <- 0.45
# plot(coord$x,coord$y, typ = "n")
# text(coord$x,coord$y, w0)
# lm((1 / w0) ~ d) # gives intercept 0.02 and slope 0.08
# 0.02 / 0.08 # it returns 0.25, which is not the parameter for
# # cortical processing X = 2.5 proposed by Levi et al
# # The other parameter X = 0.8 for retinal processing
# # is closer and is the parameter they should have
# # chosen for the experiments which results are shown
# # in their Figure 14
# plot(d, 1 / w0, xlim = c(0, 30), ylim = c(0, 2.5))
# dlm <- c(0,30)
# lines(dlm, 0.08 * (dlm + 0.8), col = "red")
#
# References:
# D. M. Levi, S. A. Klein, and A. P. Aitsebaomo. Vernier acuity,
# crowding and cortical magnification. Vision Research,
# 25(7):963–977, 1985
#
# B. Bengtsson and A. Heijl. A visual field index for calculation
# of glaucoma rate of progression. American Journal of Ophthalmology,
# 145(2):343–353, 2008
# Now that we have our weights, even if different from Bengsston and Heijl
# we can compute the VFI
vfiloc <- 100 * (1 - abs(td) / mnsens)
# if within normal limits, then score is 100
# if MD is greater than -20 dB, look at PD probability levels
usePD <- matrix(rep(tmd >= -20, ncol(tdp)), nrow(tdp), ncol(tdp))
vfiloc[usePD & pdp > 0.05] <- 100
# else, look at TD probability levels
vfiloc[!usePD & tdp > 0.05] <- 100
# non-seen locations have a score of 0
vfiloc[vf < 0] <- 0
return(apply(vfiloc, 1, wtd.mean, weights = w)) # return weighted sum of scores
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/nv.R
|
#' @rdname vf
#' @title Visual field dataset
#' @description The main object of the visualFields package is a table with
#' a specific format and fields that are mandatory for their management and
#' processing (mainly statistical analysis). Each record (row) in the table
#' contains data for a single visual field test. The mandatory fields specify
#' subject (by its ID code), eye, and test date and time. There are required
#' fields statistical and reliability analyses (e.g., age for the determination
#' of total-deviation and pattern-deviation values, and for global indices and
#' fpr, fnr, fl for the proportion of false positives, false negative, and
#' fixation losses). The rest of mandatory fields are sensitivity or deviation
#' data for each visual field test location. (The number of fields for
#' tested locations varies with the location map, 54 for the 24-2, 76 for the
#' 30-2, 68 for the 10-2, etc.). Check section \code{Structure of visual fields data}
#' below for details about the required structure of the table contatining the
#' visual fields datasets.
#'
#' The following functions carry out analysis on visual fields data:
#' \itemize{
#' \item\code{vfdesc} descriptive summary of a visual field dataset
#' \item\code{vfsort} sort visual field data
#' \item\code{vfisvalid} check if a table with visual field data is properly
#' formatted and valid for analysis
#' \item\code{vfread} read a csv file with visual field data
#' \item\code{vfwrite} write a csv file with visual field data
#' \item\code{vfjoin} joins two visual field datasets
#' \item\code{vffilter} filters elements from a visual field dataset with
#' matching conditions. This function is just a wrapper for \code{dplyr}'s
#' function \code{\link{filter}}
#' \item\code{vfselect} select visual field data by index or the first or last
#' \code{n} visits per subject and eye
#' \item\code{gettd} computes total-deviation (TD) values and probability values
#' \item\code{gettdp} computes total-deviation (TD) probability values
#' \item\code{getpd} computes pattern-deviation (PD) values
#' \item\code{getpdp} computes pattern-deviation (PD) probability values
#' \item\code{getgh} computes the general height (GH) from the TD tables
#' \item\code{getgl} computes visual fields global indices
#' \item\code{getglp} computes computes visual fields global indices probability values
#' }
#' @details
#' \itemize{
#' \item\code{vfselect} when selecting the last or first few visual fields per
#' subject and eye, if that subject and eye has fewer than \code{n} visits,
#' then all visits are returned
#' }
#' @section Structure of visual fields data:
#' Visual fields data is the central object used in visualFields. It is a table of
#' visual field data collected with the same perimeter, background and stimulus
#' paradigm (e.g., static automated perimetry or frequency-doubling perimetry),
#' stimulus size (e.g., Goldmann size III), grid of visual field test locations
#' (e.g., 24-2), and psychophysical testing strategy (e.g., SITA standard).
#' Normative values can be obtained from appropriate datasets with data for healthy
#' eyes and these normative values can then be used to generate statistical analyses
#' and visualizations of data for patients with retinal or visual anomalies.
#'
#' Each record correspond to a specific test for an eye of a subject taken on a
#' specific date at a specific time. Visual field data must have the following
#' columns
#' \itemize{
#' \item\code{id} an id uniquely identifying a subject. This field is mandatory
#' \item\code{eye} should be "OD" for right eye or "OS" for left eye. This field is
#' mandatory
#' \item\code{date} test date. This field is mandatory
#' \item\code{time} test time. This field is mandatory
#' \item\code{age} age of the patient on the test date. This field is required to
#' obtain total-deviation, pattern-deviation values, and other age-dependent
#' local and global indices
#' \item\code{type} type of subject, Could be a healthy subject (ctr for control)
#' or a patient with glaucoma (pwg) or a patient with idiopatic intraocular
#' hypertension (iih) or other. This field is no required for management or
#' statistical analysis.
#' \item\code{fpr} false positive rate. This field is no required for management or
#' statistical analysis.
#' \item\code{fnr} false negative rate. This field is no required for management or
#' statistical analysis.
#' \item\code{fl} fixation losses. This field is no required for management or
#' statistical analysis.
#' \item\code{l1..ln} sensitivity, total-deviation, or pattern-deviation values for
#' each location. For analysis with visualFields there should be as many columns
#' as coordinates in the location map set in the visualFields environment. These
#' fields are mandatory.
#' }
#' @examples
#' # get dataset description from visual field table
#' vfdesc(vfctrSunyiu24d2)
#' # sort dataset
#' vfsort(vfctrSunyiu24d2[c(5, 4, 10, 50, 30),])
#' # check if a visualField is valid
#' vf <- vfctrSunyiu24d2
#' vfisvalid(vf) # valid visual field data
#' vf$id[5] <- NA
#' vfisvalid(vf) # invalid visual field data
#' # write and read visual field data
#' vf <- vfctrSunyiu24d2
#' tf <- tempfile("vf")
#' vfwrite(vf, file = tf) # save current locmap in a temp file
#' head(vfread(tf)) # read the temp file
#' # join visual fields datasets
#' vfjoin(vfctrSunyiu24d2, vfpwgRetest24d2)
#' # visual field subselection
#' vffilter(vf, id == 1) # fields corresponding to a single subject
#' vffilter(vf, id == 1 & eye == "OD") # fields for a single subject's right eye
#' unique(vffilter(vf, eye == "OS")$eye) # only left eyes
#' vffilter(vfjoin(vfctrSunyiu24d2, vfpwgRetest24d2), type == "ctr") # get only controls
#' vffilter(vfjoin(vfctrSunyiu24d2, vfpwgRetest24d2), type == "pwg") # get only patients
#' # select visual fields by index
#' vfselect(vfctrSunyiu24d2, sel = c(1:4, 150))
#' # select last few visual fields per subject and eye
#' vfselect(vfpwgRetest24d2, sel = "last")
#' # select first few visual fields per subject and eye
#' vfselect(vfpwgRetest24d2, sel = "first")
#' vfselect(vfpwgRetest24d2, sel = "first", n = 5) # get the last 5 visits
#' # compute visual field statistics
#' vf <- vfpwgSunyiu24d2
#' td <- gettd(vf) # get TD values
#' tdp <- gettdp(td) # get TD probability values
#' pd <- getpd(td) # get PD values
#' pdp <- getpdp(pd) # get PD probability values
#' gh <- getgh(td) # get the general height
#' g <- getgl(vf) # get global indices
#' gp <- getglp(g) # get global indices probability values
#' @param vf visual field dataset
#' @return \code{vfdesc} returns descriptive statistics of a visual field dataset
#' @export
vfdesc <- function(vf) {
summary(vf) # PLACEHOLDER. TO BE REPLACED
}
#' @rdname vf
#' @param decreasing sort decreasing or increasing?
#' Default is increasing, that is \code{decreasing = FALSE}
#' @param ... arguments to be passed to or from methods
#' @return \code{vfsort} returns a sorted visual field dataset
#' @export
vfsort <- function(vf, decreasing = FALSE)
return(vf[order(vf$id, vf$eye, vf$date, vf$time, decreasing = decreasing),])
#' @rdname vf
#' @param vf visual field data
#' @return \code{vfisvalid} returns \code{TRUE} or \code{FALSE}
#' @export
vfisvalid <- function(vf) {
# check mandatory fields exist and have the correct format
mandatory <- c("id", "eye", "date", "time", "age")
eyecodes <- c("OD", "OS", "OU")
missingField <- !all(sapply(mandatory, function(field) {
if(!(field %in% names(vf))) {
warning(paste("Missing mandatory fields:", field, call. = FALSE))
return(FALSE)
}
return(TRUE)
}))
if(missingField) return(FALSE)
# no NAs allowed in mandatory fields
nacols <- !all(sapply(mandatory, function(field) {
if(any(is.na(vf[,field]))) {
warning(paste("The mandatory field", field, "contains NAs"), call. = FALSE)
return(FALSE)
}
return(TRUE)
}))
if(nacols) return(FALSE)
# check eye has only allowed values "OD" "OS", or "OU"
if(!all(unique(vf$eye) %in% eyecodes)) {
warning(paste("Wrong eye code. They must be one of the following:",
paste(eyecodes, collapse = ", ")), call. = FALSE)
return(FALSE)
}
# check date does have Date class
if(class(vf$date) != "Date") {
warning("Field 'date' must be sucessfully converted to 'Date' class", call. = FALSE)
return(FALSE)
}
# check data structure for all locations is correct
if((ncol(vf) - getlocini() + 1) != length(getvfcols())) {
warning("Unexpected number of columns with visual field data", call. = FALSE)
return(FALSE)
}
# check that all data columns are numeric (or are all their values NA meaning, which
# may happen for locations to be excluded from statistical analysis due to their
# proximity to the blind spot)
if(!all(sapply(getvfcols(), function(loc) all(is.na(vf[,loc])) || is.numeric(vf[,loc])))) {
warning("Columns with visual field data are non-numeric", call. = FALSE)
return(FALSE)
}
return(TRUE)
}
#' @rdname vf
#' @param file the name of the csv file from where to read the data
#' @param dateformat format to be used for date. Its default value
#' is \code{\%Y-\%m-\%d}
#' @param eyecodes codification for right and left eye, respectively.
#' By default in visualField uses `\code{OD}` and `\code{OS}` for
#' right and left eye respectively, but it is common to receive csv
#' files with the codes `\code{R}` and `\code{L}`. The code `\code{OU}`
#' for both eyes is also allowed
#' \code{eyecodes} should be equal to `\code{c("OD", "OS")}` or `\code{c("R", "L")}`.
#' By default it is `\code{eyecodes = c("OD", "OS", "OU")}`
#' @param ... arguments to be passed to or from methods
#' @return \code{vfread} returns a visual field dataset
#' @export
vfread <- function(file, dateformat = "%Y-%m-%d", eyecodes = c("OD", "OS", "OU"), ...) {
vf <- read.csv(file, stringsAsFactors = FALSE, ...)
# reformat eye
vf$eye[vf$eye == eyecodes[1]] <- "OD"
vf$eye[vf$eye == eyecodes[2]] <- "OS"
vf$eye[vf$eye == eyecodes[3]] <- "OU"
# reformat date
vf$date <- as.Date(vf$date, dateformat)
if(!vfisvalid(vf)) warning("visual field dataset read with warnings. Check the loaded data")
return(vf)
}
#' @rdname vf
#' @param file the name of the csv file where to write the data
#' @return \code{vfwrite} No return value
#' @export
vfwrite <- function(vf, file, dateformat = "%Y-%m-%d", eyecodes = c("OD", "OS", "OU"), ...) {
# change date format and eye codes
vf$date <- format(vf$date, dateformat)
vf$eye[vf$eye == "OD"] <- eyecodes[1]
vf$eye[vf$eye == "OS"] <- eyecodes[2]
vf$eye[vf$eye == "OU"] <- eyecodes[3]
write.csv(vf, file, row.names = FALSE, ...)
}
#' @rdname vf
#' @param vf1,vf2 the two visual field data objects to join or merge
#' @return \code{vfjoin} returns a visual field dataset
#' @export
vfjoin <- function(vf1, vf2) {
# join rows of info tables together
vf <- rbind(vf1, vf2)
# check key
if(any(duplicated(data.frame(vf$id, vf$eye, vf$date, vf$time))))
stop("Cannot join visual field data if result yields duplicated keys")
return(vfsort(vf))
}
#' @rdname vf
#' @return \code{vffilter} returns a visual field dataset
#' @export
vffilter <- function(vf, ...) return(vfsort(return(filter(vf, ...))))
#' @rdname vf
#' @param sel it can be two things, an array of indices to select from visual field data
#' or a string with the values `\code{first}` or `\code{last}` indicating that only the
#' first few n visits per subject `\code{id}` and `\code{eye}` are to be selected.
#' Default is `\code{last}`.
#' @param n number of visits to select. Default value is 1, but it is ignored if
#' \code{sel} is an index array
#' @return \code{vfselect} returns a visual field dataset
#' @export
vfselect <- function(vf, sel = "last", n = 1) {
if(is.numeric(sel)) {
if(!is.vector(sel))
stop("wrong format of selection: sel ought to be a number of vector of numbers")
if(min(sel) < 1 || max(sel) > nrow(vf))
stop("index out of bounds")
vf <- vf[unique(sel),]
} else {
if(!(is.atomic(sel) && length(sel)) && !is.character(sel))
stop("wrong type of selection")
if(sel != "last" & sel != "first")
stop("wrong type of selection")
# sort the data increasing or decreasing to select the first or last n visits
if(sel == "last") {
decreasing <- TRUE
} else decreasing <- FALSE
vf <- vfsort(vf, decreasing = decreasing)
# for each unique subject id and eye return the first n visits (or all if there
# are fewer visits than n)
uid <- unique(data.frame(id = vf$id, eye = vf$eye))
vf <- do.call(rbind.data.frame, lapply(1:nrow(uid), function(ii) {
idx <- which(vf$id == uid$id[ii] & vf$eye == uid$eye[ii])
if(length(idx) < n) return(vf[idx,])
else return(vf[idx[1:n],])
}))
return(vfsort(vf))
}
return(vfsort(vf))
}
#' @rdname vf
#' @return \code{gettd} returns a visual field dataset with total deviation values
#' @export
gettd <- function(vf) {
if(!vfisvalid(vf)) stop("cannot compute TD values")
return(getnv()$tdfun(vf))
}
#' @rdname vf
#' @param td total-deviation (TD) values
#' @return \code{gettdp} returns a visual field dataset with total deviation probability values
#' @export
gettdp <- function(td) {
if(!vfisvalid(td)) stop("cannot compute TD probability values")
return(getnv()$tdpfun(td))
}
#' @rdname vf
#' @return \code{getpd} returns a visual field dataset with pattern deviation values
#' @export
getpd <- function(td) {
if(!vfisvalid(td)) stop("cannot compute PD values")
return(getnv()$pdfun(td))
}
#' @rdname vf
#' @param pd pattern-deviation (PD) values
#' @return \code{getpdp} returns a visual field dataset with pattern deviation probability values
#' @export
getpdp <- function(pd) {
if(!vfisvalid(pd)) stop("cannot compute PD probability values")
return(getnv()$pdpfun(pd))
}
#' @rdname vf
#' @return \code{getgh} returns the general height of visual fields tests
#' @export
getgh <- function(td) {
if(!vfisvalid(td)) stop("cannot compute the general height (GH)")
return(getnv()$ghfun(td))
}
#' @rdname vf
#' @return \code{getgl} returns visual fields global indices
#' @export
getgl <- function(vf) {
if(!vfisvalid(vf)) stop("cannot compute global indices")
td <- gettd(vf)
tdp <- gettdp(td)
pd <- getpd(td)
pdp <- getpdp(pd)
gh <- getgh(td)
return(getnv()$glfun(vf, td, pd, tdp, pdp, gh))
}
#' @rdname vf
#' @param g global indices
#' @return \code{getglp} returns probability values of visual fields global indices
#' @export
getglp <- function(g)
return(getnv()$glpfun(g))
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/vf.R
|
#' @rdname vfloaders
#' @title Loaders from perimeters
#' @description Functions to load from commercial perimeters
#' @details The XML loader for the Humphrery Field Analyser (HFA) by Carl Zeiss Meditec
#' is essentially a XML parser that reads in the XML generated with the scientific
#' export license. The DICOMM loader is also a parser to read HFA data generated in a
#' DICOMM file. The loader for the Octopus perimeter by Haag-Streit is a csv reader
#' from files generated with the Eyesuite software. The parser also extracts information
#' on visual field pattern deviation values and normative values. The list that is returned
#' with the \code{loadoctopus} loader contains data frames which are structured with keys so that
#' redundancy is minimized (similar to a relational database). Detailed examples for
#' \code{loadoctopus}: \url{https://rpubs.com/huchzi/645357}
#' @param file file to load (it is a XML extracted with the export license for
#' the HFA loader), a CSV outputed by the Eyesuite software for the Octopus
#' perimeter and a CSV with two columns for the batch HFA loader. The two columns
#' for the batch HFA loader must be named `\code{file}` and `\code{type}` and must
#' have the full file name (file path + name) of each XML file to be loaded and the
#' corresponding patient type, respectively
#' @param type type of patient. It can be `\code{ctr}` (for control or healthy
#' subject-eye) or `\code{pwg}` (for patient with glaucoma) or other
#' @param repeated function to apply if there are repeated values in a particular location
#' @return Visual field data
#' @export
loadhfaxml <- function(file, type = "pwg", repeated = mean) {
vf <- td <- tdp <- pd <- pdp <- g <- gp <- NA
dat <- xmlToList(xmlParse(file))$PATIENT
id <- dat$PATIENT_ID
dob <- as.Date(dat$BIRTH_DATE)
dat <- dat$STUDY # next level
date <- as.Date(dat$VISIT_DATE)
age <- getage(dob, date)
dat <- dat$SERIES # next level
eye <- switch(dat$SITE, "0" = "OS", "1" = "OD")
dat <- dat$FIELD_EXAM # next level
time <- dat$EXAM_TIME
# get the location map
dat <- dat$STATIC_TEST # next level
duration <- dat$EXAM_DURATION
if(dat$FALSE_POSITIVE_METHOD == "1") {
fpr <- as.numeric(dat$FALSE_POSITIVE_PERCENT) / 100
} else if(dat$FALSE_POSITIVE_METHOD == "0") {
fpr <- as.numeric(dat$FALSE_POSITIVES$ERRORS) / as.numeric(dat$FALSE_POSITIVES$TRIALS)
} else {
fpr <- as.numeric(NA)
}
if(dat$FALSE_NEGATIVE_METHOD == "1") {
fnr <- as.numeric(dat$FALSE_NEGATIVE_PERCENT) / 100
} else if(dat$FALSE_NEGATIVE_METHOD == "0") {
fnr <- as.numeric(dat$FALSE_NEGATIVES$ERRORS) / as.numeric(dat$FALSE_NEGATIVES$TRIALS)
} else {
fnr <- as.numeric(NA)
}
fl <- as.numeric(dat$FIXATION_CHECK$ERRORS) / as.numeric(dat$FIXATION_CHECK$TRIALS)
info <- data.frame(id = id, eye = eye, date = date, time = time, age = age,
type = type, fpr = fpr, fnr = fnr, fl = fl, duration = duration,
stringsAsFactors = FALSE)
dat <- dat$THRESHOLD_TEST # next level
nloc <- as.numeric(dat$NUM_THRESHOLD_POINTS)
# return coordinates and value and ensure they are sort as they should
s <- lapply(1:nloc, function(i) {
x <- as.numeric(dat$THRESHOLD_SITE_LIST[[i]]$X)
y <- as.numeric(dat$THRESHOLD_SITE_LIST[[i]]$Y)
idx <- grep("THRESHOLD", names(dat$THRESHOLD_SITE_LIST[[i]]))
val <- do.call(repeated, list(x = as.numeric(dat$THRESHOLD_SITE_LIST[[i]][idx])))
return(list(x, y, val))
})
s <- matrix(unlist(s), nloc, 3, byrow = TRUE)
# if eye = "OS", x is negative
if(eye == "OS") s[,1] <- -s[,1]
s <- s[order(s[,1]),]
s <- s[order(-s[,2]),]
vf <- cbind(info, t(s[,3]))
names(vf)[getvfcols()] <- paste0("l", 1:nloc)
# need to find blindspots locations
dat <- dat$STATPAC # next level
nlocd <- as.numeric(dat$NUM_TOTAL_DEV_VALUE_POINTS)
locd <- lapply(1:nlocd, function(i) {
x <- as.numeric(dat$TOTAL_DEVIATION_VALUE_LIST[[i]]$X)
y <- as.numeric(dat$TOTAL_DEVIATION_VALUE_LIST[[i]]$Y)
return(list(x, y))
})
locd <- matrix(unlist(locd), nlocd, 2, byrow = TRUE)
# if eye = "OS", x is negative
if(eye == "OS") locd[,1] <- -locd[,1]
locd <- locd[order(locd[,1]),]
locd <- locd[order(-locd[,2]),]
bs <- which(!(paste(s[,1], s[,2], sep = "_") %in% paste(locd[,1], locd[,2], sep = "_")))
cutoffs <- c(50, 5, 2, 1, 0.5) / 100 # cutoff lookup for TD and PD probability levels
# total deviation values
if("NUM_TOTAL_DEV_VALUE_POINTS" %in% names(dat)) {
td <- xmldevvals(dat$TOTAL_DEVIATION_VALUE_LIST, as.numeric(dat$NUM_TOTAL_DEV_VALUE_POINTS),
eye, bs)
td <- cbind(info, t(td))
names(td)[getvfcols()] <- paste0("l", 1:nloc)
}
# total deviation probability values
if("NUM_TOTAL_DEV_PROBABILITY_POINTS" %in% names(dat)) {
tdp <- cutoffs[1 + xmldevvals(dat$TOTAL_DEVIATION_PROBABILITY_LIST,
as.numeric(dat$NUM_TOTAL_DEV_PROBABILITY_POINTS), eye, bs)]
tdp <- cbind(info, t(tdp))
names(tdp)[getvfcols()] <- paste0("l", 1:nloc)
}
# pattern deviation values
if("NUM_PATTERN_DEV_VALUE_POINTS" %in% names(dat)) {
pd <- xmldevvals(dat$PATTERN_DEVIATION_VALUE_LIST, as.numeric(dat$NUM_PATTERN_DEV_VALUE_POINTS),
eye, bs)
pd <- cbind(info, t(pd))
names(pd)[getvfcols()] <- paste0("l", 1:nloc)
}
# pattern deviation probability values
if("NUM_PATTERN_DEV_PROBABILITY_POINTS" %in% names(dat)) {
pdp <- cutoffs[1 + xmldevvals(dat$PATTERN_DEVIATION_PROBABILITY_LIST,
as.numeric(dat$NUM_PATTERN_DEV_PROBABILITY_POINTS),
eye, bs)]
pdp <- cbind(info, t(pdp))
names(pdp)[getvfcols()] <- paste0("l", 1:nloc)
}
cutoffs <- c(50, NA, 5, 2, 1, 0.5) / 100 # cutoff lookup for probability levels of global indices
if("GLOBAL_INDICES" %in% names(dat)) {
vals <- vf[,getvfcols()]
if(length(bs) > 1) vals <- vals[,-bs]
g <- data.frame(msens = apply(vals, 1, mean),
ssens = apply(vals, 1, sd),
tmd = as.numeric(dat$GLOBAL_INDICES$MD),
tsd = NA,
pmd = NA,
psd = as.numeric(dat$GLOBAL_INDICES$PSD),
vfi = as.numeric(dat$GLOBAL_INDICES$VFI))
gp <- data.frame(msens = NA,
ssens = NA,
tmd = cutoffs[1 + as.numeric(dat$GLOBAL_INDICES$MD_PROBABILITY)],
tsd = NA,
pmd = NA,
psd = cutoffs[1 + as.numeric(dat$GLOBAL_INDICES$PSD_PROBABILITY)],
vfi = NA)
g <- cbind(info, g)
gp <- cbind(info, gp)
}
return(list(vf = vf, td = td, tdp = tdp, pd = pd, pdp = pdp, g = g, gp = gp))
}
#' @rdname vfloaders
#' @export
loadhfadicom <- function(file, type = "pwg", repeated = mean) {
vf <- td <- tdp <- pd <- pdp <- g <- gp <- NA
# load and arrange data for processing
dat <- readDICOMFile(file)$hdr
dat <- as.data.frame(eval(parse(text = paste0("dat$`", file, "`"))),
stringsAsFactors = FALSE)
# extract the groups we are interested on
groups <- sort(unique(dat$group))
# get test grid
gridtxt <- grep("Test Pattern", dicomelement(dat, groups[2], "CodeMeaning"), value = TRUE)
# depending on the grid, the bs is in different locations
if(grepl("24-2", gridtxt)) bs <- visualFields::locmaps$p24d2$bs
if(grepl("30-2", gridtxt)) bs <- visualFields::locmaps$p30d2$bs
if(grepl("10-2", gridtxt)) bs <- visualFields::locmaps$p10d2$bs
if(grepl("30-1", gridtxt)) bs <- visualFields::locmaps$p30d1$bs
if(grepl("60-4", gridtxt)) bs <- visualFields::locmaps$p60d4$bs
# get id, test date, eye, age, time, and test duration
id <- dicomelement(dat, groups[3], "PatientID")
dob <- as.Date(dicomelement(dat, groups[3], "PatientsBirthDate"), "%Y%m%d")
date <- as.Date(dicomelement(dat, groups[8], "PerformedProcedureStepStartDate"), "%Y%m%d")
age <- getage(dob, date)
eye <- switch(dicomelement(dat, groups[5], "Laterality"), "L" = "OS", "R" = "OD")
time <- round(as.numeric(dicomelement(dat, groups[8], "PerformedProcedureStepStartTime")))
time <- substr(gsub('(?=(?:.{2})+$)', ":", time, perl = TRUE), 2, 9)
duration <- formatDuration(as.numeric(dicomelement(dat, groups[7], "VisualFieldTestDuration")))
# get false positives, false negatives, and fixation losses
if(dicomelement(dat, groups[7], "FalsePositivesEstimateFlag") == "YES") {
fpr <- as.numeric(dicomelement(dat, groups[7], "FalsePositives")) /
as.numeric(dicomelement(dat, groups[7], "PositiveCatchTrials"))
} else {
fpr <- as.numeric(NA)
}
if(dicomelement(dat, groups[7], "FalseNegativesEstimateFlag") == "YES") {
fnr <- as.numeric(dicomelement(dat, groups[7], "FalseNegatives")) /
as.numeric(dicomelement(dat, groups[7], "NegativeCatchTrials"))
} else {
fnr <- as.numeric(NA)
}
fl <- as.numeric(dicomelement(dat, groups[7], "PatientNotProperlyFixatedQuantity")) /
as.numeric(dicomelement(dat, groups[7], "FixationCheckedQuantity"))
info <- data.frame(id = id, eye = eye, date = date, time = time, age = age,
type = type, fpr = fpr, fnr = fnr, fl = fl, duration = duration,
stringsAsFactors = FALSE)
# get sensitivity, TD, PD and probability values
s <- data.frame(
x = as.numeric(dicomelement(dat, groups[7], "VisualFieldTestPointXCoordinate")),
y = as.numeric(dicomelement(dat, groups[7], "VisualFieldTestPointYCoordinate")),
val = as.numeric(dicomelement(dat, groups[7], "SensitivityValue")),
td = as.numeric(dicomelement(dat, groups[7], "AgeCorrectedSensitivityDeviationValue")),
tdp = as.numeric(dicomelement(dat, groups[7], "AgeCorrectedSensitivityDeviationProbabilityValue")),
pd = as.numeric(dicomelement(dat, groups[7], "GeneralizedDefectCorrectedSensitivityDeviationValue")),
pdp = as.numeric(dicomelement(dat, groups[7], "GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue")),
seen = dicomelement(dat, groups[7], "StimulusResults")
)
if(length(bs) > 1) s$td[bs] <- s$tdp[bs] <- s$pd[bs] <- s$pdp[bs] <- NA
s$val[s$seen == "NOT SEEN"] <- -2
s$seen <- NULL
if(eye == "OS") s$x <- -s$y
s <- s[order(s$x),]
s <- s[order(-s$y),]
vf <- cbind(info, t(s$val))
td <- cbind(info, t(s$td))
tdp <- cbind(info, t(s$tdp))
pd <- cbind(info, t(s$pd))
pdp <- cbind(info, t(s$pdp))
names(vf)[getvfcols()] <- names(td)[getvfcols()] <- names(tdp)[getvfcols()] <-
names(pd)[getvfcols()] <- names(pdp)[getvfcols()] <- paste0("l", 1:nrow(s))
cutoffs <- c(50, NA, 5, 2, 1, 0.5) / 100 # cutoff lookup for probability levels of global indices
if("GLOBAL_INDICES" %in% names(dat)) {
vals <- vf[,getvfcols()]
if(length(bs) > 1) vals <- vals[,-bs]
g <- data.frame(msens = apply(vals, 1, mean),
ssens = apply(vals, 1, sd),
tmd = as.numeric(dicomelement(dat, groups[7], "GlobalDeviationFromNormal")),
tsd = NA,
pmd = NA,
psd = as.numeric(dicomelement(dat, groups[7], "LocalizedDeviationfromNormal")),
vfi = NA)
gp <- data.frame(msens = NA,
ssens = NA,
tmd = as.numeric(dicomelement(dat, groups[7], "GlobalDeviationProbability")),
tsd = NA,
pmd = NA,
psd = as.numeric(dicomelement(dat, groups[7], "LocalizedDeviationProbability")),
vfi = NA)
g <- cbind(info, g)
gp <- cbind(info, gp)
}
return(list(vf = vf, td = td, tdp = tdp, pd = pd, pdp = pdp, g = g, gp = gp))
}
#' @rdname vfloaders
#' @param file name of the csv file exported by the eyesuite software
#' @param type type of patient. It can be `\code{ctr}` (for control or healthy
#' subject-eye) or `\code{pwg}` (for patient with glaucoma) or other
#' @param repeated function to apply if there are repeated values in a particular location
#' @param dateFormat format to be used for date. Its default value is \%d.\%m.\%Y
#' @export
loadoctopus <- function(file, type = "pwg", repeated = mean, dateFormat = "%d.%m.%Y") {
# create a list for saving the results
resultList <- list()
# read the csv-file exported by EyeSuite
dat <-
read.csv2(
file,
header = F,
quote = "",
stringsAsFactors = F,
fill = T,
col.names = paste("V", 1:2000, sep = ""),
encoding = "latin1"
)
# rename some columns for better readibility of code
names(dat)[1:6] <- c("id", "lastname", "firstname","dateofbirth","sex","ethnicity")
names(dat)[11:12] <- c("apparatus", "serial_number")
names(dat)[18:24] <- c("eye","pattern","stimulus_size","stimulus_duration","stiumulus_luminance","strategy","tperimetry")
names(dat)[26:31] <- c("testduration","testdate","test_starting_time","reliability_factor","locnum","questions")
names(dat)[32:36] <- c("repetitions","positive_catch_trials","false_positives","negative_catch_trials","false_negatives")
names(dat)[37:41] <- c("notes","sphere","cylinder","axis","bcva")
# recode some variables to factors
dat$eye <- as.character(factor(dat$eye,
levels = c(0, 1, 3),
labels = c("OD", "OS", "OU")))
dat$date <- as.Date(strptime(dat$testdate, format = "%d.%m.%Y"))
dat$dob <- strptime(dat$dateofbirth, format = "%d.%m.%Y")
dat$age <- getage(dat$dob, dat$date)
dat$time <- dat$test_starting_time
dat$type <- dat$note
dat$fpr <- round(dat$false_positives / dat$positive_catch_trials, 3)
dat$fnr <- round(dat$false_negatives / dat$negative_catch_trials, 3)
dat$fl <- dat$repetitions
dat$strategy <- factor(
dat$strategy,
levels = c(0, 1, 2, 3, 4, 6, 11),
labels = c("normal", "dynamic", "2LT/normal", "low vision", "1LT", "TOP", "GATE")
)
dat$pattern <- factor(dat$pattern)
dat$tperimetry <- factor(dat$tperimetry,
levels = c(0, 1),
labels = c("sap", "swap"))
dat <- dat[!is.na(dat$strategy), ]
dat <- dat[!is.na(dat$pattern), ]
dat <- dat[!is.na(dat$tperimetry), ]
if (nrow(dat) < 1) stop("There are no (currently) valid visual fields in this file.")
# create a table with keys for each patient
dat$patient_identifier <- paste0(dat$lastname, dat$firstname, dat$dob, sep = ", ")
dat$id <- as.integer(factor(dat$patient_identifier, levels = unique(dat$patient_identifier), ordered = TRUE))
resultList$patients <- dat[, c("id", "firstname", "lastname", "dob")]
# create a table with keys for each visual field type
dat$vf_identifier <- paste(dat$tperimetry, dat$pattern, dat$locnum, dat$strategy, sep = ", ")
dat$vfID <- as.integer(factor(dat$vf_identifier, levels = unique(dat$vf_identifier), ordered = TRUE))
vf_index <- dat$vfID
resultList$vf_types <- unique(dat[, c("vfID", "tperimetry", "pattern", "locnum", "strategy")])
# function to extract sensitivities for the different loci from one line
extractLocations <- function(tLine) {
# extract number of locations
locnum <- as.integer(tLine[which(names(tLine) == "locnum")])
# extract locations
startCol <- 44
endCol <- startCol + (locnum* 5) - 1
locs <- as.numeric(unlist(tLine[startCol:endCol])) / 10
# create a matrix
locMatrix <-
data.frame(matrix(locs, locnum, 5, byrow = TRUE))
names(locMatrix) <- c("xod", "yod", "sens1", "sens2", "norm")
# switch locmap for left eyes?
if (tLine[which(names(tLine) == "eye")] == "OS")
locMatrix$xod <- -locMatrix$xod
# order locmap
locMatrix <- locMatrix[order(locMatrix$yod, locMatrix$xod, decreasing = c(TRUE, FALSE)), ]
# give each location a key
locMatrix$loc_ID <- 1:nrow(locMatrix)
return(locMatrix)
}
# apply the extractLocations function on each row
locations <- apply(dat, 1, extractLocations)
# extract the locmaps
locmaps <- lapply(locations,
function (mt) { rv <- mt[, c("loc_ID", "xod", "yod")]; rownames(rv) <- NULL; return(rv) }
)
locmaps <- unique(locmaps)
resultList$locmaps <- locmaps
# extract the sensitivities
sens <- lapply(locations,
function (mt) { rv <- mt$sens1; names(rv) <- paste0("l", mt$loc_ID); return(rv) }
)
resultList$sensitivities <-
lapply(unique(vf_index),
function(vf_type) { vf_list <- sens[vf_index == vf_type]; rv <- t(sapply(vf_list, c)); return(rv)}
)
# extract the defects
defects <- lapply(locations,
function (mt) { rv <- mt$sens1 - mt$norm; names(rv) <- paste0("l", mt$loc_ID); return(rv) }
)
resultList$defects <-
lapply(unique(vf_index),
function(vf_type) { vf_list <- defects[vf_index == vf_type]; rv <- t(sapply(vf_list, c)); return(rv)}
)
# extract the norm_values
norm_values <- lapply(locations,
function (mt) { rv <- mt$norm; names(rv) <- paste0("l", mt$loc_ID); return(rv) }
)
resultList$norm_values <-
lapply(unique(vf_index),
function(vf_type) { vf_list <- norm_values[vf_index == vf_type]; rv <- t(sapply(vf_list, c)); return(rv)}
)
# extract other properties
resultList$fields <- dat[, c("id", "eye", "date", "time", "age", "type", "fpr", "fnr", "fl", "vfID")]
# add some functions for convering these data to standard tables of the visual fields package
resultList$create_locmap <-
function(vf_id) {
lmap <- list()
vft <- resultList$vf_types[resultList$vf_types$vfID == vf_id, c("pattern", "locnum")]
lmap$name <- paste(vft$pattern, vft$locnum)
lmap$desc <- "This locmap was automatically created from the csv exported by Eyesuite."
lmap$coord <- resultList$locmap[[vf_id]][, c("xod", "yod")]
names(lmap$coord) <- c("x", "y")
return(lmap)
}
resultList$get_sensitivities <-
function(vf_id) {
rv <- cbind(resultList$fields[resultList$fields$vfID == vf_id, ], resultList$sensitivities[[vf_id]])
# rv$date <- as.Date(rv$date)
}
resultList$get_defects <-
function(vf_id) {
rv <- cbind(resultList$fields[resultList$fields$vfID == vf_id, ], resultList$defects[[vf_id]])
# rv$date <- as.Date(rv$date)
}
resultList$get_norm_values <-
function(vf_id) {
rv <- cbind(resultList$fields[resultList$fields$vfID == vf_id, ], resultList$norm_values[[vf_id]])
# rv$date <- as.Date(rv$date)
}
resultList$patients <- unique(resultList$patients)
return(resultList)
}
#' @rdname vfloaders
#' @export
loadhfaxmlbatch <- function(file, repeated = mean) {
csvforxml <- read.csv(file, stringsAsFactors = FALSE)
vflist <- loadhfaxml(csvforxml[1,1], csvforxml[1,2], repeated = repeated)
for(i in 2:nrow(csvforxml)) {
vflist1 <- loadhfaxml(csvforxml[i,1], csvforxml[i,2], repeated = repeated)
vflist$vf <- vfjoin(vflist$vf, vflist1$vf)
# join only whatever else is available
if(is.data.frame(vflist1$td)) vflist$td <- vfjoin(vflist$td, vflist1$td)
if(is.data.frame(vflist1$tdp)) vflist$tdp <- vfjoin(vflist$tdp, vflist1$tdp)
if(is.data.frame(vflist1$pd)) vflist$pd <- vfjoin(vflist$pd, vflist1$pd)
if(is.data.frame(vflist1$pdp)) vflist$pdp <- vfjoin(vflist$pdp, vflist1$pdp)
if(is.data.frame(vflist1$g)) vflist$g <- vfjoin(vflist$g, vflist1$g)
if(is.data.frame(vflist1$gp)) vflist$gp <- vfjoin(vflist$gp, vflist1$gp)
}
return(vflist)
}
#' @rdname vfloaders
#' @export
loadhfadicombatch <- function(file, repeated = mean) {
csvfordicom <- read.csv(file, stringsAsFactors = FALSE)
vflist <- loadhfadicom(csvfordicom[1,1], csvfordicom[1,2], repeated = repeated)
for(i in 2:nrow(csvfordicom)) {
vflist1 <- loadhfaxml(csvfordicom[i,1], csvfordicom[i,2], repeated = repeated)
vflist$vf <- vfjoin(vflist$vf, vflist1$vf)
# join only whatever else is available
if(is.data.frame(vflist1$td)) vflist$td <- vfjoin(vflist$td, vflist1$td)
if(is.data.frame(vflist1$tdp)) vflist$tdp <- vfjoin(vflist$tdp, vflist1$tdp)
if(is.data.frame(vflist1$pd)) vflist$pd <- vfjoin(vflist$pd, vflist1$pd)
if(is.data.frame(vflist1$pdp)) vflist$pdp <- vfjoin(vflist$pdp, vflist1$pdp)
if(is.data.frame(vflist1$g)) vflist$g <- vfjoin(vflist$g, vflist1$g)
if(is.data.frame(vflist1$gp)) vflist$gp <- vfjoin(vflist$gp, vflist1$gp)
}
return(vflist)
}
###################################################################################
# INTERNAL FUNCTIONS: routines to ease load on XML loader
###################################################################################
# helps parse XML TD and PD values and their corresponding probability levels
#' @noRd
xmldevvals <- function(dat, nloc, eye, bs) {
# return coordinates and value
res <- lapply(1:nloc, function(i) {
x <- as.numeric(dat[[i]][1])
y <- as.numeric(dat[[i]][2])
val <- as.numeric(dat[[i]][3])
return(list(x, y, val))
})
res <- matrix(unlist(res), nloc, 3, byrow = TRUE)
# if eye = "OS", x is negative
if(eye == "OS") res[,1] <- -res[,1]
res <- res[order(res[,1]),]
res <- res[order(-res[,2]),]
res <- res[,3]
if(length(bs) > 0) {
idx <- 1:(nloc + length(bs))
aux <- rep(NA, nloc + length(bs))
aux[idx[-bs]] <- res
res <- aux
}
return(res)
}
# get value from an element of a group in a DICOM scheme
#' @noRd
dicomelement <- function(dat, group, name) {
datgr <- dat[which(dat$group == group),]
return(datgr$value[datgr$name == name])
}
# format duration from seconds to hh:mm:ss
#' @noRd
formatDuration <- function(ss) {
# convert from seconds to hh:mm:ss
hh <- floor(ss / 360)
ss <- ss - 360 * hh
mm <- floor(ss / 60)
ss <- ss - 60 * mm
# convert to strings
hh <- as.character(hh)
mm <- as.character(mm)
ss <- as.character(ss)
if(nchar(hh) == 1) hh <- paste0("0", hh)
if(nchar(mm) == 1) mm <- paste0("0", mm)
if(nchar(ss) == 1) ss <- paste0("0", ss)
return(paste(hh, mm, ss, sep = ":"))
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/vfloaders.R
|
#' @rdname vfplots
#' @title Plots for visual fields data
#' @description Graphical tools for visualization and statistical analysis of
#' visual fields.
#' @details
#' The following functions generate plots using visual fields data
#' \itemize{
#' \item\code{vfgpar} generates simple graphical parameters
#' \item\code{vftess} generates a structure to handle the visual field tessellation.
#' Check section \code{Tesselation in visualFields} below for further details
#' \item\code{vfcolscheme} generates the structures to handle the color scheme
#' Check section \code{Color schemes in visualFields} below for further details
#' \item\code{vfprogcolscheme} generates the structures to handle the color scheme
#' for progression analysis. Check section \code{Color schemes in visualFields}
#' below for further details
#' \item\code{vfplot} plots a single test for visual field data
#' \item\code{vfplotsens} plots a single test for visual field sensitivity data
#' with a grayscale where darker means greater sensitivity loss
#' \item\code{vfplotdev} plots a single test for visual field total or pattern
#' deviation data with probability scales represented in color
#' \item\code{vfplotplr} plots the results of pointwise linear regression for
#' a series of visual fields for an eye from a subject
#' \item\code{vflegoplot} the legoplot shows the differences between the average
#' values of visual field tests taken as baseline and those at the end of
#' follow up
#' \item\code{vflegoplotsens} the legoplot for visual field sensitivity data with
#' a grayscale where darker means greater sensitivity loss
#' \item\code{vflegoplotdev} the legoplot for visual field total or pattern
#' deviation data with probability scales represented in color
#' \item\code{vfsparklines} the sparklines graph shows spark lines for the series
#' of visual field sensitivities, or total or pattern deviation data for each
#' location
#' }
#' @section Structure of graphical parameters:
#' Graphical parameters for visualFields must be a list containing
#' \itemize{
#' \item\code{coord} print x and y coordinates. They could be different from the
#' the real visual field location testing coordinates in complex visual field
#' grids to help readability and improve visualization of statistical results
#' \item\code{tess} tesselation for the visual field maps. Check section
#' \code{Tesselation in visualFields}
#' \item\code{colmap} color map representing the probability scale. Check section
#' \code{Color schemes in visualFields}
#' }
#' A default graphical parameters can be generated with \code{generategpar}
#' @section Tesselation in visualFields:
#' A tesselation in visualFields must be defined with a list containing
#' \itemize{
#' \item\code{xlim}, \item\code{ylim} 2-dimensional vectors containing the minimum
#' and maximum x and y values
#' \item\code{floor} the value to be assinged to any sensitivity value lower than
#' \code{floor}
#' \item\code{tiles} a list of as many tiles defining the tesselation as visual field
#' test locations. Each element of the list is a table with x and y coordinates defining
#' a polygon containing the corresponding test location. Each polygon is thus the tile
#' for each visual field test location
#' \item\code{hull} a table with x and y coordinates defining the outer hull of the
#' tessellation
#' }
#' A default tessellation can be generated with \code{vftess}
#' @section Color schemes in visualFields:
#' A color scheme in visualFields must be defined with a list containing
#' \itemize{
#' \item\code{map} a table mapping probabilities levels with colors defined
#' in hexadecimal base
#' \item\code{fun} a function that takes sensitivity values and deviation
#' probability levels and returns the corresponding color code.
#' }
#' A default color scheme can be generated with \code{vfcolscheme}
#' @param coord print x and y coordinates. Check section
#' \code{Structure of graphical parameters} for details
#' @param tess tesselation for the visual field maps. Check section
#' \code{Tesselation in visualFields} for details
#' @param probs probability scale to use for TD and PD values. It is a numeric vector
#' of probabilities with values in [0,1]. The values 0 and 1 must be included.
#' Although not technically necessary, it would be best if it is the same as for
#' the normative values used
#' @param cols corresponding colors for each of the probability levels
#' @param ltprobs,ltcols color map for progression with the alternative hypothesis
#' lower than (LT)
#' @param gtprobs,gtcols color map for progression with the alternative hypothesis
#' lower than (GT)
#' @param neprobs,necols color map for progression with the alternative hypothesis
#' not equal (NE)
#' @param bprobs,bcols color map for progression with blth alternative
#' hypotheses LT and GT (B for both)
#' @examples
#' # generate a structure with default graphical parameters for the 30-2 map
#' vfgpar(locmaps$p30d2$coord)
#' @return \code{vfgpar} returns a list with graphical parameters to be used for vfplots
#' @export
vfgpar <- function(coord, tess = vftess(coord),
probs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 0.98, 0.99, 0.995, 1),
cols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4),
"#F7F0EB", # within normal limits
colorRampPalette(c("#00FF00", "#008000"))(4)),
floor = 0,
ltprobs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 1),
ltcols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4), "#F7F0EB", "#008000"),
gtprobs = c(0, 0.05, 0.95, 0.98, 0.99, 0.995, 1),
gtcols = c("#000000", "#FF0000", "#F7F0EB", colorRampPalette(c("#00FF00", "#008000"))(4)),
neprobs = c(0, 0.0025, 0.005, 0.01, 0.25, 0.975, 0.99, 0.995, 0.9975, 1),
necols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4), "#F7F0EB",
colorRampPalette(c("#FFFF00", "#FF0000"))(4)),
bprobs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 0.98, 0.99, 0.995, 1),
bcols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4), "#F7F0EB",
colorRampPalette(c("#00FF00", "#008000"))(4)))
return(list(coord = coord, tess = tess, colmap = vfcolscheme(probs, cols, floor),
progcolmap = list(
lt = vfprogcolscheme(ltprobs, ltcols),
gt = vfprogcolscheme(gtprobs, gtcols),
ne = vfprogcolscheme(neprobs, necols),
b = vfprogcolscheme(bprobs, bcols))))
#' @rdname vfplots
#' @param floor Flooring value, typically in dB. Default is 0
#' @param delta Distance over which the boundary should be shifted. See for \code{\link{polyclip}}
#' @examples
#' # generate a structure with default tesselation for the 30-2 map
#' vftess(locmaps$p30d2$coord)
#' @return \code{vftess} returns a list with the \code{xlim}, \code{ylim}, tessellation tiles and an outer hull
#' to be used for vfplots
#' @export
vftess <- function(coord, floor = 0, delta = 3) {
# get and expand the convex hull
hull <- coord[chull(coord),]
hull <- as.data.frame(polyoffset(hull, delta, jointype = "round")[[1]])
# get tiles
tiles <- lapply(tile.list(deldir(coord)), function(tt) data.frame(x = tt$x, y = tt$y))
# and intersect with the convex hull to obtain the
tiles <- lapply(tiles, function(tt) data.frame(polyclip(tt, hull)))
return(list(xlim = c(min(hull$x), max(hull$x)), ylim = c(min(hull$y), max(hull$y)),
floor = floor, tiles = tiles, hull = hull))
}
#' @rdname vfplots
#' @examples
#' # default color scheme
#' vfcolscheme()
#' @return \code{vfcolscheme} returns a list with a lookup table and a function that define the color scheme
#' to be used for vfplots
#' @export
vfcolscheme <- function(probs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 0.98, 0.99, 0.995, 1),
cols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4),
"#F7F0EB", # within normal limits
colorRampPalette(c("#00FF00", "#008000"))(4)),
floor = 0) {
if(any(probs < 0) || any(probs > 1))
stop("probability values must be between 0 and 1")
if(!any(probs == 0) || !any(probs == 1))
stop("probability values must include values 0 and 1")
probs <- sort(probs)
map <- data.frame(probs = probs, cols = cols, stringsAsFactors = FALSE) # fucking hate R defaulting to factors
fun <- as.function(alist(vf = , devp = , {
vf[which(is.na(devp))] <- Inf
devp[which(is.na(devp))] <- Inf # assign infinite to locations to ignore (e.g., blind spot)
cols <- rep(NA, length(devp))
for(i in nrow(map):1) cols[devp <= map$probs[i]] <- map$cols[i]
cols[vf < floor] <- "#000000" # not seen are plotted in black
return(cols)
}))
return(list(map = map, fun = fun))
}
#' @rdname vfplots
#' @examples
#' # default color scheme for progression
#' vfprogcolscheme()
#' @return \code{vfprogcolscheme} returns the default \code{vfcolscheme} to be used for vfplots
#' @export
vfprogcolscheme <- function(probs = c(0, 0.005, 0.01, 0.02, 0.05, 0.95, 1),
cols = c("#000000", colorRampPalette(c("#FF0000", "#FFFF00"))(4),
"#F7F0EB", "#008000")) {
if(any(probs < 0) || any(probs > 1))
stop("probability values must be between 0 and 1")
if(!any(probs == 0) || !any(probs == 1))
stop("probability values must include values 0 and 1")
probs <- sort(probs)
map <- data.frame(probs = probs, cols = cols, stringsAsFactors = FALSE) # fucking hate R defaulting to factors
fun <- as.function(alist(vals = , {
vals[which(is.na(vals))] <- Inf # Assign infinite to locations to ignore (e.g., blind spot)
cols <- rep(NA, length(vals))
for(i in nrow(map):1) cols[vals <= map$probs[i]] <- map$cols[i]
return(cols)
}))
return(list(map = map, fun = fun))
}
#' @rdname vfplots
#' @param vf the visual fields data to plot
#' @param type the type of data to plot: sensitivities (`\code{s}`),
#' total deviation values (`\code{td}`), pattern deviation values (`\code{pd}`),
#' a hybrid plot that shows sensitivity grayscale with TD values and corresponding
#' probability levels (`\code{tds}`), or PD values and corresponding probability
#' levels (`\code{pds}`). Default is `\code{td}`.
#' @param ... other graphical arguments. See \code{\link{plot}}
#' @examples
#' # plot visual field values for the last field in the series for the first
#' # subject in the dataset vfpwgSunyiu24d2
#' # grayscale with sensitivity values
#' vfplot(vfselect(vffilter(vfpwgRetest24d2, id == 1), n = 1), type = "s")
#' # TD values
#' vfplot(vfselect(vffilter(vfpwgRetest24d2, id == 1), n = 1), type = "td")
#' # PD values
#' vfplot(vfselect(vffilter(vfpwgRetest24d2, id == 1), n = 1), type = "pd")
#' # hybrid sensitivities and TD values
#' vfplot(vfselect(vffilter(vfpwgRetest24d2, id == 1), n = 1), type = "tds")
#' # hybrid sensitivities and PD values
#' vfplot(vfselect(vffilter(vfpwgRetest24d2, id == 1), n = 1), type = "pds")
#' @return \code{vfplot} No return value
#' @export
vfplot <- function(vf, type = "td", ...) {
if(nrow(vf) != 1) stop("can plot only 1 visual field at a time")
if(!vfisvalid(vf)) stop("incorrect visual field data structure. Cannot plot")
nv <- getnv() # get normative values
gpar <- getgpar() # get graphical parameters
locs <- getlocini():ncol(vf)
# left or right eye
if(vf$eye == "OS") gpar$tess$xlim <- gpar$tess$xlim[2:1]
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(mar = c(0, 0, 0, 0), ...)
# maximum values for grayscales used in type "s", "tds", and "pds"
maxdb <- nv$agem$model(vf$age)
# for locations in the blind spot, we input the values of the previous locations
maxdb[which(is.na(maxdb))] <- maxdb[which(is.na(maxdb)) - 1]
# dispatch to raw sensitivity (grayscale) plots, TD and PD (color) plots, or the hybrid
# sensitivity with TD and PD plot
if(type == "s") # sensitivities
vfplotsens(gpar, vf[,locs], maxdb, ...)
else { # TD, PD or hybrid plots
if(type %in% c("td", "tds")) {
dev <- gettd(vf)
devp <- gettdp(dev)
} else if(type %in% c("pd", "pds")) {
dev <- getpd(gettd(vf))
devp <- getpdp(dev)
} else stop("wrong type of plot requested. Must be 's', 'td', 'pd', 'td', or 'pds'")
if(type %in% c("td", "pd"))
vfplotdev(gpar, vf[,locs], dev[,locs], devp[,locs], ...)
else
vfplotsdev(gpar, vf[,locs], maxdb, dev[,locs], devp[,locs], ...)
}
}
#' @rdname vfplots
#' @param gpar graphical parameters
#' @param maxval maximum value, typically in dB, for the generation of a grayscale
#' @param digits digits to round values to plot. Default is 0
#' @return \code{vfplotsens} No return value
#' @export
vfplotsens <- function(gpar, vf, maxval, digits = 0, ...) {
# background gray shades
fcol <- (vf - gpar$tess$floor) / (maxval - gpar$tess$floor)
fcol[fcol > 1] <- 1
fcol[fcol < 0] <- 0
# foreground text gray shades
tcol <- rep(0.3, length(vf))
tcol[fcol < 0.5] <- 0.7
# blind spot
fcol[getlocmap()$bs] <- 1
tcol[getlocmap()$bs] <- 0.3
# convert to hexadecimal color
fcol <- rgb(fcol, fcol, fcol)
tcol <- rgb(tcol, tcol, tcol)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE,
axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles))
polygon(gpar$tess$tiles[[i]], col = fcol[i], border = NA)
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
txt <- round(vf, digits)
txt[is.na(vf)] <- ""
txt[vf < gpar$tess$floor] <- paste0("<", gpar$tess$floor)
text(gpar$coord$x, gpar$coord$y, txt, col = tcol, ...)
}
#' @rdname vfplots
#' @param dev deviation (TD or PD) values
#' @param devp deviation (TD or PD) probability values
#' @return \code{vfplotdev} No return value
#' @export
vfplotdev <- function(gpar, vf, dev, devp, digits = 0, ...) {
# background colors and foreground text gray shades
cols <- gpar$colmap$fun(vf, devp)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE,
axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles)) {
tiles <- gpar$tess$tiles[[i]] # get tiles
otiles <- polyoffset(tiles, -0.75, jointype = "round")[[1]] # shrink tiles to plot white region
polygon(tiles, col = cols[i], border = "lightgray") # plot tiles with grayscales
polygon(otiles, col = "white", border = NA) # plot tiles with white background to show text
}
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
txt <- round(dev, digits)
txt[is.na(dev)] <- ""
text(gpar$coord$x, gpar$coord$y, txt, col = rgb(0.3, 0.3, 0.3), ...)
}
#' @rdname vfplots
#' @return \code{vfplotsdev} No return value
#' @export
vfplotsdev <- function(gpar, vf, maxval, dev, devp, digits = 0, ...) {
# background gray shades
fcol <- (vf - gpar$tess$floor) / (maxval - gpar$tess$floor)
fcol[fcol > 1] <- 1
fcol[fcol < 0] <- 0
# foreground text gray shades
tcol <- rep(0.3, length(vf))
tcol[fcol < 0.5] <- 0.7
# blind spot
fcol[getlocmap()$bs] <- 1
tcol[getlocmap()$bs] <- 0.3
# convert to hexadecimal color
fcol <- rgb(fcol, fcol, fcol)
tcol <- rgb(tcol, tcol, tcol)
# background colors and foreground text gray shades
cols <- gpar$colmap$fun(vf, devp)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE,
axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles)) {
tiles <- gpar$tess$tiles[[i]] # get tiles
otiles <- polyoffset(tiles, -0.75, jointype = "round")[[1]] # shrink tiles to plot white region
polygon(tiles, col = cols[i], border = "lightgray") # plot tiles with grayscales
polygon(otiles, col = fcol[i], border = NA) # plot tiles with white background to show text
}
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
txt <- round(dev, digits)
txt[is.na(dev)] <- ""
text(gpar$coord$x, gpar$coord$y, txt, col = tcol, ...)
}
#' @rdname vfplots
#' @param alternative alternative hypothesis used in progression analyses.
#' Allowed values are `\code{LT}` (as in "lower than", default),
#' `\code{GT}` (as in "greater than"), `\code{NE}` (as in "not equal"),
#' and `\code{both}` (both `\code{LT}` and `\code{GT}`)
#' @param xoffs,yoffs offset x and y where to print the slope values. That is,
#' the distance from the center of each Voronoy polygons in degrees of visual angle
#' @param addSpark whether to overlay a sparkline graph in each visual field location.
#' The parameters \code{thr}, \code{width}, and \code{height} are used only if
#' \code{addSpark} is \code{TRUE}. Default value is \code{FALSE}.
#' @examples
#' # plot results from pointwise linear regression for the series of
#' # visual fields for the right eye in the dataset vfpwgSunyiu24d2
#' # with sensitivity values
#' vfplotplr(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "s")
#' # TD values
#' vfplotplr(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "td")
#' # PD values
#' vfplotplr(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "pd")
#' @return \code{vfplotplr} No return value
#' @export
vfplotplr <- function(vf, type = "td", alternative = "LT", xoffs = 0, yoffs = 0,
addSpark = FALSE, thr = 2, width = 4, height = 2, ...) {
res <- plr(vf, type) # if more than 1 ID/eye then it crashes as it should
gpar <- getgpar() # get graphical parameters
# left or right eye
if(vf$eye[1] == "OS") gpar$tess$xlim <- gpar$tess$xlim[2:1]
# format intercept and slope
sl <- format(round(res$sl, 1), nsmall = 1L)
sl[sl == "NA"] <- ""
if(alternative == "LT") {
cols <- getgpar()$progcolmap$lt$fun(res$pval)
} else if(alternative == "GT") {
cols <- getgpar()$progcolmap$gt$fun(res$pval)
} else if(alternative == "NE") {
cols <- getgpar()$progcolmap$ne$fun(res$pval)
} else if(alternative == "both") {
cols <- getgpar()$progcolmap$b$fun(res$pval)
} else stop("wrong alternative")
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(mar = c(0, 0, 0, 0), ...)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE, axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles)) {
tiles <- gpar$tess$tiles[[i]] # get tiles
otiles <- polyoffset(tiles, -0.75, jointype = "round")[[1]] # shrink tiles to plot white region
polygon(tiles, col = cols[i], border = "lightgray") # plot tiles with grayscales
polygon(otiles, col = "white", border = NA) # plot tiles with white background to show text
}
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
text(gpar$coord$x + xoffs, gpar$coord$y + yoffs, sl, col = rgb(0.3, 0.3, 0.3), ...)
if(addSpark) vfsparklines(vf, type, thr, width, height, add = TRUE, ...)
}
#' @rdname vfplots
#' @param grp number of baseline (first) and last visual fields to group.
#' Default is `\code{3}`
#' @examples
#' # legoplot for the series of visual fields for the right eye
#' # of the subject in the dataset vfpwgSunyiu24d2
#' # with sensitivity values
#' vflegoplot(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "s")
#' # TD values
#' vflegoplot(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "td")
#' # PD values
#' vflegoplot(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "pd")
#' @return \code{vflegoplot} No return value
#' @export
vflegoplot <- function(vf, type = "td", grp = 3, ...) {
if(nrow(unique(data.frame(vf$id, vf$eye))) != 1)
stop("all visual fields must belong to the same subject id and eye")
nv <- getnv()
gpar <- getgpar() # get graphical parameters
locs <- getlocini():ncol(vf)
# left or right eye
if(vf$eye[1] == "OS") gpar$tess$xlim <- gpar$tess$xlim[2:1]
vfb <- vfmean(vfselect(vf, sel = "first", n = grp), by = "eye")
vfl <- vfmean(vfselect(vf, sel = "last", n = grp), by = "eye")
if(type == "s") {
maxb <- nv$agem$model(vfb$age)
maxl <- nv$agem$model(vfb$age)
vflegoplotsens(gpar, vfb[,locs], vfl[,locs], maxb, maxl, ...)
} else {
if(type == "td") {
devb <- gettd(vfb)
devbp <- gettdp(devb)
devl <- gettd(vfl)
devlp <- gettdp(devl)
} else if(type == "pd") {
devb <- getpd(gettd(vfb))
devbp <- getpdp(devb)
devl <- getpd(gettd(vfl))
devlp <- getpdp(devl)
} else stop("wrong type of plot requested. Must be 's', 'td', or 'pd'")
vflegoplotdev(gpar,
vfb[,locs], devb[,locs], devbp[,locs],
vfl[,locs], devl[,locs], devlp[,locs], ...)
}
}
#' @rdname vfplots
#' @param vfb baseline visual field data
#' @param vfl last visual field data
#' @param maxb maximum value for the grayscale at baseline visual field data
#' @param maxl maximum value for the grayscale for last visual field data
#' @param crad radius of the circle in the legoplot
#' @return \code{vflegoplotsens} No return value
#' @export
vflegoplotsens <- function(gpar, vfb, vfl, maxb, maxl, crad = 2, digits = 1, ...) {
bs <- getlocmap()$bs
# baseline grayscale
fcolb <- (vfb - gpar$tess$floor) / (maxb - gpar$tess$floor)
fcolb[fcolb > 1] <- 1
fcolb[fcolb < 0] <- 0
fcolb[bs] <- 1 # blind spot
fcolb <- rgb(fcolb, fcolb, fcolb)
# final grayscale
fcol <- (vfl - gpar$tess$floor) / (maxl - gpar$tess$floor)
fcol[fcol > 1] <- 1
fcol[fcol < 0] <- 0
fcol[bs] <- 1
# foreground text gray shades
tcol <- rep(0.3, length(vfl))
tcol[fcol < 0.5] <- 0.7
# convert to hexadecimal color
fcol <- rgb(fcol, fcol, fcol)
tcol <- rgb(tcol, tcol, tcol)
# values to present
txt <- round(vfl - vfb, digits)
# remove blind spot locations
coord <- gpar$coord
if(length(bs) > 0) {
coord <- coord[-bs,]
txt <- txt[-bs]
fcol <- fcol[-bs]
tcol <- tcol[-bs]
}
# plot
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(mar = c(0, 0, 0, 0), ...)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE, axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles))
polygon(gpar$tess$tiles[[i]], border = "lightgray", col = fcolb[i])
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
# draw circles
for(i in 1:nrow(coord))
draw.circle(coord$x[i], coord$y[i], radius = crad, col = fcol[i], lty = 0)
text(coord$x, coord$y, txt, col = tcol, ...)
}
#' @rdname vfplots
#' @param devb baseline visual field (TD or PD) deviation values
#' @param devpb baseline visual field (TD or PD) deviation probability values
#' @param devl last visual field (TD or PD) deviation values
#' @param devpl last visual field (TD or PD) deviation probability values
#' @return \code{vflegoplotdev} No return value
#' @export
vflegoplotdev <- function(gpar, vfb, devb, devpb, vfl, devl, devpl, crad = 2, digits = 1, ...) {
bs <- getlocmap()$bs
# baseline colors
colsb <- gpar$colmap$fun(vfb, devpb)
# final colors
colsl <- gpar$colmap$fun(vfl, devpl)
# values to present
txt <- round(devl - devb, digits)
# text color
tcol <- rep(0.3, length(vfl))
colrgb <- col2rgb(colsl) / 255
tcol[(0.2126 * colrgb[1,] + 0.7152 * colrgb[2,] + 0.0722 * colrgb[3,]) < 0.4] <- 0.7
tcol <- rgb(tcol, tcol, tcol)
# remove blind spot locations
coord <- gpar$coord
if(length(bs) > 0) {
coord <- coord[-bs,]
txt <- txt[-bs]
colsl <- colsl[-bs]
tcol <- tcol[-bs]
}
# plot
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(mar = c(0, 0, 0, 0), ...)
plot(gpar$coord$x, gpar$coord$y, typ = "n", ann = FALSE, axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
for(i in 1:length(gpar$tess$tiles))
polygon(gpar$tess$tiles[[i]], border = "lightgray", col = colsb[i])
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
# draw circles
for(i in 1:nrow(coord))
draw.circle(coord$x[i], coord$y[i], radius = crad, col = colsl[i], lty = 0)
text(coord$x, coord$y, txt, col = tcol, ...)
}
#' @rdname vfplots
#' @param thr threshold used for the median absolute deviation of residuals
#' from simple linear regression. If greater than the threshold, the
#' sparkline for that location is plotted in red and with a thicker line.
#' Default is `\code{2}` (dB)
#' @param width the width of each pointwise sparkline plot. Default is
#' `\code{4}` (degrees of visual angle)
#' @param height the height of each pointwise sparkline plot. Default is
#' `\code{2}` (degrees of visual angle)
#' @param add whether to generate a new plot (`\code{FALSE}`, as default)
#' or to add to an existing figure (`\code{TRUE}`)
#' @examples
#' # sparklines for the series of visual fields for the right eye of
#' # the subject in the dataset vfpwgSunyiu24d2
#' # with sensitivity values
#' vfsparklines(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "s")
#' # TD values
#' vfsparklines(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "td")
#' # PD values
#' vfsparklines(vffilter(vfpwgSunyiu24d2, eye == "OD"), type = "pd")
#' @return \code{vfsparklines} No return value
#' @export
vfsparklines <- function(vf, type = "td", thr = 2, width = 4,
height = 2, add = FALSE, ...) {
if(nrow(unique(data.frame(vf$id, vf$eye))) != 1)
stop("all visual fields must belong to the same subject id and eye")
nv <- getnv()
gpar <- getgpar() # get graphical parameters
locs <- getlocini():ncol(vf)
# left or right eye
x <- as.numeric(vf$date - vf$date[1]) / 365.25 # it should be difference in years from baseline date
if(type == "s") {
y <- vf[,locs]
} else if(type == "td") {
y <- gettd(vf)[,locs]
} else if(type == "pd") {
y <- getpd(gettd(vf))[,locs]
} else stop("wrong type of plot requested. Must be 's', 'td', or 'pd'")
# remove blind spot locations
if(length(getlocmap()$bs) > 0) {
gpar$coord <- gpar$coord[-getlocmap()$bs,]
y <- y[,-getlocmap()$bs]
}
# left or right eye
if(vf$eye[1] == "OS") gpar$tess$xlim <- gpar$tess$xlim[2:1]
xlim <- c(0, max(x))
ylim <- c(min(y), max(y))
suppressWarnings(resmad <- sapply(as.list(y), function(y) mad(lm(y ~ x)$residuals)))
cols <- rep("#4D4D4D", length(resmad))
cols[resmad > thr] <- "#FF0000"
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
if(!add) {
par(mar = c(0, 0, 0, 0), ...)
plot(gpar$coord$x, gpar$coord$y, typ = "n",
ann = FALSE, axes = FALSE, asp = 1,
xlim = gpar$tess$xlim, ylim = gpar$tess$ylim, ...)
# plot polygons
lapply(gpar$tess$tiles, polygon, border = "lightgray", col = "#FFFFFF")
# add blind spot
draw.ellipse(15, -1.5, 2.75, 3.75, col = "lightgray", border = NA)
# outer hull
polygon(gpar$tess$hull, border = "lightgray")
}
# plot the spark lines: for left eyes, handling figure positions is incompatible
# with swapping the min and max x limits in the plot. We need a patch here
if(gpar$tess$xlim[1] < gpar$tess$xlim[2]) {
figs <- cbind(grconvertX(gpar$coord$x - width / 2, to = "ndc"),
grconvertX(gpar$coord$x + width / 2, to = "ndc"),
grconvertY(gpar$coord$y, to = "ndc"),
grconvertY(gpar$coord$y + height, to = "ndc"))
} else {
figs <- cbind(grconvertX(gpar$coord$x + width / 2, to = "ndc"),
grconvertX(gpar$coord$x - width / 2, to = "ndc"),
grconvertY(gpar$coord$y, to = "ndc"),
grconvertY(gpar$coord$y + height, to = "ndc"))
}
for(i in 1:nrow(figs)) {
par(fig = figs[i,], new = TRUE)
plot(x, y[,i], type = "l", xlim = xlim, ylim = ylim, axes = FALSE, col = cols[i], ...)
}
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/vfplots.R
|
#' @rdname sfa
#' @title Single Field Reporting
#' @description Generates of one-page reports of single field analyses
#' @details
#' \itemize{
#' \item\code{vfsfa} saves a pdf with one-page reports of single field analyses
#' \item\code{vfsfashiny} generates interactive one-page reports of single field
#' analyses based on Shiny
#' }
#' @param vf visual field data
#' @param file The pdf file name where to save the one-page reports of single field analysis
#' @param ... other graphical arguments
#' @return No return value
#' @export
vfsfa <- function(vf, file, ...) {
# always sort by ID, eye, date, and time
vf <- vfsort(vf)
defmar <- par("mar") # read default par
defps <- par("ps")
on.exit(par(mar = defmar, ps = defps)) # reset default par on exit, even if the code crashes
pdf(file, width = 8.27, height = 11.69)
par(mar = c(0, 0, 0, 0))
par(ps = 10)
for(i in 1:nrow(vf)) {
scrlist <- mountlayoutsfa()
vfiter <- vfselect(vf, i)
screen(scrlist$title)
filltitle("Single Field Analysis")
screen(scrlist$info)
fillinfosfa(vfiter)
screen(scrlist$vftxt)
text(0.50, 1, "Sensitivities", adj = c(0.5, 1), font = 2)
screen(scrlist$tdtxt)
text(0.50, 1, "Total Deviation", adj = c(0.5, 1), font = 2)
screen(scrlist$pdtxt)
text(0.50, 1, "Pattern Deviation", adj = c(0.5, 1), font = 2)
screen(scrlist$coltxt)
text(0.50, 1, "Color Scale", adj = c(0.5, 1), font = 2)
screen(scrlist$vf)
vfplot(vfiter, "s", mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$td)
vfplot(vfiter, "tds", mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$pd)
vfplot(vfiter, "pd", mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$col)
drawcolscalesfa(getgpar()$colmap$map$probs, getgpar()$colmap$map$cols, ps = 6, ...)
screen(scrlist$foot)
fillfoot()
close.screen(all.screens = TRUE)
}
invisible(dev.off())
}
#' @rdname spa
#' @title Series Progession Analysis
#' @description Generation of one-page reports of series progression analyses
#' \itemize{
#' \item\code{vfspa} saves a pdf with one-page reports of series progression analyses
#' \item\code{vfspashiny} generates interactive one-page reports of series progression
#' analyses based on Shiny
#' }
#' @param vf visual field data
#' @param file The pdf file name where to save the one-page reports of single field analysis
#' @param type Type of data to use. It can be `\code{s}`, `\code{td}`, or
#' `\code{pd}`.
#' @param nperm Number of permutations. Default is 7!
#' @param trunc value for the Truncated Product Method (see reference).
#' Default is 1
#' @param testSlope slope, or slopes, to test as null hypothesis. Default is 0.
#' if a single value, then the same null hypothesis is used for all locations.
#' If a vector of values, then (for \code{plr} and \code{poplr}) each
#' location of the visual field will have a different null hypothesis. The length
#' of testSlope must be 1 or equal to the number of locations to be used in the PLR
#' or PoPLR analysis
#' @param ... other graphical arguments
#' @return No return value
#' @references
#' N. O'Leary, B. C. Chauhan, and P. H. Artes. \emph{Visual field progression in
#' glaucoma: estimating the overall significance of deterioration with permutation
#' analyses of pointwise linear regression (PoPLR)}. Investigative Ophthalmology
#' and Visual Science, 53, 2012
#' @export
vfspa <- function(vf, file, type = "td", nperm = factorial(7),
trunc = 1, testSlope = 0, ...) {
# sort
vf <- vfsort(vf)
# run regression analyses
res <- runregressions(vf, type, nperm, trunc, testSlope)
defmar <- par("mar") # read default par
defps <- par("ps")
on.exit(par(mar = defmar, ps = defps)) # reset default par on exit, even if the code crashes
pdf(file, width = 8.27, height = 11.69)
par(mar = c(0, 0, 0, 0))
par(ps = 10)
for(i in 1:length(res)) {
# for each subject/eye
scrlist <- mountlayoutspa()
vfeye <- vffilter(vf, !!sym("id") == res[[i]]$id, !!sym("eye") == res[[i]]$eye)
screen(scrlist$title)
filltitle("Series Progression Analysis")
screen(scrlist$info)
fillinfospa(res[[i]], type, nperm, trunc, testSlope)
screen(scrlist$sparktxt)
text(0.50, 1, "Sparklines", adj = c(0.5, 1), font = 2)
screen(scrlist$inttxt)
text(0.50, 1, "Baseline", adj = c(0.5, 1), font = 2)
screen(scrlist$sltxt)
text(0.50, 1, "Slopes", adj = c(0.5, 1), font = 2)
screen(scrlist$poplrtxt)
text(0.50, 1, "PoPLR histograms", adj = c(0.5, 1), font = 2)
screen(scrlist$coltxt)
text(0.50, 1, "Color Scale", adj = c(0.5, 1), font = 2)
screen(scrlist$mstxt)
text(0.50, 1, "Mean sensitivity (MS)", adj = c(0.5, 1), font = 2)
screen(scrlist$mdtxt)
text(0.50, 1, "Mean Deviation (MD)", adj = c(0.5, 1), font = 2)
screen(scrlist$ghtxt)
text(0.50, 1, "General Height (GH)", adj = c(0.5, 1), font = 2)
screen(scrlist$int)
vfint <- vfselect(vfeye, sel = 1) # get first
vfint[,getvfcols()] <- plr(vfeye, type = "s")$int
vfplot(vfint, type = "tds", mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$sl)
vfplotplr(vfeye, type, mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$col)
drawcolscalespa(getgpar()$progcolmap$b$map$probs, getgpar()$progcolmap$b$map$cols, ps = 6, ...)
screen(scrlist$spark)
vfsparklines(vfeye, type, mar = c(0, 0, 0, 0), ps = 8)
screen(scrlist$poplrb)
drawhist(res[[i]]$poplr, alternative = "GT")
screen(scrlist$poplrw)
drawhist(res[[i]]$poplr, alternative = "LT")
screen(scrlist$ms)
drawgi(res[[i]]$ms, ylab = "Mean Sensitivity", ps = 8)
screen(scrlist$md)
drawgi(res[[i]]$md, ylab = "Mean Deviation", ps = 8)
screen(scrlist$gh)
drawgi(res[[i]]$gh, ylab = "General Height", ps = 8)
screen(scrlist$foot)
fillfoot()
close.screen(all.screens = TRUE)
}
invisible(dev.off())
}
#' @rdname sfa
#' @export
vfsfashiny <- function(vf, ...) {
# sort
vf <- vfsort(vf)
# user interface
ui <- fluidPage(
useShinyjs(),
titlePanel("Single Field Analysis"),
sidebarLayout(
sidebarPanel(
column(7, selectInput("id", label = "Patient ID", choices = unique(vf$id), selected = vf$id[1])),
column(5, selectInput("eye", label = "Eye", choices = NULL)),
div(dataTableOutput("vfdata"), style = "font-size: 85%")
),
mainPanel(
column(12, align = "center", htmlOutput("info")),
br(),
tabsetPanel(type = "pills",
tabPanel("Sensitivity", plotOutput("s"), plotOutput("dum", height = "60px")),
tabPanel("Total Deviation", plotOutput("td"), plotOutput("ctd", height = "60px")),
tabPanel("Pattern Deviation", plotOutput("pd"), plotOutput("cpd", height = "60px"))
),
column(6, align = "center", actionButton("prevbtn", icon = icon("arrow-left"), "")),
column(6, align = "center", actionButton("nextbtn", icon = icon("arrow-right"), ""))
)
)
)
# server
server <- function(input, output, session) {
vfdata <- vffilter(vf, !!sym("id") == vf$id[1] & !!sym("eye") == vf$eye[1])
vfsel <- reactiveVal(vfselect(vfdata, 1))
####################
# EVENTS
####################
# select Patient ID, update eye options
# if a new Patient ID is selected
observeEvent(input$id, {
vfdata <<- vffilter(vf, !!sym("id") == input$id) # get data from subject
eyes <- sort(unique(vfdata$eye)) # get eyes for this subject
vfdata <<- vffilter(vfdata, !!sym("eye") == eyes[1]) # refine selection get data only for first eye
vfsel(vfselect(vfdata, 1)) # choose first record
output$vfdata <- rendervftable(vfdata, 1)
updateSelectInput(session, "eye", choices = eyes)
})
# if a different eye is selected
observeEvent(input$eye, {
vfdata <<- vffilter(vf, !!sym("id") == input$id & !!sym("eye") == input$eye) # get data for the selected eye
vfsel(vfselect(vfdata, 1)) # choose first record
output$vfdata <- rendervftable(vfdata, 1)
}, ignoreInit = TRUE)
# update data from selected table row
observeEvent(input$vfdata_rows_selected, vfsel(vfselect(vfdata, input$vfdata_rows_selected)), ignoreInit = TRUE)
# previous record
observeEvent(input$prevbtn, {
selected <- input$vfdata_rows_selected
if(selected > 1) selected <- selected - 1
vfsel(vfselect(vfdata, selected))
output$vfdata <- rendervftable(vfdata, selected)
})
# next record
observeEvent(input$nextbtn, {
selected <- input$vfdata_rows_selected
if(selected < nrow(vfdata)) selected <- selected + 1
vfsel(vfselect(vfdata, selected))
output$vfdata <- rendervftable(vfdata, selected)
})
####################
# OUTPUT
####################
# show patient's info and global indices
output$info <- renderText(fillinfosfashiny(vfsel()))
# show the sensitivity plots (if that tab is selected in the UI)
output$s <- renderPlot(vfplot(vfsel(), type = "s"))
# show the total-deviation maps (if that tab is selected in the UI)
output$td <- renderPlot(vfplot(vfsel(), type = "tds"))
# show the pattern-deviation maps (if that tab is selected in the UI)
output$pd <- renderPlot(vfplot(vfsel(), type = "pd"))
# show col scales for TD or PD probability maps
output$ctd <- renderPlot(drawcolscalesfa(getgpar()$colmap$map$probs, getgpar()$colmap$map$cols, ps = 8, ...)) # col scale for TD probability maps
output$cpd <- renderPlot(drawcolscalesfa(getgpar()$colmap$map$probs, getgpar()$colmap$map$cols, ps = 8, ...)) # col scale for TD probability maps. Redundant but necessary
output$dum <- renderPlot({}) # for senstivity values, we need not plot col scale, but need this for consistent formatting
}
shinyApp(ui, server)
}
#' @rdname spa
#' @references
#' N. O'Leary, B. C. Chauhan, and P. H. Artes. \emph{Visual field progression in
#' glaucoma: estimating the overall significance of deterioration with permutation
#' analyses of pointwise linear regression (PoPLR)}. Investigative Ophthalmology
#' and Visual Science, 53, 2012
#' @export
vfspashiny <- function(vf, type = "td", nperm = factorial(7),
trunc = 1, testSlope = 0, ...) {
vf <- vfsort(vf)
# get eyes analyzed
vfeye <- unique(data.frame(id = vf$id, eye = vf$eye, stringsAsFactors = FALSE))
# run regression analyses
res <- runregressions(vf, type, nperm, trunc, testSlope)
ui <- fluidPage(
titlePanel("Series Progression Analysis"),
sidebarLayout(
sidebarPanel(
column(7, selectInput("id", label = "Patient ID", choices = unique(vfeye$id), selected = unique(vfeye$id)[1])),
column(5, selectInput("eye", label = "Eye", choices = NULL)),
br(), br(), br()
),
mainPanel(
column(12, align = "center", htmlOutput("info")),
tabsetPanel(type = "pills",
tabPanel("Baseline", plotOutput("bas"), plotOutput("cbas", height = "60px")),
tabPanel("PLR", plotOutput("plr"), plotOutput("cplr", height = "60px")),
tabPanel("Sparklines", plotOutput("skl")),
tabPanel("PoPLR",
column(width = 12, align = "center",
plotOutput("poplrr", width = "250px", height = "250px"),
plotOutput("poplrl", width = "250px", height = "250px")
)
),
tabPanel("Global trends",
column(width = 4, plotOutput("ms", height = "250px")),
column(width = 4, plotOutput("md", height = "250px")),
column(width = 4, plotOutput("gh", height = "250px"))
)
)
)
)
)
server <- function(input, output, session) {
ressel <- reactiveVal(res[[1]]) # select first subject/eye to show results
vfseries <- reactiveVal(vf[vf$id == res[[1]]$id & vf$eye == res[[1]]$eye,])
####################
# EVENTS
####################
# select Patient ID, update eye options
# if a new Patient ID is selected
# update available eyes for analysis
observeEvent(input$id, {
ressel(res[[which(vfeye$id == input$id & vfeye$eye == vfeye$eye[vfeye$id == input$id][1])]])
updateSelectInput(session, "eye", choices = vfeye$eye[vfeye$id == input$id])
})
# update selected eye for which to show the analysis
observeEvent(input$eye, ressel(res[[which(vfeye$id == input$id & vfeye$eye == input$eye)]]), ignoreInit = TRUE)
# update vfseries
observeEvent(ressel(), vfseries(vf[vf$id == ressel()$id & vf$eye == ressel()$eye,]))
####################
# OUTPUT
####################
# show patient's info and analysis
output$info <- renderText(fillinfospashiny(ressel()))
# show the baseline plot
output$bas <- renderPlot({
vfint <- vfselect(vfseries(), sel = 1) # get first
vfint[,getvfcols()] <- plr(vfseries(), type = "s")$int
vfplot(vfint, type = "tds", mar = c(0, 0, 0, 0))
})
# show the pointwise linear regression plot
output$plr <- renderPlot(vfplotplr(vfseries(), type, mar = c(0, 0, 0, 0)))
# show the sparklines plot
output$skl <- renderPlot(vfsparklines(vfseries(), type, mar = c(0, 0, 0, 0)))
# show the probability scales
output$cbas <- renderPlot(drawcolscalesfa(getgpar()$colmap$map$probs, getgpar()$colmap$map$cols, ps = 8, ...))
output$cplr <- renderPlot(drawcolscalesfa(getgpar()$progcolmap$b$map$probs, getgpar()$progcolmap$b$map$cols, ps = 8, ...))
# PoPLR histograms
output$poplrl <- renderPlot(drawhist(ressel()$poplr, "LT"))
output$poplrr <- renderPlot(drawhist(ressel()$poplr, "GT"))
# global indices progression analysis
output$ms <- renderPlot(drawgi(ressel()$ms, "Mean Sensitivity"))
output$md <- renderPlot(drawgi(ressel()$md, "Mean Deviation"))
output$gh <- renderPlot(drawgi(ressel()$gh, "General Height"))
}
shinyApp(ui, server)
}
########################################################
# internal helper functions for pdf and shiny reports
########################################################
mountlayoutsfa <- function() {
# all the boxes are defined in mm divided by the width and height
# of the page, also in mm
boxtitle <- c(10 / 210, 200 / 210, 267 / 297, 287 / 297)
boxinfo <- c(10 / 210, 65 / 210, 130 / 297, 265 / 297)
boxsenst <- c(65 / 210, 200 / 210, 260 / 297, 265 / 297)
boxsens <- c(65 / 210, 200 / 210, 190 / 297, 263 / 297)
boxtdt <- c(65 / 210, 200 / 210, 182 / 297, 185 / 297)
boxtd <- c(65 / 210, 200 / 210, 110 / 297, 183 / 297)
boxpdt <- c(65 / 210, 200 / 210, 102 / 297, 105 / 297)
boxpd <- c(65 / 210, 200 / 210, 30 / 297, 103 / 297)
boxcolort <- c(65 / 210, 200 / 210, 25 / 297, 28 / 297)
boxcolor <- c(65 / 210, 200 / 210, 15 / 297, 25 / 297)
boxfoot <- c(10 / 210, 200 / 210, 10 / 297, 15 / 297)
scr <- split.screen(rbind(boxtitle, boxinfo, boxsenst, boxsens,
boxtdt, boxtd, boxpdt, boxpd,
boxcolort, boxcolor, boxfoot))
return(list(title = scr[1], info = scr[2],
vftxt = scr[3], vf = scr[4],
tdtxt = scr[5], td = scr[6],
pdtxt = scr[7], pd = scr[8],
coltxt = scr[9], col = scr[10],
foot = scr[11]))
}
#' @noRd
mountlayoutspa <- function() {
# all the boxes are defined in mm divided by the width and height
# of the page, also in mm
boxtitle <- c( 10 / 210, 200 / 210, 267 / 297, 287 / 297)
boxinfo <- c( 20 / 210, 100 / 210, 140 / 297, 265 / 297)
boxinttxt <- c(100 / 210, 200 / 210, 260 / 297, 265 / 297)
boxint <- c(100 / 210, 200 / 210, 182 / 297, 262 / 297)
boxsltxt <- c(100 / 210, 200 / 210, 170 / 297, 175 / 297)
boxsl <- c(100 / 210, 200 / 210, 92 / 297, 172 / 297)
boxcoltxt <- c(100 / 210, 200 / 210, 84 / 297, 87 / 297)
boxcol <- c(100 / 210, 200 / 210, 74 / 297, 82 / 297)
boxsparktxt <- c( 10 / 210, 60 / 210, 130 / 297, 135 / 297)
boxSpark <- c( 10 / 210, 60 / 210, 80 / 297, 125 / 297)
boxpoplrtxt <- c( 60 / 210, 100 / 210, 130 / 297, 135 / 297)
boxpoplrb <- c( 60 / 210, 100 / 210, 103 / 297, 130 / 297)
boxpoplrw <- c( 60 / 210, 100 / 210, 75 / 297, 102 / 297)
boxmstxt <- c( 10 / 210, 70 / 210, 63 / 297, 68 / 297)
boxms <- c( 10 / 210, 70 / 210, 16 / 297, 63 / 297)
boxmdtxt <- c( 75 / 210, 135 / 210, 63 / 297, 68 / 297)
boxmd <- c( 75 / 210, 135 / 210, 16 / 297, 63 / 297)
boxghtxt <- c(140 / 210, 200 / 210, 63 / 297, 68 / 297)
boxgh <- c(140 / 210, 200 / 210, 16 / 297, 63 / 297)
boxfoot <- c( 10 / 210, 200 / 210, 10 / 297, 15 / 297)
scr <- split.screen(rbind(boxtitle, boxinfo, boxinttxt, boxint, boxsltxt, boxsl,
boxcoltxt, boxcol, boxsparktxt, boxSpark,
boxpoplrtxt, boxpoplrb, boxpoplrw,
boxmstxt, boxms, boxmdtxt, boxmd, boxghtxt, boxgh,
boxfoot))
return(list(title = scr[1], info = scr[2],
inttxt = scr[3], int = scr[4],
sltxt = scr[5], sl = scr[6],
coltxt = scr[7], col = scr[8],
sparktxt = scr[9], spark = scr[10],
poplrtxt = scr[11], poplrb = scr[12], poplrw = scr[13],
mstxt = scr[14], ms = scr[15],
mdtxt = scr[16], md = scr[17],
ghtxt = scr[18], gh = scr[19],
foot = scr[20]))
}
#' @noRd
filltitle <- function(txt) {
nvinfo <- getnv()$info
text(0.50, 1.00, txt, adj = c(0.5, 1), cex = 1.5, font = 2)
if(isnotempty(nvinfo$perimetry)) perim_txt <- nvinfo$perimetry
if(isnotempty(nvinfo$perimetry)) perim_txt <- paste(perim_txt, "with the", nvinfo$strategy, "strategy")
if(isnotempty(perim_txt)) text(0.01, 0.60, toTitleCase(perim_txt), adj = c(0, 1))
if(isnotempty(nvinfo$size)) { # if there is info about size
stim_txt <- paste("Stimulus size:", nvinfo$size)
if(is.numeric(nvinfo$size)) # if numeric assume that value is in degrees
stim_txt <- paste(stim_txt, "deg.")
text(0.01, 0.10, stim_txt, adj = c(0, 0))
}
if(isnotempty(nvinfo$name)) text(0.99, 0.10, nvinfo$name, adj = c(1, 0))
segments(0, 0, 1, 0)
}
#' @noRd
fillinfosfa <- function(vf) {
g <- getgl(vf)
gp <- getglp(g)
# format global indices
ms <- ifelse(isnotempty(g$msens), paste(round(g$msens, 1), "dB"), "")
msp <- ifelse(isnotempty(gp$msens), paste0("(p < ", gp$msens, ")"), "")
md <- ifelse(isnotempty(g$tmd), paste(round(g$tmd, 1), "dB"), "")
mdp <- ifelse(isnotempty(gp$tmd), paste0("(p < ", gp$tmd, ")"), "")
psd <- ifelse(isnotempty(g$psd), paste(round(g$psd, 1), "dB"), "")
psdp <- ifelse(isnotempty(gp$psd), paste0("(p < ", gp$psd, ")"), "")
vfi <- ifelse(isnotempty(g$vfi), paste(round(g$vfi, 1), "%"), "")
vfip <- ifelse(isnotempty(gp$vfi), paste0("(p < ", gp$vfi, ")"), "")
# format reliability indices
fpr <- ifelse(isnotempty(vf$fpr), paste(round(100 * vf$fpr), "%"), "")
fnr <- ifelse(isnotempty(vf$fnr), paste(round(100 * vf$fnr), "%"), "")
fl <- ifelse(isnotempty(vf$fl), paste(round(100 * vf$fl), "%"), "")
# print in the pdf file
rect(0, 0, 1, 1, col = "#F6F6F6", border = NA)
text(0.50, 0.98, "Patient Information", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.90, "Patient ID:\nEye:\nAge:\n\nDate:\nTime:", adj = c(0, 1), font = 2)
text(0.95, 0.90, paste0(vf$id, "\n", vf$eye, "\n", vf$age, "\n\n", vf$date, "\n", vf$time), adj = c(1, 1))
segments(0.05, 0.66, 0.95, 0.66, col = "#BBBBBB")
text(0.50, 0.64, "Global indices", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.56, "MS:\n\nMD:\n\nPSD:\n\nVFI:", adj = c(0, 1))
text(0.52, 0.56, paste0(ms, "\n\n", md, "\n\n", psd, "\n\n", vfi), adj = c(1, 1))
text(0.95, 0.56, paste0(msp, "\n\n", mdp, "\n\n", psdp, "\n\n", vfip), adj = c(1, 1))
segments(0.05, 0.30, 0.95, 0.30, col = "#BBBBBB")
text(0.50, 0.28, "Reliability indices", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.20, "False Positives:\n\nFalse Negatives:\n\nFixation Losses:", adj = c(0, 1))
text(0.80, 0.20, paste0(fpr, "\n\n", fnr, "\n\n", fl), adj = c(1, 1))
}
#' @noRd
fillinfospa <- function(res, type, nperm, trunc, testSlope) {
# format global regression results
# mean sensitivity
msint <- format(round(res$ms$int, 1), nsmall = 1)
mssl <- format(round(res$ms$sl, 2), nsmall = 2)
msp <- format(round(res$ms$pval, 3), nsmall = 1)
idxp <- which(mssl >= 0)
idxn <- which(mssl < 0)
mssl[idxp] <- paste("+", mssl[idxp])
mssl[idxn] <- paste("-", substr(mssl[idxn], 2, nchar(mssl[idxn])))
# mean deviation
mdint <- format(round(res$md$int, 1), nsmall = 1)
mdsl <- format(round(res$md$sl, 2), nsmall = 2)
mdp <- format(round(res$md$pval, 3), nsmall = 1)
idxp <- which(mdsl >= 0)
idxn <- which(mdsl < 0)
mdsl[idxp] <- paste("+", mdsl[idxp])
mdsl[idxn] <- paste("-", substr(mdsl[idxn], 2, nchar(mdsl[idxn])))
# general height
ghint <- format(round(res$gh$int, 1), nsmall = 1)
ghsl <- format(round(res$gh$sl, 2), nsmall = 2)
ghp <- format(round(res$gh$pval, 3), nsmall = 1)
idxp <- which(ghsl >= 0)
idxn <- which(ghsl < 0)
ghsl[idxp] <- paste("+", ghsl[idxp])
ghsl[idxn] <- paste("-", substr(ghsl[idxn], 2, nchar(ghsl[idxn])))
# format PoPLR results
if(type == "s") poplrtype <- "Sensitivity"
if(type == "td") poplrtype <- "Total Deviation"
if(type == "pd") poplrtype <- "Pattern Deviation"
sl <- format(round(res$poplr$csl, 1), nsmall = 1)
pl <- format(round(res$poplr$cslp, 3), nsmall = 1)
sr <- format(round(res$poplr$csr, 1), nsmall = 1)
pr <- format(round(res$poplr$csrp, 3), nsmall = 1)
# print in the pdf file
rect(0, 0, 1, 1, col = "#F6F6F6", border = NA)
text(0.50, 0.96, "Patient Information", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.88, "Patient ID:\nEye:\nDate from:\nDate to:\nAge:", adj = c(0, 1), font = 2)
text(0.95, 0.88, paste0(res$id, "\n", res$eye, "\n", res$dateStart, "\n", res$dateEnd,
"\nfrom ", res$ageStart, " to ", res$ageEnd), adj = c(1, 1))
segments(0.02, 0.68, 0.98, 0.68, col = "#BBBBBB")
text(0.50, 0.64, "Global indices", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.56, "MS:\nMD:\nGH:", adj = c(0, 1), font = 2)
text(0.95, 0.56, paste0(msint, " ", mssl, " y (p < ", msp, ")\n",
mdint, " ", mdsl, " y (p < ", mdp, ")\n",
ghint, " ", ghsl, " y (p < ", ghp, ")"), adj = c(1, 1))
segments(0.02, 0.42, 0.98, 0.42, col = "#BBBBBB")
text(0.50, 0.38, "PoPLR slope analysis", adj = c(0.5, 1), cex = 1.2, font = 2)
text(0.05, 0.30, paste0("data type:\npermutations:\ntruncation:\ntest slope:\n\nS (right):\nS (left):"),
adj = c(0, 1), font = 2)
text(0.95, 0.30, paste0(poplrtype, "\n", nperm, "\n", trunc, "\n", testSlope, "\n\n",
sr, " (p < ", pr, ")\n", sl, " (p < ", pl, ")"), adj = c(1, 1))
}
#' @noRd
drawcolscalesfa <- function(probs, cols, ...) {
if(!(0 %in% probs)) {
probs <- c(0, probs)
cols <- c("#000000", cols)
}
colrgb <- col2rgb(cols) / 255
txtcol <- rep("#000000", length(probs))
txtcol[(0.2126 * colrgb[1,]
+ 0.7152 * colrgb[2,]
+ 0.0722 * colrgb[3,]) < 0.4] <- "#FFFFFF"
pol <- NULL
y <- c(0.5, 0.5, -0.5, -0.5)
xini <- (26 - length(probs)) / 2
xend <- 25 - xini
pol[1] <- list(data.frame(x = c(xini, xini + 1, xini + 1, xini), y = y))
for(i in 2:length(probs)) {
xl <- pol[[i-1]]$x[2]
xu <- xl + 1
pol[i] <- list(data.frame(x = c(xl, xu, xu, xl), y = y))
}
x <- xini + 1:length(probs)
y <- rep(0, length(probs))
par(mar = c(0, 0, 0, 0), ...)
plot(x, y, typ = "n", ann = FALSE, axes = FALSE,
xlim = c(1, 25), ylim = c(-0.25, 0.25), asp = 1)
for(i in 1:length(x)) polygon(pol[[i]], border = NA, col = cols[i])
text(x - diff(x)[1] / 2, y, probs, col = txtcol)
}
#' @noRd
drawcolscalespa <- function(probs, cols, ...) {
if(!(0 %in% probs)) {
probs <- c(0, probs)
cols <- c("#000000", cols)
}
colrgb <- col2rgb(cols) / 255
txtcol <- rep("#000000", length(probs))
txtcol[(0.2126 * colrgb[1,]
+ 0.7152 * colrgb[2,]
+ 0.0722 * colrgb[3,]) < 0.4] <- "#FFFFFF"
pol <- NULL
y <- c(0.5, 0.5, -0.5, -0.5)
xini <- (17 - length(probs)) / 2
xend <- 16 - xini
pol[1] <- list(data.frame(x = c(xini, xini + 1, xini + 1, xini), y = y))
for(i in 2:length(probs)) {
xl <- pol[[i-1]]$x[2]
xu <- xl + 1
pol[i] <- list(data.frame(x = c(xl, xu, xu, xl), y = y))
}
x <- xini + 1:length(probs)
y <- rep(0, length(probs))
plot(x, y, typ = "n", ann = FALSE, axes = FALSE,
xlim = c(1, 17), ylim = c(-0.25, 0.25), asp = 1)
for(i in 1:length(x)) polygon(pol[[i]], border = NA, col = cols[i])
text(x - diff(x)[1] / 2, y, probs, col = txtcol)
}
#' @noRd
fillfoot <- function() {
box()
vf_txt <- paste0("visualFields version ", packageVersion("visualFields"),
" (", packageDate("visualFields"), ")")
r_txt <- version$version.string
text(0.01, 0.50, vf_txt, adj = c(0, 0.5))
text(0.99, 0.50, r_txt, adj = c(1, 0.5))
}
#' @noRd
isnotempty <- function(field) {
if(is.null(field) || is.na(field) || length(field) != 1 || field == "") return(FALSE)
return(TRUE)
}
# Scripts for series progression analysis
#' @noRd
runregressions <- function(vf, type, nperm, trunc, testSlope) {
# run all global and PoPLR analyses a priori so that it does not take too long
# when we move to see the analyses for different eyes
uid <- unique(data.frame(id = vf$id, eye = vf$eye))
print("running PoPLR analyses. Please be patient, it is a slow process")
pb <- txtProgressBar(min = 0, max = nrow(uid), initial = 0, style = 3) # show text progress bar
res <- lapply(1:nrow(uid), function(i) {
vfiter <- vffilter(vf, !!sym("id") == uid$id[i], !!sym("eye") == uid$eye[i])
g <- getgl(vfiter)
ms <- glr(g, type = "ms", testSlope = testSlope)
md <- glr(g, type = "md", testSlope = testSlope)
gh <- glr(g, type = "gh", testSlope = testSlope)
res <- poplr(vfiter, type = type, nperm = nperm, trunc = trunc, testSlope = testSlope)
setTxtProgressBar(pb, i)
return(list(id = uid$id[i], eye = as.character(uid$eye[i]),
dateStart = vfiter$date[1], dateEnd = vfiter$date[res$nvisits],
ageStart = vfiter$age[1], ageEnd = vfiter$age[res$nvisits],
poplr = list(int = res$int, sl = res$sl, pval = res$pval,
csl = res$csl, cslp = res$cslp, cslall = res$cstats$cslall,
csr = res$csr, csrp = res$csrp, csrall = res$cstats$csrall),
ms = ms, md = md, gh = gh))
})
close(pb)
return(res)
}
#' @noRd
drawgi <- function(res, ylab, ...) {
xlim <- c(res$years[1], res$years[length(res$years)])
if(res$sl <= 0) {
ylim <- c(max(res$pred) - 5, max(res$pred) + 3)
} else {
ylim <- c(min(res$pred) - 3, min(res$pred) + 5)
}
firstTick <- ceiling(ylim[1])
tickMarks <- c(firstTick, firstTick + 2, firstTick + 4, firstTick + 6)
tooLarge <- res$years[res$data > ylim[2]]
tooSmall <- res$years[res$data < ylim[1]]
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(plt = c( 0.3, 1, 0.3, 1 ), mgp = c( 1.5, 0.5, 0 ), ...)
plot(res$years, res$data, type = "n", axes = FALSE, ann = FALSE, xlim = xlim, ylim = ylim, ...)
axis(1, las = 1, tcl = -0.3, lwd = 0.5, lwd.ticks = 0.5)
axis(2, las = 1, tcl = -0.3, lwd = 0.5, lwd.ticks = 0.5, at = tickMarks)
years <- res$years
dat <- res$data
years[dat < ylim[1] | dat > ylim[2]] <- NA
dat[dat < ylim[1] | dat > ylim[2]] <- NA
points(years, dat, pch = 19, col = "gray50", ...)
lines(res$years, res$pred, lwd = 3, ...)
if(length(tooSmall) > 0) points(tooSmall, ylim[1] * rep(1, length(tooSmall)), pch = 10, col = "red", ...)
if(length(tooLarge) > 0) points(tooLarge, ylim[2] * rep(1, length(tooLarge)), pch = 10, col = "red", ...)
title(xlab = "years")
title(ylab = ylab)
}
#' @noRd
drawhist <- function(res, alternative, ...) {
maxsp <- 5
sep <- 1 / 10 # separation between bins in a tenth so we have 100 bins
if(alternative == "LT") {
coltxt <- "#FF0000"
colhist <- "#FF000080"
s <- res$csl
sp <- res$cslall
} else {
coltxt <- "#008000"
colhist <- "#00800040"
s <- res$csr
sp <- res$csrall
}
s <- s / length(res$pval) # average by the number of locations here
sp <- sp / length(res$pval)
sp[sp > maxsp] <- maxsp
if(s > maxsp) s <- maxsp
breaks <- seq(0, maxsp, by = sep)
ymax <- max(hist(sp, breaks = breaks, plot = FALSE)$density)
xlim <- c(0, maxsp)
ylim <- c(0, 1.1 * ymax)
defpar <- par(no.readonly = TRUE) # read default par
on.exit(par(defpar)) # reset default par on exit, even if the code crashes
par(plt = c(0, 1, 0.4, 1), mgp = c(0.6, 0.1, 0), ...)
hist(sp, breaks = breaks, freq = FALSE, main = "", xlim = xlim, ylim = ylim,
xlab = "", ylab = "", lty = 0, col = colhist, axes = FALSE, ann = FALSE)
axis(1, at = 0:maxsp, tcl = -0.2, lwd = 0.5, lwd.ticks = 0.5)
title(xlab = "S / n")
lines(c(s, s), 0.8 * c(0, ymax), col = coltxt)
points(s, 0.8 * ymax, pch = 21, col = coltxt, bg = coltxt)
if(alternative == "LT") text(x = maxsp, y = ymax, label = "S (left)", adj = c(1, 1), font = 2, ...)
if(alternative == "GT") text(x = maxsp, y = ymax, label = "S (right)", adj = c(1, 1), font = 2, ...)
}
#' @noRd
fillinfosfashiny <- function(vfsel) {
# fill information table
infoTab <- matrix(" ", 4, 13) # leave large space between blocks
cssTab <- matrix("", 4, 13)
infoTab[,1] <- c("<b>Patient ID:</b>", "<b>Eye:</b>", "<b>Date:</b>", "<b>Time:</b>")
infoTab[,2] <- " " # leave small space between columns
infoTab[,3] <- c(vfsel$id, vfsel$eye, format(vfsel$date), vfsel$time)
# global indices
infoTab[,5] <- c("<b>MS:</b>", "<b>MD:</b>", "<b>PSD:</b>", "<b>VFI:</b>")
infoTab[,6] <- " " # leave small space between columns
g <- getgl(vfsel)
gp <- getglp(g)
ms <- paste(round(g$msens), " dB")
md <- paste(round(g$tmd), " dB")
psd <- paste(round(g$psd), " dB")
vfi <- paste(round(g$vfi), " %")
msp <- paste0("(p < ", gp$msens, ")")
mdp <- paste0("(p < ", gp$tmd, ")")
psdp <- paste0("(p < ", gp$psd, ")")
vfip <- paste0("(p < ", gp$vfi, ")")
infoTab[,7] <- c(ms, md, psd, vfi)
infoTab[,8] <- " " # leave small space between columns
infoTab[,9] <- c(msp, mdp, psdp, vfip)
# check if text color needs to change (if p-value < 0.05)
cssTab[c(gp$msens, gp$tmd, gp$psd, gp$vfi) < 0.05, 7:9] <- "color: #fb0000; font-weight: 700;"
# false positive and negative rates and fixation losses
fpr <- paste(round(100 * vfsel$fpr), "%")
fnr <- paste(round(100 * vfsel$fnr), "%")
fl <- paste(round(100 * vfsel$fl), "%")
infoTab[,11] <- c("<b>Test duration:</b>", "<b>False positives:</b>", "<b>False negatives:</b>", "<b>Fixation losses:</b>")
infoTab[,12] <- " " # leave small space between columns
infoTab[,13] <- c(vfsel$duration, fpr, fnr, fl)
# check if text color needs to change (if FPR, FNR, FL are greater than 15%)
cssTab[c(0, vfsel$fpr, vfsel$fnr, vfsel$fl) > 0.15, 13] <- "color: #fb0000; font-weight: 700;"
return(htmlTable(infoTab, css.cell = cssTab,
css.table = "margin-top: 0em; margin-bottom: 1em;",
align = c("l", "c", "r", "c", "l", "c", "r", "c", "r", "c", "l", "c", "r"),
cgroup = c("Patient information", "", "Global indices", "", "Reliability indices"),
n.cgroup = c(3, 1, 5, 1, 3),
col.rgroup = c("none", "#F7F7F7")))
}
#' @noRd
rendervftable <- function(vfdata, selected)
renderDataTable(vfdata[,c("date", "time")], server = FALSE,
rownames = FALSE, colnames = c("Test date", "Test time"),
selection = list(mode = "single", selected = selected),
options = list(paging = FALSE, searching = FALSE))
#' @noRd
fillinfospashiny <- function(selres) {
# fill information table
infoTab <- matrix(" ", 4, 15) # leave large space between blocks
cssTab <- matrix("", 4, 15)
infoTab[,1] <- c("<b>Patient ID:</b>", "<b>Eye:</b>", "<b>From:</b>", "<b>To:</b>")
infoTab[,2] <- " " # leave small space between columns
infoTab[,3] <- c(selres$id, selres$eye, format(selres$dateStart), format(selres$dateEnd))
# progression global indices
infoTab[,5] <- c("<b>MS:</b>", "<b>MD:</b>", "<b>PSD:</b>", "")
infoTab[,6] <- " " # leave small space between columns
ms <- paste(round(selres$ms$sl, 2), "dB / y")
md <- paste(round(selres$md$sl, 2), "dB / y")
gh <- paste(round(selres$gh$sl, 2), "dB / y")
msp <- paste0("(p < ", round(selres$ms$pval, 3), ")")
mdp <- paste0("(p < ", round(selres$md$pval, 3), ")")
ghp <- paste0("(p < ", round(selres$gh$pval, 3), ")")
infoTab[,7] <- c(ms, md, gh, "")
infoTab[,8] <- " " # leave small space between columns
infoTab[,9] <- c(msp, mdp, ghp, "")
cssTab[c(selres$ms$pval, selres$md$pval, selres$gh$pval, 1) < 0.05, 7:9] <- "color: #fb0000; font-weight: 700;"
# progression PoPLR
csl <- round(selres$poplr$csl)
csr <- round(selres$poplr$csr)
cslp <- paste0("(p < ", round(selres$poplr$cslp, 3), ")")
csrp <- paste0("(p < ", round(selres$poplr$csrp, 3), ")")
infoTab[,11] <- c("<b>S left:</b>", "<b>S right:</b>", "", "")
infoTab[,12] <- " " # leave small space between columns
infoTab[,13] <- c(csl, csr, "", "")
infoTab[,14] <- " " # leave small space between columns
infoTab[,15] <- c(cslp, csrp, "", "")
cssTab[c(selres$poplr$cslp, 1, 1, 1) < 0.05, 12:15] <- "color: #fb0000; font-weight: 700;"
cssTab[c(1, selres$poplr$csrp, 1, 1) < 0.05, 12:15] <- "color: #228b22; font-weight: 700;"
return(htmlTable(infoTab, css.cell = cssTab,
css.table = "margin-top: 0em; margin-bottom: 1em;",
align = c("l", "c", "r", "c", "l", "c", "r", "c", "r", "c", "l", "c", "r", "c", "r"),
cgroup = c("Patient information", "", "Global slopes", "", "PoPLR"),
n.cgroup = c(3, 1, 5, 1, 5),
col.rgroup = c("none", "#F7F7F7")))
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/vfreports.R
|
#' @rdname getage
#' @title Calculates age
#' @description Computes ages at specific dates
#' @param dob date(s) of birth
#' @param date date(s) for which to calculate age
#' @return \code{getage} returns the age from the date of birth and a certain date
#' @examples
#' getage("1977-01-31", "2014-01-30")
#' @export
getage <- function(dob, date) {
dob <- as.POSIXlt(dob)
date <- as.POSIXlt(date)
age <- date$year - dob$year
# if month of DoB has not been reached yet, then a year younger
idx <- which(date$mon < dob$mon)
if(length(idx) > 0) age[idx] <- age[idx] - 1
# if same month as DoB but day has not been reached, then a year younger
idx <- which(date$mon == dob$mon & date$mday < dob$mday)
if(length(idx) > 0) age[idx] <- age[idx] - 1
return(age)
}
#' @rdname vfstats
#' @title Statistical analyses for visual fields data
#' @description
#' \itemize{
#' \item\code{vfaggregate} computes summary statistics of visual field data
#' \item\code{vfmean} computes the mean statistics of visual field data. It is
#' a wrapper for vfaggregate but only to compute means
#' \item\code{vfretestdist} computes the conditional distribution from test-retest data
#' }
#' @details
#' \itemize{
#' \item\code{vfaggregate} this is a restricted version of \code{\link{aggregate}}
#' that only allows to use part of the key hierarchically, and operates on all
#' data frames of the \code{VisualField} object. The restriction is that only
#' aggregates that are allowed are `\code{newkey = c("id", "eye")}` and
#' `\code{newkey = c("id", "eye", "date")}`. It returns the aggregated value for all
#' numeric columns grouped and ordered by the new key (id and eye, or id, eye,
#' and date). If the aggregate grouping is by \code{eye} and the function, then
#' the \code{date} returned is the average.
#' }
#' @param by aggregate by \code{date}, that is by id, eye, and date (default) or by
#' \code{eye}, that is by id and eye
#' @param fun a function to compute the summary statistics which can be applied to
#' all data subsets. The default is `\code{mean}`
#' @return \code{vfaggregate} and \code{vfmean} return a vf data frame with aggregate values
#' @examples
#' # aggregate by date
#' vfaggregate(vfpwgRetest24d2, by = "date") # compute the mean
#' vfaggregate(vfpwgRetest24d2, by = "date", fun = sd) # compute standard deviation
#' # aggregate by eye
#' vfaggregate(vfpwgRetest24d2, by = "eye") # compute the mean
#' vfaggregate(vfpwgRetest24d2, by = "eye", fun = sd) # compute standard deviation
#' @export
vfaggregate <- function(vf, by = "date", fun = mean, ...) {
if(by == "eye") {
form <- . ~ id + eye
nkey <- 1:2
} else if(by == "date") {
form <- . ~ id + eye + date
nkey <- 1:3
} else stop("type of summary statistics not allowed")
# we need to do different things depending on what type of data we are dealing with
# find which column of the non-key columns is numeric, which is character
cnames <- names(vf)
cclass <- sapply(cnames[5:length(cnames)], function(col) class(vf[,col]))
numer <- which(cclass == "numeric" | cclass == "integer") + 4 # numeric columns
other <- setdiff(5:length(cclass), numer) # all other columns
# aggregate numeric columns
vfa <- aggregate(form, data = vf[,c(nkey, numer)], fun, na.action = na.pass, ...)
# time is no longer relevant and we set it to midnight
vfa$time <- "00:00:00"
# add column for date. if aggregate is for eye and fun is mean then find average
if(by == "eye") {
vfa$date <- as.Date(sapply(1:nrow(vfa), function(i) {
return(as.character(mean.Date(vf$date[vf$id == vfa$id[i] & vf$eye == vfa$eye[i]])))
}))
}
# sort
vfa <- vfa[order(vfa$id, vfa$eye, vfa$date),]
# add other columns. If they have the same value the new key, then keep
# that value otherwise, blank
for(col in cnames[other]) {
vfa[,col] <- sapply(1:nrow(vfa), function(i) {
if(by == "eye") idx <- which(vf$id == vfa$id[i] & vf$eye == vfa$eye[i])
else idx <- which(vf$id == vfa$id[i] & vf$eye == vfa$eye[i] & vf$date == vfa$date[i]) # by == "date"
if(length(unique(vf[idx,col])) == 1) return(vf[idx[1],col])
return(NA)
})
}
# return the aggregated visual field data with columns in the correct order
return(vfa[,cnames])
}
#' @rdname vfstats
#' @examples
#' # mean by date
#' vfmean(vfpwgRetest24d2, by = "date")
#' # mean by eye
#' vfmean(vfpwgRetest24d2, by = "eye")
#' @export
vfmean <- function(vf, by = "date", ...) return(vfaggregate(vf, by, fun = mean, ...))
#' @rdname vfstats
#' @param vf a table with visual fields data. Data is rounded, which leaves
#' sensitivity data unchanged, but it is necessary for the nature of the
#' algorithm if the data passed are TD or PD values or summary stats such as
#' averages. Beware of the locations in the blind spot, which very likely need
#' to be removed
#' @param nbase number of visual fields to be used as baseline
#' @param nfollow number of visual fields to be used as follow up
#' @param alpha significance level to derive the conditional retest intervals.
#' Default value is \code{0.1}
#' @param ... arguments to be passed to or from methods. A useful one to try
#' is type of quantile calculation `\code{type}` use in \code{\link{quantile}}
#' @return \code{vfretestdist} returns a list with the following elements:
#' \itemize{
#' \item\code{x} with all the test values (x-axis)
#' \item\code{y} the distribution of retest dB values conditional to each
#' test value in \code{x}. It is a list with as many entries as \code{x}
#' \item\code{n} number of retest values conditional to each value in \code{x}.
#' It is a list with as many entries as \code{x}
#' \item\code{ymed} median for each value in \code{x}. It is a list with as
#' many entries as \code{x}
#' \item\code{ylow} quantile value for significance \code{1 - alpha / 2}
#' for each value in \code{x}. It is a list with as many entries as \code{x}
#' \item\code{yup} quantile value for significance \code{alpha / 2}
#' for each value in \code{x}. It is a list with as many entries as \code{x}
#' }
#' Together \code{ylow} and \code{yup} represent the lower and upper limit of the
#' \code{(1 - alpha)\%} confidence intervals at each value \code{x}.
#' @examples
#' # get the retest sensitivity data after removing the blind spot
#' retest <- vfretestdist(vfpwgRetest24d2, nbase = 1, nfollow = 1)
#'
#' plot(0, 0, typ = "n", xlim = c(0, 40), ylim = c(0,40),
#' xlab = "test in dB", ylab = "retest in dB", asp = 1)
#' for(i in 1:length(retest$x)) {
#' points(rep(retest$x[i], length(retest$y[[i]])), retest$y[[i]],
#' pch = 20, col = "lightgray", cex = 0.75)
#' }
#' lines(c(0,40), c(0,40), col = "black")
#' lines(retest$x, retest$ymed, col = "red")
#' lines(retest$x, retest$ylow, col = "red", lty = 2)
#' lines(retest$x, retest$yup, col = "red", lty = 2)
#' @export
vfretestdist <- function(vf, nbase = 1, nfollow = 1, alpha = 0.1, ...) {
# get all subject id and eye to process
idall <- paste(vf$id, vf$eye, sep = "_")
idu <- unique(idall)
neyes <- length(idu) # total number of eyes to process
vf <- round(vf[,getvfcols()]) # remove the first 4 columns corresponding to the key
if(length(getlocmap()$bs) > 0) vf <- vf[,-getlocmap()$bs] # remove blind spot if necessary
# check if it can be done
if(any(sapply(idu, function(idu) length(which(idall == idu))) < nbase + nfollow))
stop("not enough baseline and follow up data for the retest analysis")
# gather all possible values
retest <- NULL
retest$x <- sort(unique(c(as.matrix(vf))))
retest$y <- as.list(rep(NA, length(retest$x)))
# construct all possible permutations from the series
combs <- combinations((nbase + nfollow), nbase)
# start analysis for each possible combination
for(i in 1:nrow(combs)) {
# do the analysis for each subject-eye
for(j in 1:neyes) {
# first get the baseline data vs the followup data
idx <- which(idall == idu[j])
vfiter <- vf[idx[1:(nbase + nfollow)],]
dbbase <- vfiter[combs[i,],]
dbfollow <- as.numeric(colMeans(vf[idx[-combs[i,]],]))
# analyse baseline
idxbase <- NULL
for(k in 1:ncol(dbbase)) {
if(all(dbbase[,k] == dbbase[1,k])) idxbase <- c(idxbase, k)
}
# mount conditional distribution
if(length(idxbase) > 0) {
for(k in 1:length(idxbase)) {
idxcp <- which(retest$x == dbbase[1,idxbase[k]])
if(length(retest$y[[idxcp]]) == 1 && is.na(retest$y[[idxcp]])) {
retest$y[[idxcp]] <- dbfollow[idxbase[k]]
} else {
retest$y[[idxcp]] <- c(retest$y[[idxcp]], dbfollow[idxbase[k]])
}
}
}
}
}
# remove whatever has no data in it
idx <- which(is.na(retest$y))
if(length( idx ) > 0) {
retest$x <- retest$x[-idx]
retest$y[idx] <- NULL
}
# sort the results and obtain percentiles at level alpha
for(i in 1:length(retest$y)) {
retest$y[[i]] <- sort(retest$y[[i]])
qq <- as.numeric(quantile(retest$y[[i]],
probs = c(0.5, alpha / 2, 1 - alpha / 2), ...))
retest$n[i] <- length(retest$y[[i]])
retest$ymed[i] <- qq[1]
retest$ylow[i] <- qq[2]
retest$yup[i] <- qq[3]
}
return(retest)
}
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/vfstats.R
|
#' @rdname visualFields
#' @title visualFields: statistical methods for visual fields
#' @description visualFields is a collection of tools for analyzing the field of vision.
#' It provides a framework for development and use of innovative methods
#' for visualization, statistical analysis, and clinical interpretation
#' of visual-field loss and its change over time. It is intended to be a
#' tool for collaborative research.
#' @details The development version of visualFields 1.x, can be found in
#' \url{https://github.com/imarinfr/vf1}. For developers who want to collaborate
#' extending, updating, and patching visualFields, all necessary imports are to
#' be added to the source file \code{visualFields.R}. visualField developers can
#' use the source codes here as examples on how to craft new source code and keep
#' documentation that is consistent with the rest of the package, roxygen2, and CRAN.
#'
#' The previous version of visualFields, 0.6, is still available for use in
#' \url{https://github.com/imarinfr/vf0}, but is no longer maintained.
#'
#' This work was supported by the NIH grant number \bold{R01EY007716} and
#' the Veterans Administration grant number \bold{I01 RX-001821-01A1}.
#' @seealso \code{OPI}: the Open Perimetry Initiative
#' \url{https://people.eng.unimelb.edu.au/aturpin/opi/index.html}
#' @references
#' Marín-Franch I & Swanson WH. \emph{The visualFields package: A tool for
#' analysis and visualization of visual fields}. Journal of Vision, 2013,
#' 13(4):10, 1-12
#'
#' Turpin A, Artes PH, & McKendrick AM. \emph{The Open Perimetry Interface:
#' An enabling tool for clinical visual psychophysics}. Journal of Vision,
#' 2012, 12(11):22, 21–25
#' @import utils graphics
#' @importFrom stats sd lm quantile predict aggregate approx na.pass optimize pt var mad
#' @importFrom Hmisc wtd.mean wtd.var wtd.quantile
#' @importFrom dplyr filter
#' @importFrom gtools combinations
#' @importFrom combinat permn
#' @importFrom XML xmlParse xmlToList
#' @importFrom oro.dicom readDICOMFile
#' @importFrom grDevices colorRampPalette rgb col2rgb chull pdf dev.off
#' @importFrom polyclip polyclip polyoffset
#' @importFrom deldir deldir tile.list
#' @importFrom plotrix draw.circle draw.ellipse
#' @importFrom tools toTitleCase
#' @importFrom rlang sym
#' @importFrom shiny fluidPage titlePanel sidebarLayout sidebarPanel column selectInput div
#' mainPanel br tabsetPanel tabPanel plotOutput htmlOutput actionButton icon
#' reactiveVal observeEvent updateSelectInput renderText renderPlot shinyApp
#' @importFrom shinyjs useShinyjs
#' @importFrom DT dataTableOutput renderDataTable
#' @importFrom htmlTable htmlTable
#' @importFrom boot boot
#' @importFrom pracma inv interp2
"_PACKAGE"
#' @rdname vfenv
#' @title Settings in the visualField environment
#' @description Functions to set and get settings in the visualField environment
#' @details
#' \itemize{
#' \item\code{setdefaults} sets the default location map, normative value and
#' graphical parameters visualFields environment
#' \item\code{setnv} sets normative values in the visualFields environment
#' \item\code{getnv} gets current normative values from the visualFields
#' environment
#' \item\code{setlocmap} sets a location map in the visualFields environment
#' \item\code{getlocmap} gets the current location map from the visualFields
#' environment
#' \item\code{setgpar} sets graphical parameters in the visualFields environment
#' \item\code{getgpar} gets current graphical parameters from the visualFields
#' environment
#' \item\code{setlocini} sets the column where visual field data start in the
#' visualFields environment
#' \item\code{getlocini} gets the column where visual field data starts from
#' the visualFields environment
#' \item\code{getlocini} gets the column where visual field data starts from
#' the visualFields environment
#' \item\code{getvfcols} gets all the columns with visual field data
#' }
#' @examples
#' # get and set normative values
#' getnv()$info$name # print name of set normative values
#' setnv(normvals$iowa_PC26_pw_cps) # set pointwise normative values
#' getnv()$info$name # print name of set normative values
#' setdefaults() # return back to defaults
#' # get and set a location map
#' getlocmap()$name # name of set normative values
#' setlocmap(locmaps$p30d2) # set the 30-2 location map
#' getlocmap()$name # name of set normative values
#' setdefaults() # return back to defaults
#' # get and set a graphical parameters
#' getgpar()$tess$xlim # limits of x axis
#' setgpar(gpars$pPeri) # set graphical parameters for the Peripheral test
#' getgpar()$tess$xlim # limits of x axis
#' setdefaults() # return back to defaults
#' # get and set initial column for visual field data
#' getlocini()
#' getvfcols() # get columns with visual fields data
#' setlocini(15)
#' getvfcols() # get columns with visual fields data
#' setdefaults() # return back to defaults
#' @return \code{setdefaults}: No return value
#' @export
setdefaults <- function() {
setlocini(11) # set starting location for visual fields data
setlocmap(visualFields::locmaps$p24d2) # set default location map
setnv(visualFields::normvals$sunyiu_24d2) # set default normative values
setgpar(visualFields::gpars$p24d2) # set default graphical parameters
}
#' @rdname vfenv
#' @return \code{getnv}: Returns the normative value currently in used by visualFields
#' @export
getnv <- function() return(.vfenv$nv)
#' @rdname vfenv
#' @param nv normative values to to set in the visualFields environment
#' @return \code{setnv}: No return value
#' @export
setnv <- function(nv) {
if(is.null(nv)) stop("normative values input is null")
assign("nv", nv, envir = .vfenv)
}
#' @rdname vfenv
#' @return \code{getgpar}: Returns the graphical parameters currently in used by visualFields
#' @export
getgpar <- function() return(.vfenv$gpar)
#' @rdname vfenv
#' @param gpar structure with all graphical parameters
#' @return \code{setgpar}: No return value
#' @export
setgpar <- function(gpar) {
if(is.null(gpar)) stop("graphical parameters input is null")
assign("gpar", gpar, envir = .vfenv)
}
#' @rdname vfenv
#' @return \code{getlocmap}: Returns the location map currently in used by visualFields
#' @export
getlocmap <- function() return(.vfenv$locmap)
#' @rdname vfenv
#' @param locmap location map to to set in the visualFields environment
#' @return \code{setlocmap}: No return value
#' @export
setlocmap <- function(locmap) {
if(is.null(locmap)) stop("location map input is null")
assign("locmap", locmap, envir = .vfenv)
}
#' @rdname vfenv
#' @return \code{getlocini}: Returns the column where visual field data starts
#' @export
getlocini <- function() return(.vfenv$locini)
#' @rdname vfenv
#' @param locini column from where to start reading the visual field data
#' @return \code{setlocini}: No return value
#' @export
setlocini <- function(locini = 11) {
if(is.null(locini)) stop("locini input is null")
assign("locini", locini, envir = .vfenv)
}
#' @rdname vfenv
#' @return \code{getvfcols}: Returns the columns with visual field data
#' @export
getvfcols <- function() return(getlocini() - 1 + 1:nrow(getlocmap()$coord))
#' @noRd
#' @export
.vfenv <- new.env(parent = globalenv(), size = 3) # create visualFields environment
.onAttach <- function(libname, pkgname) setdefaults()
|
/scratch/gouwar.j/cran-all/cranData/visualFields/R/visualFields.R
|
#' Visualize's Supported Distributions
#'
#' All of visualize's supported distributions with their density, probability,
#' and quantile functions. In addition, mean and variance functions are
#' present. Other descriptors also exist and are documented below.
#'
#' @format
#' Distributions are loaded with the following format:
#' \tabular{ll}{
#' type: \tab specify either `"continuous"` or `"discrete"` \cr
#' \tab to direct the query to the right graph handler. \cr
#' name: \tab specify the name of the distribution. \cr
#' \tab In example, "Poisson Distribution." \cr
#' \tab This is used in the main graph title. \cr
#' variable: \tab specify the variable in probability statement.\cr
#' \tab In example, P(z < 5). \cr
#' \tab This is used in the probability subtitle. \cr
#' varsymbols:\tab specify the variable symbols for distribution.\cr
#' \tab In example, mu = 1 sd = 2. \cr
#' \tab This is used in the distribution subtitle. \cr
#' params: \tab specify the amount of params required for distribution.\cr
#' \tab This is used in the first error handling check to ensure\cr
#' \tab the correct number of params is supplied.\cr
#' init(params, ...):\tab Function that generates the mean and variance \cr
#' \tab of a distribution.\cr
#'
#' density(x, params, ncp = 0, lower.tail = TRUE, log = FALSE, ...):\tab
#' Function that provides the density value using vectors of the \cr
#' \tab quantiles from the distribution. \cr
#' \tab This serves as a wrapper for **d***distr_name*. \cr
#'
#' probability(x, params, ncp = 0, lower.tail = TRUE, log.p = FALSE, ...) \tab
#' Function that provides the probability value \cr
#' \tab using vectors of quantiles from the distribution. \cr
#' \tab This serves as a wrapper for **p***distr_name*.\cr
#'
#' quantile(x, params, ncp = 0, lower.tail = TRUE, log.p = FALSE, ...) \tab
#' Function that provides the quantile value \cr
#' \tab using vectors of probabilities from the distribution. \cr
#' \tab This serves as a wrapper for **q***distr_name*.\cr
#'
#' }
#'
#' The distributions currently available to use are: \tabular{llll}{
#' Distribution \tab r Name \tab Distribution \tab r Name \cr
#' Beta \tab beta \tab Lognormal* \tab lnorm \cr
#' Binomial \tab binom \tab Negative Binomial \tab nbinom \cr
#' Cauchy* \tab cauchy \tab Normal \tab norm \cr
#' Chisquare \tab chisq \tab Poisson \tab pois\cr
#' Exponential \tab exp \tab Student t* \tab t\cr
#' F* \tab f \tab Uniform \tab unif\cr
#' Gamma \tab gamma \tab Geometric \tab geom \cr
#' Hypergeometric \tab hyper \tab Wilcoxon* \tab wilcox\cr
#' Logistic* \tab logis\tab \tab \cr }
#' * denotes the distribution was added in v2.0.
#' @author James Balamuta
#' @keywords datasets internal
#' @examples
#' visualize.distributions = list(
#' 'beta' = list(
#' type = "continuous",
#' name = "Beta Distribution",
#' variable = "b",
#' varsymbols = c("\u03B1","\u03B2"),
#' params = 2,
#' init = function(params, ...) {
#' shape1 = params[[1]]; shape2 = params[[2]]
#' if(shape1 <= 0 || shape2 <= 0) stop("Error: Need alpha, beta > 0")
#' mean = shape1 / (shape1 + shape2)
#' var = (shape1 * shape2)/((shape1 + shape2 + 1)*(shape1 + shape2)^2)
#' c(mean, var)
#' },
#' density = function(x,params, ncp = 0, lower.tail = TRUE, log = FALSE, ...){
#' if(params[[1]] <= 0 || params[[2]] <= 0) stop("Error: Need alpha, beta > 0")
#' dbeta(x,params[[1]], params[[2]], ncp = ncp, log = log)
#' },
#' probability = function(q,params, ncp = 0, lower.tail = TRUE, log.p = FALSE, ...){
#' if(params[[1]] <= 0 || params[[2]] <= 0) stop("Error: Need alpha, beta > 0")
#' pbeta(q,params[[1]], params[[2]], ncp = ncp, lower.tail = lower.tail, log.p = log.p)
#' },
#' quantile = function(p,params, ncp = 0, lower.tail = TRUE, log.p = FALSE, ...){
#' if(params[[1]] <= 0 || params[[2]] <= 0) stop("Error: Need alpha, beta > 0")
#' qbeta(p,params[[1]], params[[2]], ncp = ncp, lower.tail = lower.tail, log.p = log.p)
#' }
#' )
#' )
#'
"visualize.distributions"
|
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize-distributions.R
|
#' @keywords internal
#' @importFrom graphics axis barplot mtext plot polygon title
#' @examples
#'
#' ## visualize.it acts as the general wrapper.
#' ## For guided application of visualize, see the visualize.distr_name list.
#' # Binomial distribution evaluated at lower tail.
#' visualize.it(dist = 'binom', stat = 2, params = list(size = 4,prob = .5),
#' section ="lower", strict = TRUE)
#' visualize.binom(stat = 2, size = 4, prob =.5, section ="lower", strict = TRUE)
#'
#' # Set to shade inbetween a bounded region.
#' visualize.it(dist = 'norm', stat = c(-1, 1), list(mu = 0, sd = 1), section="bounded")
#' visualize.norm(stat = c(-1, 1), mu = 0, sd = 1, section ="bounded")
#'
#' # Gamma distribution evaluated at upper tail.
#' visualize.it(dist = 'gamma', stat = 2, params = list(alpha = 2, theta = 1), section="upper")
#' visualize.gamma(stat = 2, alpha = 2, theta = 1, section="upper")
#'
#'
"_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/visualize/R/visualize-package.R
|
#' Visualize Beta Distribution
#'
#' Generates a plot of the Beta distribution with user specified parameters.
#'
#'
#' @param stat a statistic to obtain the probability from. When using the
#' "bounded" condition, you must supply the parameter as `stat =
#' c(lower_bound, upper_bound)`. Otherwise, a simple `stat =
#' desired_point` will suffice.
#' @param alpha `alpha` is considered to be *shape1* by R's
#' implementation of the beta distribution. `alpha` must be greater than
#' 0.
#' @param beta `beta` is considered to be *shape2* by R's
#' implementation of the beta distribution. `beta` must be greater than 0.
#' @param section Select how you want the statistic(s) evaluated via
#' `section=` either `"lower"`,`"bounded"`, `"upper"`,
#' or`"tails"`.
#' @return Returns a plot of the distribution according to the conditions
#' supplied.
#' @author James Balamuta
#' @export
#' @seealso [visualize.it()], [dbeta()].
#' @keywords continuous-distribution
#' @examples
#'
#' # Evaluates lower tail.
#' visualize.beta(stat = 1, alpha = 2, beta = 3, section = "lower")
#'
#' # Evaluates bounded region.
#' visualize.beta(stat = c(.5,1), alpha = 4, beta = 3, section = "bounded")
#'
#' # Evaluates upper tail.
#' visualize.beta(stat = 1, alpha = 2, beta = 3, section = "upper")
#'
visualize.beta <-
function(stat = 1, alpha = 3, beta = 2, section = "lower") {
visualize.it('beta', stat = stat, list(alpha = alpha, beta = beta),section = section)
}
|
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.beta.R
|
#' Visualize Binomial Distribution
#'
#' Generates a plot of the Binomial distribution with user specified
#' parameters.
#'
#'
#' @param stat a statistic to obtain the probability from. When using the
#' "bounded" condition, you must supply the parameter as `stat =
#' c(lower_bound, upper_bound)`. Otherwise, a simple `stat =
#' desired_point` will suffice.
#' @param size size of sample.
#' @param prob probability of picking object.
#' @param section Select how you want the statistic(s) evaluated via
#' `section=` either `"lower"`,`"bounded"`, `"upper"`,
#' or`"tails"`.
#' @param strict Determines whether the probability will be generated as a
#' strict (<, >) or equal to (<=, >=) inequality. `strict=` requires
#' either values = 0 or =FALSE for equal to OR values =1 or =TRUE for strict.
#' For bounded condition use: `strict=c(0,1)` or
#' `strict=c(FALSE,TRUE)`.
#' @author James Balamuta
#' @export
#' @seealso [visualize.it()] , [dbinom()].
#' @keywords visualize
#' @examples
#'
#' # Evaluates lower tail with equal to inequality.
#' visualize.binom(stat = 1, size = 3, prob = 0.5, section = "lower", strict = FALSE)
#'
#' # Evaluates bounded region with lower bound equal to and upper bound strict inequality.
#' visualize.binom(stat = c(1,2), size = 5, prob = 0.35, section = "bounded", strict = c(0,1))
#'
#' # Evaluates upper tail with strict inequality.
#' visualize.binom(stat = 1, size = 3, prob = 0.5, section = "upper", strict = TRUE)
#'
visualize.binom <-
function(stat = 1, size = 3, prob = .5, section = "lower", strict = FALSE) {
visualize.it('binom', stat = stat, list(size = size, prob = prob), section = section, strict=strict)
}
|
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.binom.R
|
#' Visualize Cauchy Distribution
#'
#' Generates a plot of the Cauchy distribution with user specified parameters.
#'
#'
#' @param stat a statistic to obtain the probability from. When using the
#' "bounded" condition, you must supply the parameter as `stat =
#' c(lower_bound, upper_bound)`. Otherwise, a simple `stat =
#' desired_point` will suffice.
#' @param location location parameter
#' @param scale scale parameter
#' @param section Select how you want the statistic(s) evaluated via
#' `section=` either `"lower"`,`"bounded"`, `"upper"`,
#' or`"tails"`.
#' @return Returns a plot of the distribution according to the conditions
#' supplied.
#' @author James Balamuta
#' @export
#' @seealso [visualize.it()], [dcauchy()].
#' @keywords continuous-distribution
#' @examples
#'
#' # Evaluates lower tail.
#' visualize.cauchy(stat = 1, location = 4, scale = 2, section = "lower")
#'
#' # Evaluates bounded region.
#' visualize.cauchy(stat = c(3,5), location = 5, scale = 3, section = "bounded")
#'
#' # Evaluates upper tail.
#' visualize.cauchy(stat = 1, location = 4, scale = 2, section = "upper")
#'
visualize.cauchy <-
function(stat = 1, location = 2, scale = 1, section = "lower") {
visualize.it('cauchy', stat = stat, list(location = location, scale = scale), section = section)
}
|
/scratch/gouwar.j/cran-all/cranData/visualize/R/visualize.cauchy.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.