content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# The BoutrosLab.plotting.general package is copyright (c) 2013 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO WRITE METADATA ####################################################################
write.metadata <- function(filename = NULL, description = NULL, verbose = FALSE) {
exiftool.location <- Sys.which('exiftool');
# whether to output stuff or not
if (FALSE == verbose) {
standard.out <- NULL;
}
else {
standard.out <- '';
}
# write metadata only if file exists and exiftool has been installed
if (!is.null(filename) && exiftool.location != '') {
# retrieve software versions
R.version <- getRversion();
lattice.version <- packageVersion('lattice');
lattice.extra.version <- packageVersion('latticeExtra');
plotting.general.version <- packageVersion('BoutrosLab.plotting.general');
plotting.survival.version <- tryCatch({
packageVersion('BoutrosLab.plotting.survival');
}, error = function(e) {
'unknown';
});
software.versions = paste0(
'R ',
R.version,
' | lattice ',
lattice.version,
' | latticeExtra ',
lattice.extra.version,
' | BL.plotting.general ',
plotting.general.version,
' | BL.plotting.survival ',
plotting.survival.version
);
# retrieve computer information
operating.system <- paste(Sys.info()[['sysname']], Sys.info()[['version']], collapse = ' ');
machine <- Sys.info()[['machine']];
# retrieve username
author <- Sys.info()[['user']];
# write author, software, description of figure,
# os info & hardware info
system2(
'exiftool',
args = paste0(
'-Author="',
author,
'" -Software="',
software.versions,
'" -ImageDescription="',
description,
'" -HostComputer="',
operating.system,
'" -Make="',
machine,
'" -overwrite_original ',
filename
),
stdout = standard.out
);
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/write.metadata.R
|
# The BoutrosLab plotting.general package is copyright (c) 2011 Ontario Institute for Cancer Research (OICR)
# This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL
# (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text.
# OICR makes no representations whatsoever as to the SOFTWARE contained herein. It is experimental in nature and is provided WITHOUT
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR IMPLIED. OICR MAKES NO REPRESENTATION
# OR WARRANTY THAT THE USE OF THIS SOFTWARE WILL NOT INFRINGE ANY PATENT OR OTHER PROPRIETARY RIGHT.
# By downloading this SOFTWARE, your Institution hereby indemnifies OICR against any loss, claim, damage or liability, of whatsoever kind or
# nature, which may arise from your Institution's respective use, handling or storage of the SOFTWARE.
# If publications result from research using this SOFTWARE, we ask that the Ontario Institute for Cancer Research be acknowledged and/or
# credit be given to OICR scientists, as scientifically appropriate.
### FUNCTION TO WRITE PLOT #######################################################################
write.plot <- function(
trellis.object, filename = NULL, additional.trellis.objects = NULL, additional.trellis.locations = NULL,
height = 6, width = 6, size.units = 'in', resolution = 1000, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general'
) {
if (!is.null(filename)) {
# check all potential locations for the extension->functionname mapping file
data.directories <- file.path(.libPaths(), 'BoutrosLab.plotting.general');
file.checks <- file.exists(file.path(data.directories, 'ext2function.txt'));
if (any(file.checks)) {
data.directory <- data.directories[order(file.checks, decreasing = TRUE)[1]];
}
else {
stop('Unable to find ext2function file.');
}
# read in the mapping table
mapping.object <- read.table(
paste(data.directory, 'ext2function.txt', sep = '/'),
sep = '\t',
header = TRUE,
as.is = TRUE
);
rownames(mapping.object) <- mapping.object$FileExt;
# set the graphics driver
old.type <- getOption('bitmapType');
if (capabilities('cairo')) {
options(bitmapType = 'cairo');
}
for (i in c(1:length(filename))) {
# determine which function to use
extension <- file_ext(filename[i]);
# if no extension is passed, use TIFF
if ('' == extension) {
extension <- 'tiff';
}
# set ps.options for eps
if ('eps' == extension) {
setEPS();
}
# grab the mapping object
if (!extension %in% rownames(mapping.object)) {
stop(paste('Unknown extension:', extension, '.'));
}
call.param <- mapping.object[extension, , drop = FALSE];
# set up the list of arguments
call.args <- list();
for (param in strsplit(call.param$Args, ';')[[1]]) {
param.split <- strsplit(param, '=')[[1]];
arg <- param.split[1];
val <- param.split[2];
# do not perform 'get' if the value begins with $ (our marker)
if (any(grep('^\\$', val, perl = TRUE))) {
val <- gsub('^\\$', '', val, perl = TRUE);
call.args[[arg]] <- val;
}
else {
call.args[[arg]] <- get(val);
}
}
call.args$filename <- filename[i];
do.call(call.param$Function, call.args);
# plot the object to the file
plot(trellis.object, newpage = FALSE);
# MANY checks for correctness of additional plots to embedded and parameters
if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) != 'list') ||
(!is.null(additional.trellis.locations) && typeof(additional.trellis.locations) != 'list')
) {
# checks if trellis objects and locations are provided in a list
stop('Additional trellis objects and their locations must be provided in a list.');
}
else if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) == 'list') &&
(is.null(additional.trellis.locations) || typeof(additional.trellis.locations) != 'list')
) {
# checks if coordinates are specified in a list if trellis objects are provided
stop('If trellis objects are specified, their coordinates must be provided in a list.');
}
else if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) == 'list') &&
(!is.null(additional.trellis.locations) && typeof(additional.trellis.locations) == 'list')
) {
# checks if elements denoting coordinates for trellis objects are appropriately named
# once the type of the parameters are deemed correct
# trellis locations object should have the following elements: xleft, ybottom, xright, ytop
if (
!exists('xleft', where = additional.trellis.locations) ||
!exists('ybottom', where = additional.trellis.locations) ||
!exists('xright', where = additional.trellis.locations) ||
!exists('ytop', where = additional.trellis.locations)
) {
stop('Locations for trellis objects must be specified using: xleft, ybottom, xright, ytop.');
}
# checking lengths of inputs
input.lengths <- list(
length(additional.trellis.objects),
length(additional.trellis.locations$xleft),
length(additional.trellis.locations$ybottom),
length(additional.trellis.locations$xright),
length(additional.trellis.locations$ytop)
);
# only proceed if inputs are equal
if (length(unique(input.lengths)) != 1) {
stop('Lists of trellis objects and coordinates provided not equal in length.');
}
else if (length(unique(input.lengths)) == 1) {
for (i in 1:length(additional.trellis.objects)) {
print(
x = additional.trellis.objects[[i]],
position = c(
additional.trellis.locations$xleft[i],
additional.trellis.locations$ybottom[i],
additional.trellis.locations$xright[i],
additional.trellis.locations$ytop[i]
),
newpage = FALSE
);
}
}
}
dev.off();
options(bitmapType = old.type);
if ('eps' == extension) {
# revert back to standard configuration
ps.options(reset = TRUE);
}
# write image metadata
BoutrosLab.plotting.general::write.metadata(
filename = filename[i],
description = description
);
}
}
else if (is.null(filename)) {
# MANY checks for correctness of additional plots to embedded and parameters
if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) != 'list') ||
(!is.null(additional.trellis.locations) && typeof(additional.trellis.locations) != 'list')
) {
# checks if trellis objects and locations are provided in a list
stop('Additional trellis objects and their locations must be provided in a list.');
}
else if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) == 'list') &&
(is.null(additional.trellis.locations) || typeof(additional.trellis.locations) != 'list')
) {
# checks if coordinates are specified in a list if trellis objects are provided
stop('If trellis objects are specified, their coordinates must be provided in a list.');
}
else if (
(!is.null(additional.trellis.objects) && typeof(additional.trellis.objects) == 'list') &&
(!is.null(additional.trellis.locations) && typeof(additional.trellis.locations) == 'list')
) {
# checks if elements denoting coordinates for trellis objects are appropriately named
# once the type of the parameters are deemed correct
# trellis locations object should have the following elements: xleft, ybottom, xright, ytop
if (
!exists('xleft', where = additional.trellis.locations) ||
!exists('ybottom', where = additional.trellis.locations) ||
!exists('xright', where = additional.trellis.locations) ||
!exists('ytop', where = additional.trellis.locations)
) {
stop('Locations for trellis objects must be specified using: xleft, ybottom, xright, ytop.');
}
# checking lengths of inputs
input.lengths <- list(
length(additional.trellis.objects),
length(additional.trellis.locations$xleft),
length(additional.trellis.locations$ybottom),
length(additional.trellis.locations$xright),
length(additional.trellis.locations$ytop)
);
# only proceed if inputs are equal
if (length(unique(input.lengths)) != 1) {
stop('Lists of trellis objects and coordinates provided not equal in length.');
}
else if (length(unique(input.lengths)) == 1) {
# plot the object to the file
plot(trellis.object, newpage = TRUE);
for (i in 1:length(additional.trellis.objects)) {
print(
x = additional.trellis.objects[[i]],
position = c(
additional.trellis.locations$xleft[i],
additional.trellis.locations$ybottom[i],
additional.trellis.locations$xright[i],
additional.trellis.locations$ytop[i]
),
newpage = FALSE
);
}
}
}
else {
return(trellis.object);
}
}
# check if graphics device is postscript
if ('postscript' %in% rownames(as.matrix(dev.cur()))) {
ps.options(family = 'sans');
}
# check if graphics device is not set i-e 'null device'
if (enable.warnings && 1 == dev.cur()) {
warning('\nIf you wish to print this plot to postscript device, please set family param as: postscript(family=\"sans\").\n');
}
}
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/R/write.plot.R
|
# this function is for testing how easily greyscale values are distinguished
### difference = the attempted greyscale cutoff difference
### value = if light or dark values should be emphasized
### total = the total number of greys displayed
print.greys <- function(difference, value, total = 25) {
start <- 1;
end <- 100;
if("light" == value){
start = 40;
}
else if ("dark" == value){
end = 60;
}
greyval <- seq(start, end, difference);
palette <- c();
greyval <- sample(greyval, total, replace = TRUE)
length(greyval)
for (i in 1:length(greyval)){
palette <- c(palette, paste("grey", greyval[i], sep=""));
}
jumbled.palette <- sample(palette, length(palette))
BoutrosLab.plotting.general::display.colours(jumbled.palette)
}
png("test4L.png")
print.greys(4, "light");
dev.off()
png("test4D.png")
print.greys(4, "dark");
dev.off()
png("test6L.png")
print.greys(6, "light");
dev.off()
png("test6D.png")
print.greys(6, "dark");
dev.off()
png("test8L.png")
print.greys(8, "light");
dev.off()
png("test8D.png")
print.greys(8, "dark");
dev.off()
png("test10L.png")
print.greys(10, "light");
dev.off()
png("test10D.png")
print.greys(10, "dark");
dev.off()
png("test12L.png")
print.greys(12,"light");
dev.off()
png("test12D.png")
print.greys(12,"dark");
dev.off()
png("test14L.png")
print.greys(14,"light");
dev.off()
png("test14D.png")
print.greys(14,"dark");
dev.off()
png("test16L.png")
print.greys(16,"light");
dev.off()
png("test16D.png")
print.greys(16,"dark");
dev.off()
png("test18L.png")
print.greys(18,"light");
dev.off()
png("test18D.png")
print.greys(18,"dark");
dev.off()
png("test20L.png")
print.greys(20,"light");
dev.off()
png("test20D.png")
print.greys(20,"dark");
dev.off()
png("test22L.png")
print.greys(22,"light");
dev.off()
png("test22D.png")
print.greys(22,"dark");
dev.off()
png("test24L.png")
print.greys(24,"light");
dev.off()
png("test24D.png")
print.greys(24,"dark");
dev.off()
#perl -w ~/Cluster/svn/BoutrosLab/Resources/code/perl/GeneralPerlUtilities/paper_tile_format.pl -d 300 -s 3x2 -i test4L.png -i test6L.png -i test8L.png -i test10L.png -i test12L.png -i test14L.png -l 4L 6L 8L 10L 12L 14L -o "testL.tiff"
#perl -w ~/Cluster/svn/BoutrosLab/Resources/code/perl/GeneralPerlUtilities/paper_tile_format.pl -d 300 -s 3x2 -i test4D.png -i test6D.png -i test8D.png -i test10D.png -i test12D.png -i test14D.png -l 4D 6D 8D 10D 12D 14D -o "testD.tiff"
#perl -w ~/Cluster/svn/BoutrosLab/Resources/code/perl/GeneralPerlUtilities/paper_tile_format.pl -d 300 -s 3x2 -i test16L.png -i test18L.png -i test20L.png -i test22L.png -i test24L.png -i test24L.png -l 16L 18L 20L 22L 24L 24L -o "test2L.tiff"
#perl -w ~/Cluster/svn/BoutrosLab/Resources/code/perl/GeneralPerlUtilities/paper_tile_format.pl -d 300 -s 3x2 -i test16D.png -i test18D.png -i test20D.png -i test22D.png -i test24D.png -i test24D.png -l 16D 18D 20D 22D 24D 24D -o "test2D.tiff"
|
/scratch/gouwar.j/cran-all/cranData/BoutrosLab.plotting.general/inst/scripts/test_greyscale.R
|
#' Estimated Abilities from a Bradley-Terry Model
#'
#' Computes the (baseline) ability of each player from a model object of class
#' `"BTm"`.
#'
#' The player abilities are either directly estimated by the model, in which
#' case the appropriate parameter estimates are returned, otherwise the
#' abilities are computed from the terms of the fitted model that involve
#' player covariates only (those indexed by `model$id` in the model
#' formula). Thus parameters in any other terms are assumed to be zero. If one
#' player has been set as the reference, then `predict.BTm()` can be used to
#' obtain ability estimates with non-player covariates set to other values,
#' see examples for [predict.BTm()].
#'
#' If the abilities are structured according to a linear predictor, and if
#' there are player covariates with missing values, the abilities for the
#' corresponding players are estimated as separate parameters. In this event
#' the resultant matrix has an attribute, named `"separate"`, which
#' identifies those players whose ability was estimated separately. For an
#' example, see [flatlizards()].
#'
#' @aliases BTabilities print.BTabilities coef.BTabilities vcov.BTabilities
#' @param model a model object for which `inherits(model, "BTm")` is
#' `TRUE`
#' @return A two-column numeric matrix of class `c("BTabilities",
#' "matrix")`, with columns named `"ability"` and `"se"`; has one row
#' for each player; has attributes named `"vcov"`, `"modelcall"`,
#' `"factorname"` and (sometimes --- see below) `"separate"`. The
#' first three attributes are not printed by the method
#' `print.BTabilities`.
#'
#' @author David Firth and Heather Turner
#' @seealso [BTm()], [residuals.BTm()]
#' @references Firth, D. (2005) Bradley-Terry models in R. *Journal of
#' Statistical Software*, **12**(1), 1--12.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#' @keywords models
#' @examples
#'
#' ### citations example
#'
#' ## Convert frequencies to success/failure data
#' citations.sf <- countsToBinomial(citations)
#' names(citations.sf)[1:2] <- c("journal1", "journal2")
#'
#' ## Fit the "standard" Bradley-Terry model
#' citeModel <- BTm(cbind(win1, win2), journal1, journal2, data = citations.sf)
#' BTabilities(citeModel)
#'
#' ### baseball example
#'
#' data(baseball) # start with baseball data as provided by package
#'
#' ## Fit mode with home advantage
#' baseball$home.team <- data.frame(team = baseball$home.team, at.home = 1)
#' baseball$away.team <- data.frame(team = baseball$away.team, at.home = 0)
#' baseballModel2 <- BTm(cbind(home.wins, away.wins), home.team, away.team,
#' formula = ~ team + at.home, id = "team",
#' data = baseball)
#' ## Estimate abilities for each team, relative to Baltimore, when
#' ## playing away from home:
#' BTabilities(baseballModel2)
#'
#' @importFrom stats C contrasts model.frame model.matrix model.offset na.exclude na.pass terms reformulate relevel vcov
#' @export
BTabilities <- function (model)
{
if (!inherits(model, "BTm"))
stop("model is not of class BTm")
X0 <- model.matrix(model)
player1 <- model$player1[, model$id]
player.names <- levels(player1)
factors <- attr(terms(model$formula), "factors")
if (!(model$id %in% rownames(factors))) {
players <- data.frame(factor(seq(player.names), labels = player.names))
names(players) <- model$id
## assume player covariates indexed by id
fixed <- nobars(model$formula)
factors <- attr(terms(fixed), "factors")
vars <- rownames(factors)
by.id <- grep(paste("[", model$id, "]", sep = ""), vars,
fixed = TRUE)
drop <- setdiff(seq(length(vars)), by.id)
## following will only work for linear terms
## (drop any term involving non-player covariate)
keep <- colSums(factors[drop, , drop = FALSE]) == 0
formula <- reformulate(names(keep)[keep])
mf <- model.frame(terms(formula), data = c(players, model$data),
na.action = na.pass)
rownames(mf) <- player.names
players <- players[, model$id]
offset <- model.offset(mf)
if (is.null(offset)) offset <- 0
predvars <- setdiff(seq(ncol(mf)),
attr(attr(mf, "terms"), "offset"))
predvars <- reformulate(colnames(mf)[predvars])
X <- model.matrix(predvars, mf)
Xmiss <- is.na(rowSums(X)) | players %in% model$separate.ability
X[Xmiss, ] <- 0
X <- X[, -1, drop = FALSE]
separate.ability <- unique(union(players[Xmiss],
model$separate.ability))
ns <- length(separate.ability)
if (ns) {
S <- matrix(0, nrow = nrow(X), ncol = ns)
S[cbind(which(players %in% separate.ability), seq(ns))] <- 1
X <- cbind(S, X)
}
## remove inestimable coef
est <- !is.na(model$coef)
kept <- model$assign[est] %in% c(0, which(keep))
est <- est[kept]
X <- X[, est, drop = FALSE]
sqrt.vcov <- chol(vcov(model)[kept, kept])
V <- crossprod(sqrt.vcov %*% t(X))
se <- sqrt(diag(V))
abilities <- cbind(X %*% coef(model)[est][kept] + offset, se)
attr(abilities, "vcov") <- V
if (length(separate.ability)) {
attr(abilities, "separate") <- separate.ability
}
}
else {
## get ability coef and corresponding vcov
asgn <- model$assign
if (is.null(asgn))
abilities <- TRUE
else {
idterm <- attr(terms(model$formula), "term.labels") == model$id
if (!any(idterm))
stop("abilities not uniquely defined for this parameterization")
coefs.to.include <- asgn == which(idterm)
vcov.to.include <- asgn[!is.na(coef(model))] == which(idterm)
}
coef <- na.exclude(coef(model)[coefs.to.include])
vc <- vcov(model)[names(coef), names(coef), drop = FALSE]
## setup factor reflecting contrasts used ..
fac <- factor(player.names, levels = player.names)
if (!is.null(model$refcat)) {
fac <- C(relevel(fac, model$refcat),
"contr.treatment")
} else fac <- C(fac, model$contrasts[[model$id]])
contr <- contrasts(fac)[player.names,]
## calc abilities and s.e., fill in NA as necessary
if (!is.null(attr(coef, "na.action"))) {
contr <- contr[, -attr(coef, "na.action"), drop = FALSE]
}
est <- contr %*% coef
## vc of contrasts for use with qvcalc
vc <- contr %*% vc %*% t(contr)
se <- sqrt(diag(vc))
if (!is.null(attr(coef, "na.action"))){
id <- match(names(attr(coef, "na.action")),
paste0(model$id, rownames(contr)))
est[id] <- se[id] <- NA
}
abilities <- cbind(est, se)
rownames(abilities) <- player.names
attr(abilities, "vcov") <- vc
}
colnames(abilities) <- c("ability", "s.e.")
attr(abilities, "modelcall") <- model$call
attr(abilities, "factorname") <- model$id
class(abilities) <- c("BTabilities", "matrix")
abilities
}
#' @export
print.BTabilities <- function(x, ...) {
attr(x, "vcov") <- attr(x, "modelcall") <- attr(x, "factorname") <- NULL
class(x) <- "matrix"
print(x, ...) ## ie, print without showing the messy attributes
}
#' @export
vcov.BTabilities <- function(object, ...) {
attr(object, "vcov")
}
#' @export
coef.BTabilities <- function(object, ...) {
object[, "ability"]
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/BTabilities.R
|
#' Bradley-Terry Model and Extensions
#'
#' Fits Bradley-Terry models for pair comparison data, including models with
#' structured scores, order effect and missing covariate data. Fits by either
#' maximum likelihood or maximum penalized likelihood (with Jeffreys-prior
#' penalty) when abilities are modelled exactly, or by penalized
#' quasi-likelihood when abilities are modelled by covariates.
#'
#' In each comparison to be modelled there is a 'first player' and a 'second
#' player' and it is assumed that one player wins while the other loses (no
#' allowance is made for tied comparisons).
#'
#' The [countsToBinomial()] function is provided to convert a
#' contingency table of wins into a data frame of wins and losses for each pair
#' of players.
#'
#' The `formula` argument specifies the model for player ability and
#' applies to both the first player and the second player in each contest. If
#' `NULL` a separate ability is estimated for each player, equivalent to
#' setting `formula = reformulate(id)`.
#'
#' Contest-level variables can be specified in the formula in the usual manner,
#' see [formula()]. Player covariates should be included as variables
#' indexed by `id`, see examples. Thus player covariates must be ordered
#' according to the levels of the ID factor.
#'
#' If `formula` includes player covariates and there are players with
#' missing values over these covariates, then a separate ability will be
#' estimated for those players.
#'
#' When player abilities are modelled by covariates, then random player effects
#' should be added to the model. These should be specified in the formula using
#' the vertical bar notation of [lme4::lmer()], see examples.
#'
#' When specified, it is assumed that random player effects arise from a
#' \eqn{N(0, }{N(0, sigma^2)}\eqn{ \sigma^2)}{N(0, sigma^2)} distribution and
#' model parameters, including \eqn{\sigma}{sigma}, are estimated using PQL
#' (Breslow and Clayton, 1993) as implemented in the [glmmPQL()]
#' function.
#'
#' @param outcome the binomial response: either a numeric vector, a factor in
#' which the first level denotes failure and all others success, or a
#' two-column matrix with the columns giving the numbers of successes and
#' failures.
#' @param player1 either an ID factor specifying the first player in each
#' contest, or a data.frame containing such a factor and possibly other
#' contest-level variables that are specific to the first player. If given in a
#' data.frame, the ID factor must have the name given in the `id`
#' argument. If a factor is specified it will be used to create such a
#' data.frame.
#' @param player2 an object corresponding to that given in `player1` for
#' the second player in each contest, with identical structure -- in particular
#' factors must have identical levels.
#' @param formula a formula with no left-hand-side, specifying the model for
#' player ability. See details for more information.
#' @param id the name of the ID factor.
#' @param separate.ability (if `formula` does not include the ID factor as
#' a separate term) a character vector giving the names of players whose
#' abilities are to be modelled individually rather than using the
#' specification given by `formula`.
#' @param refcat (if `formula` includes the ID factor as a separate term)
#' a character specifying which player to use as a reference, with the first
#' level of the ID factor as the default. Overrides any other contrast
#' specification for the ID factor.
#' @param family a description of the error distribution and link function to
#' be used in the model. Only the binomial family is implemented, with
#' either`"logit"`, `"probit"` , or `"cauchit"` link. (See
#' [stats::family()] for details of family functions.)
#' @param data an optional object providing data required by the model. This
#' may be a single data frame of contest-level data or a list of data frames.
#' Names of data frames are ignored unless they refer to data frames specified
#' by `player1` and `player2`. The rows of data frames that do not
#' contain contest-level data must correspond to the levels of a factor used
#' for indexing, i.e. row 1 corresponds to level 1, etc. Note any rownames are
#' ignored. Objects are searched for first in the `data` object if
#' provided, then in the environment of `formula`. If `data` is a
#' list, the data frames are searched in the order given.
#' @param weights an optional numeric vector of \sQuote{prior weights}.
#' @param subset an optional logical or numeric vector specifying a subset of
#' observations to be used in the fitting process.
#' @param na.action a function which indicates what should happen when any
#' contest-level variables contain `NA`s. The default is the
#' `na.action` setting of `options`. See details for the handling of
#' missing values in other variables.
#' @param start a vector of starting values for the fixed effects.
#' @param etastart a vector of starting values for the linear predictor.
#' @param mustart a vector of starting values for the vector of means.
#' @param offset an optional offset term in the model. A vector of length equal
#' to the number of contests.
#' @param br logical. If `TRUE` fitting will be by penalized maximum
#' likelihood as in Firth (1992, 1993), using [brglm::brglm()],
#' rather than maximum likelihood using [glm()], when abilities are
#' modelled exactly or when the abilities are modelled by covariates and the
#' variance of the random effects is estimated as zero.
#' @param model logical: whether or not to return the model frame.
#' @param x logical: whether or not to return the design matrix for the fixed
#' effects.
#' @param contrasts an optional list specifying contrasts for the factors in
#' `formula`. See the `contrasts.arg` of [model.matrix()].
#' @param \dots other arguments for fitting function (currently either
#' [glm()], [brglm::brglm()], or [glmmPQL()])
#' @return An object of class `c("BTm", "x")`, where `"x"` is the
#' class of object returned by the model fitting function (e.g. `glm`).
#' Components are as for objects of class `"x"`, with additionally
#' \item{id}{the `id` argument.} \item{separate.ability}{the
#' `separate.ability` argument.} \item{refcat}{the `refcat`
#' argument.} \item{player1}{a data frame for the first player containing the
#' ID factor and any player-specific contest-level variables.} \item{player2}{a
#' data frame corresponding to that for `player1`.} \item{assign}{a
#' numeric vector indicating which coefficients correspond to which terms in
#' the model.} \item{term.labels}{labels for the model terms.}
#' \item{random}{for models with random effects, the design matrix for the
#' random effects. }
#' @author Heather Turner, David Firth
#' @seealso [countsToBinomial()], [glmmPQL()],
#' [BTabilities()], [residuals.BTm()],
#' [add1.BTm()], [anova.BTm()]
#' @references
#'
#' Agresti, A. (2002) *Categorical Data Analysis* (2nd ed). New York:
#' Wiley.
#'
#' Firth, D. (1992) Bias reduction, the Jeffreys prior and GLIM. In
#' *Advances in GLIM and Statistical Modelling*, Eds. Fahrmeir, L.,
#' Francis, B. J., Gilchrist, R. and Tutz, G., pp91--100. New York: Springer.
#'
#' Firth, D. (1993) Bias reduction of maximum likelihood estimates.
#' *Biometrika* **80**, 27--38.
#'
#' Firth, D. (2005) Bradley-Terry models in R. *Journal of Statistical
#' Software*, **12**(1), 1--12.
#'
#' Stigler, S. (1994) Citation patterns in the journals of statistics and
#' probability. *Statistical Science* **9**, 94--108.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#' @keywords models
#' @examples
#'
#' ########################################################
#' ## Statistics journal citation data from Stigler (1994)
#' ## -- see also Agresti (2002, p448)
#' ########################################################
#'
#' ## Convert frequencies to success/failure data
#' citations.sf <- countsToBinomial(citations)
#' names(citations.sf)[1:2] <- c("journal1", "journal2")
#'
#' ## First fit the "standard" Bradley-Terry model
#' citeModel <- BTm(cbind(win1, win2), journal1, journal2, data = citations.sf)
#'
#' ## Now the same thing with a different "reference" journal
#' citeModel2 <- update(citeModel, refcat = "JASA")
#' BTabilities(citeModel2)
#'
#' ##################################################################
#' ## Now an example with an order effect -- see Agresti (2002) p438
#' ##################################################################
#' data(baseball) # start with baseball data as provided by package
#'
#' ## Simple Bradley-Terry model, ignoring home advantage:
#' baseballModel1 <- BTm(cbind(home.wins, away.wins), home.team, away.team,
#' data = baseball, id = "team")
#'
#' ## Now incorporate the "home advantage" effect
#' baseball$home.team <- data.frame(team = baseball$home.team, at.home = 1)
#' baseball$away.team <- data.frame(team = baseball$away.team, at.home = 0)
#' baseballModel2 <- update(baseballModel1, formula = ~ team + at.home)
#'
#' ## Compare the fit of these two models:
#' anova(baseballModel1, baseballModel2)
#'
#' ##
#' ## For a more elaborate example with both player-level and contest-level
#' ## predictor variables, see help(chameleons).
#' ##
#'
#' @importFrom brglm brglm
#' @export
BTm <- function(outcome = 1, player1, player2, formula = NULL,
id = "..", separate.ability = NULL, refcat = NULL,
family = "binomial", data = NULL, weights = NULL, subset = NULL,
na.action = NULL, start = NULL, etastart = NULL, mustart = NULL,
offset = NULL, br = FALSE, model = TRUE, x = FALSE,
contrasts = NULL, ...){
call <- match.call()
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family))
family <- family()
if (is.null(family$family)) {
print(family)
stop("`family' not recognized")
}
if (family$family != "binomial")
stop("`family' must be binomial")
if (!family$link %in% c("logit", "probit", "cauchit"))
stop("link for binomial family must be one of \"logit\", \"probit\"",
"or \"cauchit\"")
fcall <- as.list(match.call(expand.dots = FALSE))
if (is.null(formula)) {
formula <- reformulate(id)
environment(formula) <- parent.frame()
fcall$formula <- formula
}
setup <- match(c("outcome", "player1", "player2", "formula", "id",
"separate.ability", "refcat", "data", "weights",
"subset", "offset", "contrasts"), names(fcall), 0L)
setup <- do.call(BTm.setup, fcall[setup], envir = parent.frame())
if (setup$saturated)
warning("Player ability saturated - equivalent to fitting ",
"separate abilities.")
mf <- data.frame(X = setup$player1) #just to get length
if (!is.null(setup$X)) {
mf$X <- setup$X
formula <- Y ~ X - 1
}
else formula <- Y ~ 0
mf$Y <- setup$Y
argPos <- match(c("na.action", "start", "etastart",
"mustart", "control", "model", "x"), names(fcall), 0)
dotArgs <- fcall$"..."
if (is.null(setup$random)) {
method <- get(ifelse(br, "brglm", "glm"), mode = "function")
fit <- as.call(c(method, fcall[argPos],
list(formula = formula, family = family, data = mf,
offset = setup$offset, subset = setup$subset,
weights = setup$weights), dotArgs))
fit <- eval(fit, parent.frame())
}
else {
method <- get("glmmPQL", mode = "function")
fit <- as.call(c(method, fcall[argPos],
list(formula, setup$random, family = family,
data = mf, offset = setup$offset,
subset = setup$subset, weights = setup$weights),
dotArgs))
fit <- eval(fit, parent.frame())
if (br) {
if (identical(fit$sigma, 0)){
argPos <- match(c("na.action", "model", "x"), names(fcall), 0)
method <- get("brglm", mode = "function")
fit <- as.call(c(method, fcall[argPos],
list(formula, family = family, data = mf,
offset = setup$offset,
subset = setup$subset,
weights = setup$weights,
etastart = fit$linear.predictors)))
fit <- eval(fit, parent.frame())
fit$class <- c("glmmPQL", class(fit))
}
else
warning("'br' argument ignored for models with random effects",
call. = FALSE)
}
}
if (length(fit$coefficients)) {
if (ncol(setup$X) > 1)
names(fit$coefficients) <- substring(names(fit$coefficients), 2)
else
names(fit$coefficients) <- colnames(setup$X)
fit$assign <- attr(setup$X, "assign")
}
fit$call <- call
fit$id <- id
fit$separate.ability <- separate.ability
fit$contrasts <- setup$contrasts
fit$refcat <- setup$refcat
fit$formula <- setup$formula
fit$player1 <- setup$player1
fit$player2 <- setup$player2
fit$term.labels <- setup$term.labels
fit$data <- setup$data
fit$random <- setup$random
class(fit) <- c("BTm", class(fit))
fit
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/BTm.R
|
#' @importFrom stats reformulate
BTm.setup <- function(outcome = 1, player1, player2, formula = NULL,
id = "..", separate.ability = NULL, refcat = NULL,
data = NULL, weights = NULL, subset = NULL,
offset = NULL, contrasts = NULL, ...){
if (!is.data.frame(data)){
keep <- names(data) %in% c(deparse(substitute(player1)),
deparse(substitute(player2)))
if (!length(keep)) keep <- FALSE
## save row names for checking against index variables (in Diff)
data <- lapply(data, as.data.frame)
nm <- lapply(data, rownames)
data <- c(data[keep], unlist(unname(data[!keep]), recursive = FALSE))
if (any(dup <- duplicated(names(data))))
warning("'data' argument specifies duplicate variable names: ",
paste(names(data)[dup], collapse = " "))
}
## (will take first occurence of replicated names)
withIfNecessary <- function(x, formula, data = NULL, as.data.frame = TRUE) {
if (as.data.frame)
expr <- substitute(data.frame(x), list(x = x))
else expr <- x
eval(expr, data, enclos = environment(formula))
}
player1 <- withIfNecessary(substitute(player1), formula, data)
player2 <- withIfNecessary(substitute(player2), formula, data)
if (ncol(player1) == 1) colnames(player1) <- colnames(player2) <- id
Y <- withIfNecessary(substitute(outcome), formula,
c(player1, player2, data), as.data.frame = FALSE)
weights <- withIfNecessary(substitute(weights), formula, data, FALSE)
subset1 <- withIfNecessary(substitute(subset), formula,
c(player1 = list(player1),
player2 = list(player2), player1, data), FALSE)
subset2 <- withIfNecessary(substitute(subset), formula,
c(player1 = list(player1),
player2 = list(player2), player2, data), FALSE)
if (is.logical(subset1)) subset <- subset1 | subset2
else subset <- c(subset1, subset2)
diffModel <- Diff(player1, player2, formula, id, data, separate.ability,
refcat, contrasts, nm)
# offset is contest level
offset <- withIfNecessary(substitute(offset), formula, data, FALSE)
if (!is.null(offset)) {
if (is.null(diffModel$offset)) diffModel$offset <- offset
else diffModel$offset <- diffModel$offset + offset
}
res <- c(diffModel, list(data = data, player1 = player1, player2 = player2,
Y = Y, weights = weights, subset = subset,
formula = formula))
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/BTm.setup.R
|
#' Dittrich, Hatzinger and Katzenbeisser (1998, 2001) Data on Management School
#' Preference in Europe
#'
#' *Community of European management schools* (CEMS) data as used in the
#' paper by Dittrich et al. (1998, 2001), re-formatted for use with
#' [BTm()]
#'
#' The variables `win1.adj` and `win2.adj` are provided in order to
#' allow a simple way of handling ties (in which a tie counts as half a win and
#' half a loss), which is slightly different numerically from the Davidson
#' (1970) method that is used by Dittrich et al. (1998): see the examples.
#'
#' @name CEMS
#' @docType data
#' @format A list containing three data frames, `CEMS$preferences`,
#' `CEMS$students` and `CEMS$schools`.
#'
#' The `CEMS$preferences` data frame has `303 * 15 = 4505`
#' observations (15 possible comparisons, for each of 303 students) on the
#' following 8 variables: \describe{
#' \item{student}{a factor with
#' levels `1:303`}
#' \item{school1}{a factor with levels
#' `c("Barcelona", "London", "Milano", "Paris", "St.Gallen",
#' "Stockholm")`; the first management school in a comparison}
#' \item{school2}{a factor with the same levels as `school1`; the
#' second management school in a comparison}
#' \item{win1}{integer (value
#' 0 or 1) indicating whether `school1` was preferred to `school2`}
#' \item{win2}{integer (value 0 or 1) indicating whether `school2`
#' was preferred to `school1`}
#' \item{tied}{integer (value 0 or 1)
#' indicating whether no preference was expressed}
#' \item{win1.adj}{numeric, equal to `win1 + tied/2`}
#' \item{win2.adj}{numeric, equal to `win2 + tied/2`} }
#'
#' The `CEMS$students` data frame has 303 observations (one for each
#' student) on the following 8 variables: \describe{
#' \item{STUD}{a
#' factor with levels `c("other", "commerce")`, the student's main
#' discipline of study}
#' \item{ENG}{a factor with levels `c("good,
#' poor")`, indicating the student's knowledge of English}
#' \item{FRA}{a
#' factor with levels `c("good, poor")`, indicating the student's
#' knowledge of French}
#' \item{SPA}{a factor with levels `c("good,
#' poor")`, indicating the student's knowledge of Spanish}
#' \item{ITA}{a
#' factor with levels `c("good, poor")`, indicating the student's
#' knowledge of Italian}
#' \item{WOR}{a factor with levels `c("no",
#' "yes")`, whether the student was in full-time employment while studying}
#' \item{DEG}{a factor with levels `c("no", "yes")`, whether the
#' student intended to take an international degree}
#' \item{SEX}{a
#' factor with levels `c("female", "male")` } }
#'
#' The `CEMS$schools` data frame has 6 observations (one for each
#' management school) on the following 7 variables: \describe{
#' \item{Barcelona}{numeric (value 0 or 1)}
#' \item{London}{numeric (value 0 or 1)}
#' \item{Milano}{numeric
#' (value 0 or 1)} \item{Paris}{numeric (value 0 or 1)}
#' \item{St.Gallen}{numeric (value 0 or 1)}
#' \item{Stockholm}{numeric (value 0 or 1)}
#' \item{LAT}{numeric
#' (value 0 or 1) indicating a 'Latin' city} }
#' @author David Firth
#' @references Davidson, R. R. (1970) Extending the Bradley-Terry model to
#' accommodate ties in paired comparison experiments. *Journal of the
#' American Statistical Association* **65**, 317--328.
#'
#' Dittrich, R., Hatzinger, R. and Katzenbeisser, W. (1998) Modelling the
#' effect of subject-specific covariates in paired comparison studies with an
#' application to university rankings. *Applied Statistics* **47**,
#' 511--525.
#'
#' Dittrich, R., Hatzinger, R. and Katzenbeisser, W. (2001) Corrigendum:
#' Modelling the effect of subject-specific covariates in paired comparison
#' studies with an application to university rankings. *Applied
#' Statistics* **50**, 247--249.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#' @source Royal Statistical Society datasets website, at
#' \url{https://rss.onlinelibrary.wiley.com/hub/journal/14679876/series-c-datasets/pre_2016}.
#' @keywords datasets
#' @examples
#'
#' ##
#' ## Fit the standard Bradley-Terry model, using the simple 'add 0.5'
#' ## method to handle ties:
#' ##
#' table3.model <- BTm(outcome = cbind(win1.adj, win2.adj),
#' player1 = school1, player2 = school2,
#' formula = ~.. , refcat = "Stockholm",
#' data = CEMS)
#' ## The results in Table 3 of Dittrich et al (2001) are reproduced
#' ## approximately by a simple re-scaling of the estimates:
#' table3 <- summary(table3.model)$coef[, 1:2]/1.75
#' print(table3)
#' ##
#' ## Now fit the 'final model' from Table 6 of Dittrich et al.:
#' ##
#' table6.model <- BTm(outcome = cbind(win1.adj, win2.adj),
#' player1 = school1, player2 = school2,
#' formula = ~ .. +
#' WOR[student] * Paris[..] +
#' WOR[student] * Milano[..] +
#' WOR[student] * Barcelona[..] +
#' DEG[student] * St.Gallen[..] +
#' STUD[student] * Paris[..] +
#' STUD[student] * St.Gallen[..] +
#' ENG[student] * St.Gallen[..] +
#' FRA[student] * London[..] +
#' FRA[student] * Paris[..] +
#' SPA[student] * Barcelona[..] +
#' ITA[student] * London[..] +
#' ITA[student] * Milano[..] +
#' SEX[student] * Milano[..],
#' refcat = "Stockholm",
#' data = CEMS)
#' ##
#' ## Again re-scale to reproduce approximately Table 6 of Dittrich et
#' ## al. (2001):
#' ##
#' table6 <- summary(table6.model)$coef[, 1:2]/1.75
#' print(table6)
#' ##
#' \dontrun{
#' ## Now the slightly simplified model of Table 8 of Dittrich et al. (2001):
#' ##
#' table8.model <- BTm(outcome = cbind(win1.adj, win2.adj),
#' player1 = school1, player2 = school2,
#' formula = ~ .. +
#' WOR[student] * LAT[..] +
#' DEG[student] * St.Gallen[..] +
#' STUD[student] * Paris[..] +
#' STUD[student] * St.Gallen[..] +
#' ENG[student] * St.Gallen[..] +
#' FRA[student] * London[..] +
#' FRA[student] * Paris[..] +
#' SPA[student] * Barcelona[..] +
#' ITA[student] * London[..] +
#' ITA[student] * Milano[..] +
#' SEX[student] * Milano[..],
#' refcat = "Stockholm",
#' data = CEMS)
#' table8 <- summary(table8.model)$coef[, 1:2]/1.75
#' ##
#' ## Notice some larger than expected discrepancies here (the coefficients
#' ## named "..Barcelona", "..Milano" and "..Paris") from the results in
#' ## Dittrich et al. (2001). Apparently a mistake was made in Table 8 of
#' ## the published Corrigendum note (R. Dittrich personal communication,
#' ## February 2010).
#' ##
#' print(table8)
#' }
#'
"CEMS"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/CEMS.R
|
#' @importFrom stats is.empty.model model.frame model.matrix model.offset na.omit na.pass reformulate relevel terms
Diff <- function(player1, player2, formula = NULL, id = "..", data = NULL,
separate.ability = NULL, refcat = NULL, contrasts = NULL,
subset = NULL) {
player.one <- player1[[id]]
player.two <- player2[[id]]
if (!is.factor(player.one) || !is.factor(player.two) ||
!identical(levels(player.one), levels(player.two)))
stop("'player1$", id, "' and 'player2$", id,
"' must be factors with the same levels")
if (!identical(attr(player.one, "contrasts"),
attr(player.two, "contrasts")))
stop("'player1$", id, "' and 'player2$", id,
"' must have the same contrasts attribute")
if(is.null(formula)) formula <- reformulate(id)
players <- levels(player.one)
nplayers <- nlevels(player.one)
ncontests <- length(player.one)
D <- matrix(nrow = ncontests, ncol = nplayers)
D <- col(D) == as.numeric(player.one)
D <- D - (col(D) == as.numeric(player.two))
colnames(D) <- paste(id, players, sep = "")
fixed <- nobars(formula)
X <- offset <- missing <- term.labels <- NULL
saturated <- FALSE
sep <- list()
empty <- is.null(fixed) || is.empty.model(mt <- terms(fixed))
if (!empty) {
factors <- attr(mt, "factors")
term.labels <- as.character(colnames(factors))
vars <- rownames(factors)
indexed <- grep("[[][^],]+[],]", vars)
if (length(indexed)) { #set NAs to zero
indices <- gsub("[^[]*[[]([^],]+)[],].*", "\\1", vars[indexed])
vars <- gsub("[[][^]]*[]]", "", vars[indexed])
## assumes no overlap, e.g. no age[..]:judge.gender[judge]
grp <- split(vars, indices)
for (ind in names(grp)) {
vars <- model.frame(terms(reformulate(grp[[ind]])),
data = data, na.action = na.pass)
lev <- levels(eval(as.name(ind), c(player1, data)))
as.sep <- rowSums(is.na(vars)) | lev %in% separate.ability
if (any(as.sep)) {
sep[[ind]] <- as.sep
vars[sep[[ind]], ] <- lapply(vars, function(x)
max(levels(x)[1], 0))
colnames(vars) <- gsub(".*[$[],? ?\"?([^]\"]*).*", "\\1",
grp[[ind]])
labels <- gsub("([^[$]*)[[$].*", "\\1", grp[[ind]])
for (lab in intersect(labels, grp[[ind]]))
data[lab] <- vars[lab]
for (lab in setdiff(labels, grp[[ind]]))
data[[lab]] <- vars[, labels == lab, drop = FALSE]
}
}
if (length(sep)) {
fixed <- reformulate(c(names(sep), attr(mt, "term.labels"),
rownames(attr(mt, "factors"))[
attr(mt, "offset")]))
mt <- terms(fixed)
}
}
idterm <- id %in% rownames(attr(mt, "factors"))
mf1 <- model.frame(mt, data = c(player1, data), na.action = na.pass)
if (nrow(mf1) != ncontests)
stop("Predictor variables are not of the correct length --",
"they probably need indexing in 'formula'.")
mf2 <- model.frame(mt, data = c(player2, data), na.action = na.pass)
if (idterm){
if (!is.null(refcat)) {
mf1[[id]] <- relevel(mf1[[id]], refcat)
mf2[[id]] <- relevel(mf2[[id]], refcat)
if (!is.null(contrasts)) contrasts[[id]] <- "contr.treatment"
} else {
## 'else' defined by contrasts arg/contrasts attr of id factor
## leave refcat NULL
if (is.null(contrasts) &
!is.null(attr(player.one, "contrasts"))){
contrasts <- list()
contrasts[[id]] <- attr(player.one, "contrasts")
}
}
}
offset <- model.offset(mf1)
if (!is.null(offset)) offset <- offset - model.offset(mf2)
if (length(sep)){ #create separate effect factor
recode <- function(x, keep){
lev <- levels(x)
ext <- make.unique(c(lev[keep], "nosep"))[sum(keep) + 1]
levels(x)[!keep] <- ext
relevel(x, ref = ext)
}
for (ind in names(grp)) {
mf1[ind] <- recode(mf1[[ind]], sep[[ind]])
mf2[ind] <- recode(mf2[[ind]], sep[[ind]])
}
}
X1 <- model.matrix(fixed, mf1, contrasts = contrasts)
X2 <- model.matrix(fixed, mf2, contrasts = contrasts)
X <- X1 - X2
## will need to check for saturation in each set of indexed var
## - however as only allowing (1|..) just consider player id for now
saturated <-
qr(na.omit(X))$rank == qr(na.omit(cbind(D, X)))$rank && !idterm
if (all(X[,1] == 0)) X <- X[, -1, drop = FALSE]
attr(X, "assign") <- attr(X1, "assign")[-1]
}
random <- findbars(formula[[2]])
if (!is.null(random)) {
if (!is.list(random)) random <- list(random)
if (length(random) > 1 ||
random[[1]] != parse(text = paste("1|", id, sep = ""))[[1]])
stop("Currently '(1 | ", id, ")' is the only random effects",
"structure allowed.")
random <- D
}
else if (!empty && (!idterm & !saturated))
warning("Ability modelled by predictors but no random effects",
call. = FALSE)
if (length(sep)) {
attr(X, "assign") <- attr(X, "assign") - 1
if (!is.null(random))
random <- D[,!sep[[id]], drop = FALSE]
}
list(X = X, random = random, offset = offset,
term.labels = term.labels, refcat = refcat, contrasts = contrasts,
saturated = saturated)
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/Diff.R
|
#' Specify a Generalised Davidson Term in a gnm Model Formula
#'
#' GenDavidson is a function of class `"nonlin"` to specify a generalised
#' Davidson term in the formula argument to [gnm::gnm()], providing a
#' model for paired comparison data where ties are a possible outcome.
#'
#' `GenDavidson` specifies a generalisation of the Davidson model (1970)
#' for paired comparisons where a tie is a possible outcome. It is designed for
#' modelling trinomial counts corresponding to the win/draw/loss outcome for
#' each contest, which are assumed Poisson conditional on the total count for
#' each match. Since this total must be one, the expected counts are
#' equivalently the probabilities for each possible outcome, which are modelled
#' on the log scale: \deqn{\log(p(i \textrm{beats} j)_k) = \theta_{ijk} +
#' \log(\mu\alpha_i}{log(p(i beats j)_k) = theta_{ijk} + log(mu * alpha_i)}
#' \deqn{\log(p(draw)_k) = \theta_{ijk} + \delta + c + }{ log(p(draw)_k) =
#' theta_{ijk} + log(delta) + c + sigma * (pi * log(mu * alpha_i) + (1 - pi) *
#' log(alpha_j)) + (1 - sigma) * log(mu * alpha_i + alpha_j) }\deqn{
#' \sigma(\pi\log(\mu\alpha_i) - (1 - \pi)log(\alpha_j)) + }{ log(p(draw)_k) =
#' theta_{ijk} + log(delta) + c + sigma * (pi * log(mu * alpha_i) + (1 - pi) *
#' log(alpha_j)) + (1 - sigma) * log(mu * alpha_i + alpha_j) }\deqn{ (1 -
#' \sigma)(\log(\mu\alpha_i + \alpha_j))}{ log(p(draw)_k) = theta_{ijk} +
#' log(delta) + c + sigma * (pi * log(mu * alpha_i) + (1 - pi) * log(alpha_j))
#' + (1 - sigma) * log(mu * alpha_i + alpha_j) } \deqn{\log(p(j \textrm{beats}
#' i)_k) = \theta_{ijk} + }{log(p(j beats i)_k) = theta_{ijk} +
#' log(alpha_j)}\deqn{ log(\alpha_j)}{log(p(j beats i)_k) = theta_{ijk} +
#' log(alpha_j)} Here \eqn{\theta_{ijk}}{theta_{ijk}} is a structural parameter
#' to fix the trinomial totals; \eqn{\mu}{mu} is the home advantage parameter;
#' \eqn{\alpha_i}{alpha_i} and \eqn{\alpha_j}{alpha_j} are the abilities of
#' players \eqn{i} and \eqn{j} respectively; \eqn{c}{c} is a function of the
#' parameters such that \eqn{\textrm{expit}(\delta)}{plogis(delta)} is the
#' maximum probability of a tie, \eqn{\sigma}{sigma} scales the dependence of
#' the probability of a tie on the relative abilities and \eqn{\pi}{pi} allows
#' for asymmetry in this dependence.
#'
#' For parameters that must be positive (\eqn{\alpha_i, \sigma, \mu}{alpha,
#' sigma, mu}), the log is estimated, while for parameters that must be between
#' zero and one (\eqn{\delta, \pi}), the logit is estimated, as illustrated in
#' the example.
#'
#' @param win a logical vector: `TRUE` if player1 wins, `FALSE`
#' otherwise.
#' @param tie a logical vector: `TRUE` if the outcome is a tie,
#' `FALSE` otherwise.
#' @param loss a logical vector: `TRUE` if player1 loses, `FALSE`
#' otherwise.
#' @param player1 an ID factor specifying the first player in each contest,
#' with the same set of levels as `player2`.
#' @param player2 an ID factor specifying the second player in each contest,
#' with the same set of levels as `player2`.
#' @param home.adv a formula for the parameter corresponding to the home
#' advantage effect. If `NULL`, no home advantage effect is estimated.
#' @param tie.max a formula for the parameter corresponding to the maximum tie
#' probability.
#' @param tie.scale a formula for the parameter corresponding to the scale of
#' dependence of the tie probability on the probability that `player1`
#' wins, given the outcome is not a draw.
#' @param tie.mode a formula for the parameter corresponding to the location of
#' maximum tie probability, in terms of the probability that `player1`
#' wins, given the outcome is not a draw.
#' @param at.home1 a logical vector: `TRUE` if `player1` is at home,
#' `FALSE` otherwise.
#' @param at.home2 a logical vector: `TRUE` if `player2` is at home,
#' `FALSE` otherwise.
#' @return A list with the anticipated components of a "nonlin" function:
#' \item{ predictors }{ the formulae for the different parameters and the ID
#' factors for player 1 and player 2. } \item{ variables }{ the outcome
#' variables and the \dQuote{at home} variables, if specified. } \item{ common
#' }{ an index to specify that common effects are to be estimated for the
#' players. } \item{ term }{ a function to create a deparsed mathematical
#' expression of the term, given labels for the predictors.} \item{ start }{ a
#' function to generate starting values for the parameters.}
#' @author Heather Turner
#' @seealso [football()], [plotProportions()]
#' @references Davidson, R. R. (1970). On extending the Bradley-Terry model to
#' accommodate ties in paired comparison experiments. *Journal of the
#' American Statistical Association*, **65**, 317--328.
#' @keywords models nonlinear
#' @examples
#'
#' ### example requires gnm
#' if (require(gnm)) {
#' ### convert to trinomial counts
#' football.tri <- expandCategorical(football, "result", idvar = "match")
#' head(football.tri)
#'
#' ### add variable to indicate whether team playing at home
#' football.tri$at.home <- !logical(nrow(football.tri))
#'
#' ### fit shifted & scaled Davidson model
#' ### - subset to first and last season for illustration
#' shifScalDav <- gnm(count ~
#' GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1, tie.scale = ~1, tie.mode = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri,
#' subset = season %in% c("2008-9", "2012-13"))
#'
#' ### look at coefs
#' coef <- coef(shifScalDav)
#' ## home advantage
#' exp(coef["home.adv"])
#' ## max p(tie)
#' plogis(coef["tie.max"])
#' ## mode p(tie)
#' plogis(coef["tie.mode"])
#' ## scale relative to Davidson of dependence of p(tie) on p(win|not a draw)
#' exp(coef["tie.scale"])
#'
#' ### check model fit
#' alpha <- names(coef[-(1:4)])
#' plotProportions(result == 1, result == 0, result == -1,
#' home:season, away:season,
#' abilities = coef[alpha], home.adv = coef["home.adv"],
#' tie.max = coef["tie.max"], tie.scale = coef["tie.scale"],
#' tie.mode = coef["tie.mode"],
#' at.home1 = at.home, at.home2 = !at.home,
#' data = football.tri, subset = count == 1)
#' }
#'
#' ### analyse all five seasons
#' ### - takes a little while to run, particularly likelihood ratio tests
#' \dontrun{
#' ### fit Davidson model
#' Dav <- gnm(count ~ GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri)
#'
#' ### fit scaled Davidson model
#' scalDav <- gnm(count ~ GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1, tie.scale = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri)
#'
#' ### fit shifted & scaled Davidson model
#' shifScalDav <- gnm(count ~
#' GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1, tie.scale = ~1, tie.mode = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri)
#'
#' ### compare models
#' anova(Dav, scalDav, shifScalDav, test = "Chisq")
#'
#' ### diagnostic plots
#' main <- c("Davidson", "Scaled Davidson", "Shifted & Scaled Davidson")
#' mod <- list(Dav, scalDav, shifScalDav)
#' names(mod) <- main
#'
#' ## use football.tri data so that at.home can be found,
#' ## but restrict to actual match results
#' par(mfrow = c(2,2))
#' for (i in 1:3) {
#' coef <- parameters(mod[[i]])
#' plotProportions(result == 1, result == 0, result == -1,
#' home:season, away:season,
#' abilities = coef[alpha],
#' home.adv = coef["home.adv"],
#' tie.max = coef["tie.max"],
#' tie.scale = coef["tie.scale"],
#' tie.mode = coef["tie.mode"],
#' at.home1 = at.home,
#' at.home2 = !at.home,
#' main = main[i],
#' data = football.tri, subset = count == 1)
#' }
#' }
#'
#' @importFrom stats coef plogis runif
#' @export
GenDavidson <- function(win, # TRUE/FALSE
tie, # TRUE/FALSE
loss, # TRUE/FALSE
player1, # player1 in each contest
player2, # ditto player2
home.adv = NULL,
tie.max = ~1,
tie.mode = NULL,
tie.scale = NULL,
at.home1 = NULL,
at.home2 = NULL){
call <- as.expression(sys.call()[c(1,5:6)])
extra <- NULL
if (is.null(tie.max)) stop("a formula must be specified for tie.max")
if (!is.null(home.adv) & is.null(at.home1))
stop("at.home1 and at.home2 must be specified")
has.home.adv <- !is.null(home.adv)
has.tie.mode <- !is.null(tie.mode)
has.tie.scale <- !is.null(tie.scale)
if (has.home.adv) extra <- c(extra, list(home.adv = home.adv))
if (has.tie.mode) extra <- c(extra, list(tie.mode = tie.mode))
if (has.tie.scale) extra <- c(extra, list(tie.scale = tie.scale))
i <- has.home.adv + has.tie.mode + has.tie.scale
a <- match("home.adv", names(extra), 1)
b <- match("tie.mode", names(extra), 1)
c <- match("tie.scale", names(extra), 1)
adv <- has.home.adv | has.tie.mode
list(predictors = {c(extra,
list(tie.max = tie.max,
substitute(player1), # player1 & 2 are homogeneous
substitute(player2)))},
## substitutes "result" for "outcome", but also substitutes all of
## code vector
variables = {c(list(loss = substitute(loss),
tie = substitute(tie),
win = substitute(win)),
list(at.home1 = substitute(at.home1),
at.home2 = substitute(at.home2))[adv])},
common = c(1[has.home.adv], 2[has.tie.mode], 3[has.tie.scale],
4, 5, 5),
term = function(predLabels, varLabels){
if (has.home.adv) {
ability1 <- paste("(", predLabels[a], ") * ", varLabels[4],
" + ", predLabels[i + 2], sep = "")
ability2 <- paste("(", predLabels[a], ") * ", varLabels[5],
" + ", predLabels[i + 3], sep = "")
}
else {
ability1 <- predLabels[i + 2]
ability2 <- predLabels[i + 3]
}
tie.scale <- ifelse(has.tie.scale, predLabels[c], 0)
scale <- paste("exp(", tie.scale, ")", sep = "")
if (has.tie.mode) {
psi1 <- paste("exp((", predLabels[b], ") * ", varLabels[4],
")", sep = "")
psi2 <- paste("exp((", predLabels[b], ") * ", varLabels[5],
")", sep = "")
weight1 <- paste(psi1, "/(", psi1, " + ", psi2, ")", sep = "")
weight2 <- paste(psi2, "/(", psi1, " + ", psi2, ")", sep = "")
}
else {
weight1 <- weight2 <- "0.5"
}
nu <- paste(predLabels[i + 1], " - ", scale, " * (",
weight1, " * log(", weight1, ") + ",
weight2, " * log(", weight2, "))", sep = "")
paste(varLabels[1], " * (", ability2, ") + ",
varLabels[2], " * (", nu, " + ",
scale, " * ", weight1, " * (", ability1, ") + ",
scale, " * ", weight2, " * (", ability2, ") + ",
"(1 - ", scale, ") * ",
"log(exp(", ability1, ") + exp(", ability2, "))) + ",
varLabels[3], " * (", ability1, ")", sep = "")
},
start = function(theta) {
init <- runif(length(theta)) - 0.5
init[c] <- 0.5
}
)
}
class(GenDavidson) <- "nonlin"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/GenDavidson.R
|
#' Add or Drop Single Terms to/from a Bradley Terry Model
#'
#' Add or drop single terms within the limit specified by the `scope`
#' argument. For models with no random effects, compute an analysis of deviance
#' table, otherwise compute the Wald statistic of the parameters that have been
#' added to or dropped from the model.
#'
#' The hierarchy is respected when considering terms to be added or dropped:
#' all main effects contained in a second-order interaction must remain, and so
#' on.
#'
#' In a scope formula \samp{.} means \sQuote{what is already there}.
#'
#' For `drop1`, a missing `scope` is taken to mean that all terms in
#' the model may be considered for dropping.
#'
#' If `scope` includes player covariates and there are players with
#' missing values over these covariates, then a separate ability will be
#' estimated for these players in *all* fitted models. Similarly if there
#' are missing values in any contest-level variables in `scope`, the
#' corresponding contests will be omitted from all models.
#'
#' If `formula` includes random effects, the same random effects structure
#' will apply to all models.
#'
#' @aliases add1.BTm drop1.BTm
#' @param object a fitted object of class inheriting from `"BTm"`.
#' @param scope a formula specifying the model including all terms to be
#' considered for adding or dropping.
#' @param scale an estimate of the dispersion. Not implemented for models with
#' random effects.
#' @param test should a p-value be returned? The F test is only appropriate for
#' models with no random effects for which the dispersion has been estimated.
#' The Chisq test is a likelihood ratio test for models with no random effects,
#' otherwise a Wald test.
#' @param x a model matrix containing columns for all terms in the scope.
#' Useful if `add1` is to be called repeatedly. **Warning:** no checks
#' are done on its validity.
#' @param \dots further arguments passed to [add1.glm()].
#' @return An object of class `"anova"` summarizing the differences in fit
#' between the models.
#' @author Heather Turner
#' @seealso [BTm()], [anova.BTm()]
#' @keywords models
#' @examples
#'
#' result <- rep(1, nrow(flatlizards$contests))
#' BTmodel1 <- BTm(result, winner, loser,
#' ~ throat.PC1[..] + throat.PC3[..] + (1|..),
#' data = flatlizards,
#' tol = 1e-4, sigma = 2, trace = TRUE)
#'
#' drop1(BTmodel1)
#'
#' add1(BTmodel1, ~ . + head.length[..] + SVL[..], test = "Chisq")
#'
#' BTmodel2 <- update(BTmodel1, formula = ~ . + head.length[..])
#'
#' drop1(BTmodel2, test = "Chisq")
#'
#' @importFrom stats add.scope coef model.frame model.offset model.response model.weights formula pchisq pf reformulate terms update update.formula vcov
#' @importFrom lme4 findbars nobars
#' @export
add1.BTm <- function(object, scope, scale = 0, test = c("none", "Chisq", "F"),
x = NULL, ...) {
old.form <- formula(object)
new.form <- update.formula(old.form, scope)
if (!is.character(scope)){
orandom <- findbars(old.form[[2]])
srandom <- findbars(new.form[[2]])
if (length(srandom) && !identical(orandom, srandom))
stop("Random effects structure of object and scope must be ",
"identical.")
scope <- add.scope(old.form, new.form)
}
if (!length(scope))
stop("no terms in scope for adding to object")
if (is.null(x)) { # create model.matrix for maximum scope
model <- Diff(object$player1, object$player2, new.form, object$id,
object$data, object$separate.ability, object$refcat)
if (sum(model$offset) > 0)
warning("ignoring offset terms in scope")
x <- model$X
asgn <- attr(x, "assign")
## add dummy term for any separate effects
oTerms <- c("sep"[0 %in% asgn], object$term.labels)
object$terms <- terms(reformulate(oTerms))
y <- object$y
dummy <- y ~ x - 1
if (!is.null(model$random)) {
dummy <- update(dummy, .~ . + Z)
Z <- model$random
}
argPos <- match(c("weights", "subset", "na.action"),
names(object$call), 0)
mf <- as.call(c(model.frame, as.list(object$call)[argPos],
list(formula = dummy, offset = object$offset)))
mf <- eval(mf, parent.frame())
x <- mf$x
y <- model.response(mf)
Z <- mf$Z
wt <- model.weights(mf)
if (is.null(wt)) wt <- rep.int(1, length(y))
offset <- model.offset(mf)
}
else {
asgn <- attr(x, "assign")
y <- object$y
wt <- object$prior.weights
offset <- object$offset
Z <- object$random
}
if (is.null(object$random)){
attr(x, "assign") <- asgn + 1
object$formula <- formula(object$terms)
object$x <- x
object$y <- y
object$random <- Z
object$prior.weights <- wt
object$offset <- offset
stat.table <- NextMethod(x = x)
attr(stat.table, "heading")[3] <- deparse(old.form)
if (newsep <- sum(asgn == 0) - sum(object$assign ==0))
attr(stat.table, "heading") <- c(attr(stat.table, "heading"),
paste("\n", newsep,
" separate effects added\n",
sep = ""))
attr(stat.table, "separate.abilities") <- colnames(x)[asgn == 0]
return(stat.table)
}
## use original term labels: no sep effects or backticks (typically)
oTerms <- attr(terms(nobars(old.form)), "term.labels")
Terms <- attr(terms(nobars(new.form)), "term.labels")
ousex <- asgn %in% c(0, which(Terms %in% oTerms))
sTerms <- vapply(strsplit(Terms, ":", fixed = TRUE),
function(x) paste(sort(x), collapse = ":"),
character(1))
method <- switch(object$method,
glmmPQL.fit)
control <- object$control
control$trace <- FALSE
if (scale == 0) dispersion <- 1
else dispersion <- scale
ns <- length(scope)
stat <- df <- numeric(ns) # don't add in original as don't need for tests
names(stat) <- names(df) <- as.character(scope)
tryerror <- FALSE
for (i in seq(scope)) {
stt <- paste(sort(strsplit(scope[i], ":")[[1]]), collapse = ":")
usex <- match(asgn, match(stt, sTerms), 0) > 0 | ousex
fit <- method(X = x[, usex, drop = FALSE], y = y, Z = Z, weights = wt,
offset = offset, family = object$family,
control = control,
sigma = object$call$sigma,
sigma.fixed = object$sigma.fixed)
class(fit) <- oldClass(object)
ind <- (usex & !ousex)[usex]
trystat <- try(t(coef(fit)[ind]) %*%
chol2inv(chol(vcov(fit, dispersion = dispersion)[ind, ind])) %*%
coef(fit)[ind], silent = TRUE) #vcov should handle disp != 1
if (inherits(trystat, "try-error")) {
stat[i] <- df[i] <- NA
tryerror <- TRUE
}
else {
stat[i] <- trystat
df[i] <- sum(ind)
}
}
table <- data.frame(stat, df)
dimnames(table) <- list(names(df), c("Statistic", "Df"))
title <- "Single term additions\n"
topnote <- paste("Model: ", deparse(as.vector(formula(object))),
if (scale > 0) paste("\nscale: ", format(scale), "\n"),
if (tryerror)
"\n\nTest statistic unestimable for at least one term")
test <- match.arg(test)
if (test == "Chisq") {
dfs <- table[, "Df"]
vals <- table[, "Statistic"]
vals[dfs %in% 0] <- NA
table <- cbind(table, `P(>|Chi|)` = pchisq(vals, abs(dfs),
lower.tail = FALSE))
}
else if (test == "F") {
## Assume dispersion fixed at one - if dispersion estimated, would use
## "residual" df from larger model in each comparison
df.dispersion <- Inf
if (df.dispersion == Inf) {
fam <- object[[1]]$family$family
if (fam == "binomial" || fam == "poisson")
warning(gettextf(
"using F test with a '%s' family is inappropriate",
fam), domain = NA, call. = FALSE)
else {
warning("using F test with a fixed dispersion is inappropriate")
}
}
dfs <- table[, "Df"]
Fvalue <- table[, "Statistic"]/abs(dfs)
Fvalue[dfs %in% 0] <- NA
table <- cbind(table, F = Fvalue, `Pr(>F)` =
pf(Fvalue, abs(dfs), df.dispersion,
lower.tail = FALSE))
}
if (newsep <- sum(asgn == 0) - sum(object$assign ==0))
heading <- c(heading, paste("\n", newsep,
" separate effects added\n",
sep = ""))
structure(table, heading = c(title, topnote),
class = c("anova", "data.frame"),
separate.abilities = colnames(x)[asgn == 0])
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/add1.BTm.R
|
#' Compare Nested Bradley Terry Models
#'
#' Compare nested models inheriting from class `"BTm"`. For models with no
#' random effects, compute analysis of deviance table, otherwise compute Wald
#' tests of additional terms.
#'
#' For models with no random effects, an analysis of deviance table is computed
#' using [anova.glm()]. Otherwise, Wald tests are computed as
#' detailed here.
#'
#' If a single object is specified, terms are added sequentially and a Wald
#' statistic is computed for the extra parameters. If the full model includes
#' player covariates and there are players with missing values over these
#' covariates, then the `NULL` model will include a separate ability for
#' these players. If there are missing values in any contest-level variables in
#' the full model, the corresponding contests will be omitted throughout. The
#' random effects structure of the full model is assumed for all sub-models.
#'
#' For a list of objects, consecutive pairs of models are compared by computing
#' a Wald statistic for the extra parameters in the larger of the two models.
#'
#' The Wald statistic is always based on the variance-covariance matrix of the
#' larger of the two models being compared.
#'
#' @param object a fitted object of class inheriting from `"BTm"`.
#' @param ... additional `"BTm"` objects.
#' @param dispersion a value for the dispersion. Not implemented for models
#' with random effects.
#' @param test optional character string (partially) matching one of
#' `"Chisq"`, `"F"` or `"Cp"` to specify that p-values should be
#' returned. The Chisq test is a likelihood ratio test for models with no
#' random effects, otherwise a Wald test. Options `"F"` and `"Cp"`
#' are only applicable to models with no random effects, see
#' [stat.anova()].
#' @return An object of class `"anova"` inheriting from class
#' `"data.frame"`.
#' @section Warning: The comparison between two or more models will only be
#' valid if they are fitted to the same dataset. This may be a problem if there
#' are missing values and 's default of `na.action = na.omit` is used. An
#' error will be returned in this case.
#'
#' The same problem will occur when separate abilities have been estimated for
#' different subsets of players in the models being compared. However no
#' warning is given in this case.
#' @author Heather Turner
#' @seealso [BTm()], [add1.BTm()]
#' @keywords models
#' @examples
#'
#' result <- rep(1, nrow(flatlizards$contests))
#' BTmodel <- BTm(result, winner, loser, ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + (1|..), data = flatlizards,
#' trace = TRUE)
#' anova(BTmodel)
#'
#' @export
anova.BTm <- function (object, ..., dispersion = NULL, test = NULL)
{
## Only list models in ...
dotargs <- list(...)
named <- if (is.null(names(dotargs)))
rep(FALSE, length(dotargs))
else (names(dotargs) != "")
if (any(named))
warning("the following arguments to 'anova.BTm' are invalid and ",
"dropped: ",
paste(deparse(dotargs[named]), collapse = ", "))
dotargs <- dotargs[!named]
is.BTm <- unlist(lapply(dotargs, function(x) inherits(x, "BTm")))
dotargs <- dotargs[is.BTm]
## Compare list of models
models <- c(list(object), dotargs)
if (length(dotargs) > 0){
fixed <- unlist(lapply(models, function(x) is.null(x$random)))
if (all(fixed)) {
variables <- lapply(models, function(x) paste(deparse(formula(x)),
collapse = "\n"))
models <- lapply(models, function(x) {
x$formula <- formula(x$terms)
class(x) <- setdiff(class(x), "BTm")
x})
call <- match.call()
anova.table <- do.call("anova",
c(models, dispersion = call$dispersion,
test = call$test))
attr(anova.table, "heading") <-
c(paste("Analysis of Deviance Table\n\n",
"Response: ",
deparse(object$call$outcome, 500), "\n", sep = ""),
paste("Model ", format(seq(models)), ": ", variables,
sep = "", collapse = "\n"))
return(anova.table)
}
else
return(anova.BTmlist(c(list(object), dotargs),
dispersion = dispersion, test = test))
}
X <- model.matrix(object)
Z <- object$random
sep <- 0 %in% object$assign
## Passing on to glm when no random effects
if (is.null(Z)) {
object$x <- X
attr(object$x, "assign") <- object$assign + sep
attr(object$terms, "term.labels") <- c("[sep]"[sep], object$term.labels)
anova.table <- NextMethod()
attr(anova.table, "heading") <-
paste("Analysis of Deviance Table", "\n\nModel: ",
object$family$family, ", link: ", object$family$link,
"\n\nResponse: ", deparse(object$call$outcome, 500),
"\n\nTerms added sequentially (first to last)\n\n",
sep = "")
if (sep) {
anova.table <- anova.table[-1,]
rownames(anova.table)[1] <- "NULL"
anova.table[1, 1:2] <- NA
}
return(anova.table)
}
varseq <- object$assign
nvars <- max(0, varseq)
stat <- df <- numeric(nvars)
tryerror <- FALSE
if (nvars > 1) {
y <- object$y
## Extension to further methods
method <- object$method
if (!is.function(method))
method <- get(method, mode = "function")
control <- object$control
control$trace <- FALSE
for (i in 1:(nvars - 1)) {
fit <- method(X = X[, varseq <= i, drop = FALSE], y = y, Z = Z,
weights = object$prior.weights, start = object$start,
offset = object$offset, family = object$family,
control = control,
sigma = object$call$sigma,
sigma.fixed = object$sigma.fixed)
class(fit) <- oldClass(object)
ind <- (varseq == i)[varseq <= i]
trystat <-
try(t(coef(fit)[ind]) %*%
chol2inv(chol(suppressMessages(
#vcov should deal with dispersion != 1
vcov(fit, dispersion = dispersion))[ind, ind])) %*%
coef(fit)[ind], silent = TRUE)
if (inherits(trystat, "try-error")) {
stat[i] <- df[i] <- NA
tryerror <- TRUE
}
else {
stat[i] <- trystat
df[i] <- sum(ind)
}
}
}
ind <- varseq == nvars
trystat <- try(t(coef(object)[ind]) %*%
chol2inv(chol(object$varFix[ind, ind])) %*%
coef(object)[ind], silent = TRUE)
if (inherits(trystat, "try-error")) {
stat[nvars] <- df[nvars] <- NA
tryerror <- TRUE
}
else {
stat[nvars] <- trystat
df[nvars] <- sum(ind)
}
table <- data.frame(c(NA, stat), c(NA, df))
dimnames(table) <- list(c("NULL", object$term.labels), c("Statistic", "Df"))
title <- paste("Sequential Wald Tests", "\n\nModel: ",
object$family$family, ", link: ", object$family$link,
"\n\nResponse: ", deparse(object$call$outcome, 500),
"\n\nPredictor: ", paste(formula(object), collapse = ""),
"\n\nTerms added sequentially (first to last)",
if (tryerror)
"\n\nTest statistic unestimable for at least one term",
"\n", sep = "")
## Assume dispersion fixed at one - if dispersion estimated, would use
## "residual" df from larger model in each comparison
df.dispersion <- Inf
if (!is.null(test)) {
if (test == "F" && df.dispersion == Inf) {
fam <- object$family$family
if (fam == "binomial" || fam == "poisson")
warning(gettextf("using F test with a %s family is ",
"inappropriate", fam), domain = NA)
else {
warning("using F test with a fixed dispersion is inappropriate")
}
}
table <- switch(test, Chisq = {
dfs <- table[, "Df"]
vals <- table[, "Statistic"]
vals[dfs %in% 0] <- NA
cbind(table, `P(>|Chi|)` = pchisq(vals, dfs, lower.tail = FALSE))
}, F = {
dfs <- table[, "Df"]
Fvalue <- table[, "Statistic"]/dfs
Fvalue[dfs %in% 0] <- NA
cbind(table, F = Fvalue, `Pr(>F)` =
pf(Fvalue, dfs, df.dispersion, lower.tail = FALSE))
})
}
structure(table, heading = title, class = c("anova", "data.frame"))
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/anova.BTm.R
|
#' @importFrom stats coef fitted formula na.omit pchisq pf terms vcov
anova.BTmlist <- function (object, ..., dispersion = NULL, test = NULL) {
## Pass on if no random effects
fixed <- unlist(lapply(object, function(x) is.null(x$random)))
if (!all(!fixed))
stop("Models must have the same random effects structure")
responses <- as.character(lapply(object, function(x) {
deparse(formula(terms(x))[[2]])
}))
sameresp <- responses == responses[1]
if (!all(sameresp)) {
object <- object[sameresp]
warning("models with response ", deparse(responses[!sameresp]),
" removed because response differs from model 1")
}
ns <- vapply(object, function(x) length(fitted(x)), numeric(1))
if (any(ns != ns[1]))
stop("models were not all fitted to the same size of dataset")
nmodels <- length(object)
ncoefs <- vapply(object, function(x) length(na.omit(coef(x))),
numeric(1)) #omit aliased
labels <- lapply(object, function(x) x$term.labels)
stat <- numeric(nmodels)
for (i in 2:nmodels) {
descending <- ncoefs[i] < ncoefs[i - 1]
bigger <- i - descending
smaller <- i - !descending
if (!all(labels[[smaller]] %in% labels[[bigger]]))
stop("models are not nested")
term.ind <- !(labels[[bigger]] %in% labels[[smaller]])
ind <- object[[bigger]]$assign %in% which(term.ind)
stat[i] <- t(coef(object[[bigger]])[ind]) %*%
chol2inv(chol(vcov(object[[bigger]],
dispersion = dispersion)[ind, ind])) %*%
coef(object[[bigger]])[ind] #vcov should handle dispersion != 1
}
stat[1] <- NA
table <- data.frame(stat, c(NA, diff(ncoefs)))
variables <- lapply(object, function(x) paste(deparse(formula(x)),
collapse = "\n"))
dimnames(table) <- list(1:nmodels, c("Statistic", "Df"))
title <- paste("Sequential Wald Tests\n\n",
"Response: ", responses[1], "\n", sep = "")
topnote <- paste("Model ", format(1:nmodels), ": ", variables,
sep = "", collapse = "\n")
if (!is.null(test)) {
## Assume dispersion fixed at one - if dispersion estimated, would use
## "residual" df from larger model in each comparison
df.dispersion <- Inf
if (test == "F" && df.dispersion == Inf) {
fam <- object[[1]]$family$family
if (fam == "binomial" || fam == "poisson")
warning(gettextf(
"using F test with a '%s' family is inappropriate",
fam), domain = NA, call. = FALSE)
else {
warning("using F test with a fixed dispersion is inappropriate")
}
}
table <- switch(test, Chisq = {
dfs <- table[, "Df"]
vals <- table[, "Statistic"]
vals[dfs %in% 0] <- NA
cbind(table,
`P(>|Chi|)` = pchisq(vals, abs(dfs), lower.tail = FALSE))
}, F = {
dfs <- table[, "Df"]
Fvalue <- table[, "Statistic"]/abs(dfs)
Fvalue[dfs %in% 0] <- NA
cbind(table, F = Fvalue, `Pr(>F)` =
pf(Fvalue, abs(dfs), df.dispersion, lower.tail = FALSE))
})
}
structure(table, heading = c(title, topnote), class = c("anova",
"data.frame"))
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/anova.BTmlist.R
|
#' Baseball Data from Agresti (2002)
#'
#' Baseball results for games in the 1987 season between 7 teams in the Eastern
#' Division of the American League.
#'
#'
#' @name baseball
#' @docType data
#' @format A data frame with 42 observations on the following 4 variables.
#' \describe{
#' \item{home.team}{a factor with levels `Baltimore`,
#' `Boston`, `Cleveland`, `Detroit`, `Milwaukee`, `New York`, `Toronto`.}
#' \item{away.team}{a factor with levels
#' `Baltimore`, `Boston`, `Cleveland`, `Detroit`,
#' `Milwaukee`, `New York`, `Toronto`.}
#' \item{home.wins}{a numeric vector.}
#' \item{away.wins}{a numeric vector.} }
#' @note This dataset is in a simpler format than the one described in Firth
#' (2005).
#' @seealso [BTm()]
#' @references Firth, D. (2005) Bradley-Terry models in R. *Journal of
#' Statistical Software*, **12**(1), 1--12.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#' @source Page 438 of Agresti, A. (2002) *Categorical Data Analysis* (2nd
#' Edn.). New York: Wiley.
#' @keywords datasets
#' @examples
#'
#' ## This reproduces the analysis in Sec 10.6 of Agresti (2002).
#' data(baseball) # start with baseball data as provided by package
#'
#' ## Simple Bradley-Terry model, ignoring home advantage:
#' baseballModel1 <- BTm(cbind(home.wins, away.wins), home.team, away.team,
#' data = baseball, id = "team")
#'
#' ## Now incorporate the "home advantage" effect
#' baseball$home.team <- data.frame(team = baseball$home.team, at.home = 1)
#' baseball$away.team <- data.frame(team = baseball$away.team, at.home = 0)
#' baseballModel2 <- update(baseballModel1, formula = ~ team + at.home)
#'
#' ## Compare the fit of these two models:
#' anova(baseballModel1, baseballModel2)
#'
#'
"baseball"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/baseball.R
|
#' Male Cape Dwarf Chameleons: Measured Traits and Contest Outcomes
#'
#' Data as used in the study by Stuart-Fox et al. (2006). Physical
#' measurements made on 35 male Cape dwarf chameleons, and the results of 106
#' inter-male contests.
#'
#' The published paper mentions 107 contests, but only 106 contests are
#' included here. Contest number 16 was deleted from the data used to fit the
#' models, because it involved a male whose predictor-variables were incomplete
#' (and it was the only contest involving that lizard, so it is uninformative).
#'
#' @name chameleons
#' @docType data
#' @format A list containing three data frames: `chameleons$winner`,
#' `chameleons$loser` and `chameleons$predictors`.
#'
#' The `chameleons$winner` and `chameleons$loser` data frames each
#' have 106 observations (one per contest) on the following 4 variables:
#' \describe{
#' \item{ID}{a factor with 35 levels `C01`, `C02`,
#' ... , `C43`, the identity of the winning (or losing) male in each
#' contest}
#' \item{prev.wins.1}{integer (values 0 or 1), did the
#' winner/loser of this contest win in an immediately previous contest?}
#' \item{prev.wins.2}{integer (values 0, 1 or 2), how many of his
#' (maximum) previous 2 contests did each male win?}
#' \item{prev.wins.all}{integer, how many previous contests has each
#' male won?} }
#'
#' The `chameleons$predictors` data frame has 35 observations, one for
#' each male involved in the contests, on the following 7 variables:
#' \describe{
#' \item{ch.res}{numeric, residuals of casque height regression on
#' `SVL`, i.e. relative height of the bony part on the top of the
#' chameleons' heads}
#' \item{jl.res}{numeric, residuals of jaw length
#' regression on `SVL`}
#' \item{tl.res}{numeric, residuals of tail
#' length regression on `SVL`}
#' \item{mass.res}{numeric, residuals
#' of body mass regression on `SVL` (body condition)}
#' \item{SVL}{numeric, snout-vent length (body size)}
#' \item{prop.main}{numeric, proportion (arcsin transformed) of area of
#' the flank occupied by the main pink patch on the flank}
#' \item{prop.patch}{numeric, proportion (arcsin transformed) of area
#' of the flank occupied by the entire flank patch} }
#' @author David Firth
#' @source The data were obtained by Dr Devi Stuart-Fox,
#' \url{https://devistuartfox.com/},
#' and they are reproduced here with her kind permission.
#'
#' These are the same data that were used in
#'
#' Stuart-Fox, D. M., Firth, D., Moussalli, A. and Whiting, M. J. (2006)
#' Multiple signals in chameleon contests: designing and analysing animal
#' contests as a tournament. *Animal Behaviour* **71**, 1263--1271.
#' @keywords datasets
#' @examples
#'
#' ##
#' ## Reproduce Table 3 from page 1268 of the above paper:
#' ##
#' summary(chameleon.model <- BTm(player1 = winner, player2 = loser,
#' formula = ~ prev.wins.2 + ch.res[ID] + prop.main[ID] + (1|ID), id = "ID",
#' data = chameleons))
#' head(BTabilities(chameleon.model))
#' ##
#' ## Note that, although a per-chameleon random effect is specified as in the
#' ## above [the term "+ (1|ID)"], the estimated variance for that random
#' ## effect turns out to be zero in this case. The "prior experience"
#' ## effect ["+ prev.wins.2"] in this analysis has explained most of the
#' ## variation, leaving little for the ID-specific predictors to do.
#' ## Despite that, two of the ID-specific predictors do emerge as
#' ## significant.
#' ##
#' ## Test whether any of the other ID-specific predictors has an effect:
#' ##
#' add1(chameleon.model, ~ . + jl.res[ID] + tl.res[ID] + mass.res[ID] +
#' SVL[ID] + prop.patch[ID])
#'
"chameleons"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/chameleons.R
|
#' Statistics Journal Citation Data from Stigler (1994)
#'
#' Extracted from a larger table in Stigler (1994). Inter-journal citation
#' counts for four journals, \dQuote{Biometrika}, \dQuote{Comm Statist.},
#' \dQuote{JASA} and \dQuote{JRSS-B}, as used on p448 of Agresti (2002).
#'
#' In the context of paired comparisons, the \sQuote{winner} is the cited
#' journal and the \sQuote{loser} is the one doing the citing.
#'
#' @name citations
#' @docType data
#' @format A 4 by 4 contingency table of citations, cross-classified by the
#' factors `cited` and `citing` each with levels `Biometrika`,
#' `Comm Statist`, `JASA`, and `JRSS-B`.
#' @seealso [BTm()]
#' @references Firth, D. (2005) Bradley-Terry models in R. *Journal of
#' Statistical Software* **12**(1), 1--12.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#'
#' Stigler, S. (1994) Citation patterns in the journals of statistics and
#' probability. *Statistical Science* **9**, 94--108.
#' @source Agresti, A. (2002) *Categorical Data Analysis* (2nd ed). New
#' York: Wiley.
#' @keywords datasets
#' @examples
#'
#' ## Data as a square table, as in Agresti p448
#' citations
#'
#' ##
#' ## Convert frequencies to success/failure data:
#' ##
#' citations.sf <- countsToBinomial(citations)
#' names(citations.sf)[1:2] <- c("journal1", "journal2")
#'
#' ## Standard Bradley-Terry model fitted to these data
#' citeModel <- BTm(cbind(win1, win2), journal1, journal2,
#' data = citations.sf)
#'
"citations"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/citations.R
|
#' Convert Contingency Table of Wins to Binomial Counts
#'
#' Convert a contingency table of wins to a four-column data frame containing
#' the number of wins and losses for each pair of players.
#'
#'
#' @param xtab a contingency table of wins cross-classified by \dQuote{winner}
#' and \dQuote{loser}
#' @return A data frame with four columns \item{player1 }{ the first player in
#' the contest. } \item{player2 }{ the second player in the contest. }
#' \item{win1 }{ the number of times `player1` won. } \item{win2 }{ the
#' number of times `player2` won. }
#' @author Heather Turner
#' @seealso [BTm()]
#' @keywords models
#' @examples
#'
#' ########################################################
#' ## Statistics journal citation data from Stigler (1994)
#' ## -- see also Agresti (2002, p448)
#' ########################################################
#' citations
#'
#' ## Convert frequencies to success/failure data
#' citations.sf <- countsToBinomial(citations)
#' names(citations.sf)[1:2] <- c("journal1", "journal2")
#' citations.sf
#'
#' @importFrom gtools combinations
#' @export
countsToBinomial <- function(xtab) {
## make square if necessary
if (nrow(xtab) != ncol(xtab) || !all(rownames(xtab) == colnames(xtab))) {
dat <- as.data.frame(xtab)
lev <- union(rownames(xtab), colnames(xtab))
dat[,1] <- factor(dat[,1], levels = lev)
dat[,2] <- factor(dat[,2], levels = lev)
xtab <- tapply(dat[,3], dat[1:2], sum)
xtab[is.na(xtab)] <- 0
}
##assumes square
players <- rownames(xtab)
comb <- combinations(nrow(xtab), 2)
won <- xtab[comb]
lost <- t(xtab)[comb]
res <- !(won == 0 & lost == 0)
player1 <- factor(players[comb[,1]], levels = players)[res]
player2 <- factor(players[comb[,2]], levels = players)[res]
data.frame(player1, player2, win1 = won[res], win2 = lost[res])
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/countsToBinomial.R
|
#' @importFrom stats coef drop.scope model.matrix formula pchisq pf terms update.formula vcov
#' @export
drop1.BTm <- function(object, scope, scale = 0, test = c("none", "Chisq", "F"),
...) {
x <- model.matrix(object)
## Pass on if no random effects
if (is.null(object$random)){
object$x <- x
attr(object$x, "assign") <- object$assign
object$terms <- terms(object$formula)
return(NextMethod())
}
form <- formula(object)
if (missing(scope))
scope <- drop.scope(nobars(form))
else {
if (!is.character(scope)) {
srandom <- findbars(scope[[2]])
if (length(srandom))
stop("Scope should not include random effects.")
scope <- attr(terms(update.formula(form, scope)),
"term.labels")
}
if (!all(match(scope, terms(form), 0L) > 0L))
stop("scope is not a subset of term labels")
}
asgn <- object$assign
coefs <- coef(object)
if (scale == 0) dispersion <- 1
else dispersion <- scale
vc <- vcov(object, dispersion = dispersion) #vcov should handle disp != 1
sTerms <- vapply(strsplit(scope, ":", fixed = TRUE),
function(x) paste(sort(x), collapse = ":"),
character(1))
stat <- df <- numeric(length(scope))
names(stat) <- names(df) <- as.character(lapply(scope, as.name))
tryerror <- FALSE
for (i in seq(scope)) {
stt <- paste(sort(strsplit(scope[i], ":")[[1]]), collapse = ":")
usex <- match(asgn, match(stt, sTerms), 0) > 0
trystat <- try(t(coefs[usex]) %*% chol2inv(chol(vc[usex, usex])) %*%
coefs[usex], silent = TRUE)
if (inherits(trystat, "try-error")) {
stat[i] <- df[i] <- NA
tryerror <- TRUE
}
else {
stat[i] <- trystat
df[i] <- sum(usex)
}
}
table <- data.frame(stat, df)
dimnames(table) <- list(names(df), c("Statistic", "Df"))
title <- "Single term deletions\n"
topnote <- gsub("\\s+", " ", paste("Model: ",
paste(deparse(as.vector(formula(object))),
collapse = ""),
if (scale > 0) paste("\nscale: ", format(scale), "\n"),
if (tryerror)
"\n\nTest statistic unestimable for at least one term"),
perl = TRUE)
test <- match.arg(test)
if (test == "Chisq") {
dfs <- table[, "Df"]
vals <- table[, "Statistic"]
vals[dfs %in% 0] <- NA
table <- cbind(table, `P(>|Chi|)` = pchisq(vals, abs(dfs),
lower.tail = FALSE))
}
else if (test == "F") {
## Assume dispersion fixed at one - if dispersion estimated, would use
## "residual" df from larger model in each comparison
df.dispersion <- Inf
if (df.dispersion == Inf) {
fam <- object[[1]]$family$family
if (fam == "binomial" || fam == "poisson")
warning(gettextf("using F test with a '%s' family is ",
"inappropriate",
fam), domain = NA, call. = FALSE)
else {
warning("using F test with a fixed dispersion is inappropriate")
}
}
dfs <- table[, "Df"]
Fvalue <- table[, "Statistic"]/abs(dfs)
Fvalue[dfs %in% 0] <- NA
table <- cbind(table, F = Fvalue, `Pr(>F)` =
pf(Fvalue, abs(dfs), df.dispersion,
lower.tail = FALSE))
}
structure(table, heading = c(title, topnote), class = c("anova",
"data.frame"))
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/drop1.BTm.R
|
#' Augrabies Male Flat Lizards: Contest Results and Predictor Variables
#'
#' Data collected at Augrabies Falls National Park (South Africa) in
#' September-October 2002, on the contest performance and background attributes
#' of 77 male flat lizards (*Platysaurus broadleyi*). The results of
#' exactly 100 contests were recorded, along with various measurements made on
#' each lizard. Full details of the study are in Whiting et al. (2006).
#'
#' There were no duplicate contests (no pair of lizards was seen fighting more
#' than once), and there were no tied contests (the result of each contest was
#' clear).
#'
#' The variables `head.length`, `head.width`, `head.height` and
#' `condition` were all computed as residuals (of directly measured head
#' length, head width, head height and body mass index, respectively) from
#' simple least-squares regressions on `SVL`.
#'
#' Values of some predictors are missing (`NA`) for some lizards,
#' \sQuote{at random}, because of instrument problems unconnected with the
#' value of the measurement being made.
#'
#' @name flatlizards
#' @docType data
#' @format This dataset is a list containing two data frames:
#' `flatlizards$contests` and `flatlizards$predictors`.
#'
#' The `flatlizards$contests` data frame has 100 observations on the
#' following 2 variables: \describe{
#' \item{winner}{a factor with 77
#' levels `lizard003` ... `lizard189`.}
#' \item{loser}{a factor
#' with the same 77 levels `lizard003` ... `lizard189`.} }
#'
#' The `flatlizards$predictors` data frame has 77 observations (one for
#' each of the 77 lizards) on the following 18 variables: \describe{
#' \item{id}{factor with 77 levels (3 5 6 ... 189), the lizard
#' identifiers.}
#' \item{throat.PC1}{numeric, the first principal
#' component of the throat spectrum.}
#' \item{throat.PC2}{numeric, the
#' second principal component of the throat spectrum.}
#' \item{throat.PC3}{numeric, the third principal component of the
#' throat spectrum.}
#' \item{frontleg.PC1}{numeric, the first principal
#' component of the front-leg spectrum.}
#' \item{frontleg.PC2}{numeric,
#' the second principal component of the front-leg spectrum.}
#' \item{frontleg.PC3}{numeric, the third principal component of the
#' front-leg spectrum.}
#' \item{badge.PC1}{numeric, the first principal
#' component of the ventral colour patch spectrum.}
#' \item{badge.PC2}{numeric, the second principal component of the
#' ventral colour patch spectrum.}
#' \item{badge.PC3}{numeric, the third
#' principal component of the ventral colour patch spectrum.}
#' \item{badge.size}{numeric, a measure of the area of the ventral
#' colour patch.}
#' \item{testosterone}{numeric, a measure of blood
#' testosterone concentration.}
#' \item{SVL}{numeric, the snout-vent
#' length of the lizard.}
#' \item{head.length}{numeric, head length.}
#' \item{head.width}{numeric, head width.}
#' \item{head.height}{numeric, head height.}
#' \item{condition}{numeric, a measure of body condition.}
#' \item{repro.tactic}{a factor indicating reproductive tactic; levels
#' are `resident` and `floater`.} }
#' @seealso [BTm()]
#' @references Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The
#' BradleyTerry2 package. *Journal of Statistical Software*,
#' **48**(9), 1--21.
#'
#' Whiting, M. J., Stuart-Fox, D. M., O'Connor, D., Firth, D., Bennett, N. C.
#' and Blomberg, S. P. (2006). Ultraviolet signals ultra-aggression in a
#' lizard. *Animal Behaviour* **72**, 353--363.
#' @source The data were collected by Dr Martin Whiting,
#' \url{http://whitinglab.com/people/martin-whiting/}, and they appear here
#' with his kind permission.
#' @keywords datasets
#' @examples
#'
#' ##
#' ## Fit the standard Bradley-Terry model, using the bias-reduced
#' ## maximum likelihood method:
#' ##
#' result <- rep(1, nrow(flatlizards$contests))
#' BTmodel <- BTm(result, winner, loser, br = TRUE, data = flatlizards$contests)
#' summary(BTmodel)
#' ##
#' ## That's fairly useless, though, because of the rather small
#' ## amount of data on each lizard. And really the scientific
#' ## interest is not in the abilities of these particular 77
#' ## lizards, but in the relationship between ability and the
#' ## measured predictor variables.
#' ##
#' ## So next fit (by maximum likelihood) a "structured" B-T model in
#' ## which abilities are determined by a linear predictor.
#' ##
#' ## This reproduces results reported in Table 1 of Whiting et al. (2006):
#' ##
#' Whiting.model <- BTm(result, winner, loser,
#' ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..],
#' data = flatlizards)
#' summary(Whiting.model)
#' ##
#' ## Equivalently, fit the same model using glmmPQL:
#' ##
#' Whiting.model <- BTm(result, winner, loser,
#' ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..] + (1|..),
#' sigma = 0, sigma.fixed = TRUE, data = flatlizards)
#' summary(Whiting.model)
#' ##
#' ## But that analysis assumes that the linear predictor formula for
#' ## abilities is _perfect_, i.e., that there is no error in the linear
#' ## predictor. This will always be unrealistic.
#' ##
#' ## So now fit the same predictor but with a normally distributed error
#' ## term --- a generalized linear mixed model --- by using the BTm
#' ## function instead of glm.
#' ##
#' Whiting.model2 <- BTm(result, winner, loser,
#' ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..] + (1|..),
#' data = flatlizards, trace = TRUE)
#' summary(Whiting.model2)
#' ##
#' ## The estimated coefficients (of throat.PC1, throat.PC3,
#' ## head.length and SVL are not changed substantially by
#' ## the recognition of an error term in the model; but the estimated
#' ## standard errors are larger, as expected. The main conclusions from
#' ## Whiting et al. (2006) are unaffected.
#' ##
#' ## With the normally distributed random error included, it is perhaps
#' ## at least as natural to use probit rather than logit as the link
#' ## function:
#' ##
#' require(stats)
#' Whiting.model3 <- BTm(result, winner, loser,
#' ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..] + (1|..),
#' family = binomial(link = "probit"),
#' data = flatlizards, trace = TRUE)
#' summary(Whiting.model3)
#' BTabilities(Whiting.model3)
#' ## Note the "separate" attribute here, identifying two lizards with
#' ## missing values of at least one predictor variable
#' ##
#' ## Modulo the usual scale change between logit and probit, the results
#' ## are (as expected) very similar to Whiting.model2.
#'
"flatlizards"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/flatlizards.R
|
#' English Premier League Football Results 2008/9 to 2012/13
#'
#' The win/lose/draw results for five seasons of the English Premier League
#' football results, from 2008/9 to 2012/13
#'
#' In each season, there are 20 teams, each of which plays one home game and
#' one away game against all the other teams in the league. The results in 380
#' games per season.
#'
#' @name football
#' @docType data
#' @format A data frame with 1881 observations on the following 4 variables.
#' \describe{
#' \item{season}{a factor with levels `2008-9`,
#' `2009-10`, `2010-11`, `2011-12`, `2012-13`}
#' \item{home}{a factor specifying the home team, with 29 levels
#' `Ars` (Arsenal), ... , `Wol` (Wolverhampton)}
#' \item{away}{a factor specifying the away team, with the same levels
#' as `home`.}
#' \item{result}{a numeric vector giving the result
#' for the home team: 1 for a win, 0 for a draw, -1 for a loss.} }
#' @seealso [GenDavidson()]
#' @references Davidson, R. R. (1970). On extending the Bradley-Terry model to
#' accommodate ties in paired comparison experiments. *Journal of the
#' American Statistical Association*, **65**, 317--328.
#' @source These data were downloaded from http://soccernet.espn.go.com in
#' 2013. The site has since moved and the new site does not appear to have an
#' equivalent source.
#' @keywords datasets
#' @examples
#'
#' ### example requires gnm
#' if (require(gnm)) {
#' ### convert to trinomial counts
#' football.tri <- expandCategorical(football, "result", idvar = "match")
#' head(football.tri)
#'
#' ### add variable to indicate whether team playing at home
#' football.tri$at.home <- !logical(nrow(football.tri))
#'
#' ### fit Davidson model for ties
#' ### - subset to first and last season for illustration
#' Davidson <- gnm(count ~
#' GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season,
#' home.adv = ~1, tie.max = ~1,
#' at.home1 = at.home, at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri,
#' subset = season %in% c("2008-9", "2012-13"))
#'
#' ### see ?GenDavidson for further analysis
#' }
#'
"football"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/football.R
|
#' @export
formula.BTm <- function(x, ...) x$formula
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/formula.BTm.R
|
#' PQL Estimation of Generalized Linear Mixed Models
#'
#' Fits GLMMs with simple random effects structure via Breslow and Clayton's
#' PQL algorithm.
#' The GLMM is assumed to be of the form \ifelse{html}{\out{g(<b>μ</b>) =
#' <b>Xβ</b> + <b>Ze</b>}}{\deqn{g(\boldsymbol{\mu}) = \boldsymbol{X\beta}
#' + \boldsymbol{Ze}}{ g(mu) = X * beta + Z * e}} where \eqn{g} is the link
#' function, \ifelse{html}{\out{<b>μ</b>}}{\eqn{\boldsymbol{\mu}}{mu}} is the
#' vector of means and \ifelse{html}{\out{<b>X</b>, <b>Z</b>}}{\eqn{\boldsymbol{X},
#' \boldsymbol{Z}}{X,Z}} are design matrices for the fixed effects
#' \ifelse{html}{\out{<b>β</b>}}{\eqn{\boldsymbol{\beta}}{beta}} and random
#' effects \ifelse{html}{\out{<b>e</b>}}{\eqn{\boldsymbol{e}}{e}} respectively.
#' Furthermore the random effects are assumed to be i.i.d.
#' \ifelse{html}{\out{N(0, σ<sup>2</sup>)}}{\eqn{N(0, \sigma^2)}{
#' N(0, sigma^2)}}.
#'
#' @param fixed a formula for the fixed effects.
#' @param random a design matrix for the random effects, with number of rows
#' equal to the length of variables in `formula`.
#' @param family a description of the error distribution and link function to
#' be used in the model. This can be a character string naming a family
#' function, a family function or the result of a call to a family function.
#' (See [family()] for details of family functions.)
#' @param data an optional data frame, list or environment (or object coercible
#' by [as.data.frame()] to a data frame) containing the variables in
#' the model. If not found in `data`, the variables are taken from
#' `environment(formula)`, typically the environment from which
#' `glmmPQL` called.
#' @param subset an optional logical or numeric vector specifying a subset of
#' observations to be used in the fitting process.
#' @param weights an optional vector of \sQuote{prior weights} to be used in
#' the fitting process.
#' @param offset an optional numeric vector to be added to the linear predictor
#' during fitting. One or more `offset` terms can be included in the
#' formula instead or as well, and if more than one is specified their sum is
#' used. See [model.offset()].
#' @param na.action a function which indicates what should happen when the data
#' contain `NA`s. The default is set by the `na.action` setting of
#' [options()], and is [na.fail()] if that is unset.
#' @param start starting values for the parameters in the linear predictor.
#' @param etastart starting values for the linear predictor.
#' @param mustart starting values for the vector of means.
#' @param control a list of parameters for controlling the fitting process.
#' See the [glmmPQL.control()] for details.
#' @param sigma a starting value for the standard deviation of the random
#' effects.
#' @param sigma.fixed logical: whether or not the standard deviation of the
#' random effects should be fixed at its starting value.
#' @param model logical: whether or not the model frame should be returned.
#' @param x logical: whether or not the design matrix for the fixed effects
#' should be returned.
#' @param contrasts an optional list. See the `contrasts.arg` argument of
#' [model.matrix()].
#' @param \dots arguments to be passed to [glmmPQL.control()].
#' @return An object of class `"BTglmmPQL"` which inherits from
#' `"glm"` and `"lm"`: \item{coefficients}{ a named vector of
#' coefficients, with a `"random"` attribute giving the estimated random
#' effects.} \item{residuals}{ the working residuals from the final iteration
#' of the IWLS loop.} \item{random}{the design matrix for the random effects.}
#' \item{fitted.values}{ the fitted mean values, obtained by transforming the
#' linear predictors by the inverse of the link function.} \item{rank}{the
#' numeric rank of the fitted linear model.} \item{family}{the `family`
#' object used.} \item{linear.predictors}{the linear fit on link scale.}
#' \item{deviance}{up to a constant, minus twice the maximized log-likelihood.}
#' \item{aic}{a version of Akaike's *An Information Criterion*, minus
#' twice the maximized log-likelihood plus twice the number of parameters,
#' computed by the `aic` component of the family.}
#' \item{null.deviance}{the deviance for the null model, comparable with
#' `deviance`.} \item{iter}{the numer of iterations of the PQL algorithm.}
#' \item{weights}{the working weights, that is the weights in the final
#' iteration of the IWLS loop.} \item{prior.weights}{the weights initially
#' supplied, a vector of `1`'s if none were.} \item{df.residual}{the
#' residual degrees of freedom.} \item{df.null}{the residual degrees of freedom
#' for the null model.} \item{y}{if requested (the default) the `y` vector
#' used. (It is a vector even for a binomial model.)} \item{x}{if requested,
#' the model matrix.} \item{model}{if requested (the default), the model
#' frame.} \item{converged}{logical. Was the PQL algorithm judged to have
#' converged?} \item{call}{the matched call.} \item{formula}{the formula
#' supplied.} \item{terms}{the `terms` object used.} \item{data}{the
#' `data` argument used.} \item{offset}{the offset vector used.}
#' \item{control}{the value of the `control` argument used.}
#' \item{contrasts}{(where relevant) the contrasts used.} \item{xlevels}{(where
#' relevant) a record of the levels of the factors used in fitting.}
#' \item{na.action}{(where relevant) information returned by `model.frame`
#' on the special handling of `NA`s.} \item{sigma}{the estimated standard
#' deviation of the random effects} \item{sigma.fixed}{logical: whether or not
#' `sigma` was fixed} \item{varFix}{the variance-covariance matrix of the
#' fixed effects} \item{varSigma}{the variance of `sigma`}
#' @author Heather Turner
#' @seealso
#' [predict.BTglmmPQL()],[glmmPQL.control()],[BTm()]
#' @references Breslow, N. E. and Clayton, D. G. (1993) Approximate inference
#' in Generalized Linear Mixed Models. *Journal of the American
#' Statistical Association* **88**(421), 9--25.
#'
#' Harville, D. A. (1977) Maximum likelihood approaches to variance component
#' estimation and to related problems. *Journal of the American
#' Statistical Association* **72**(358), 320--338.
#' @keywords models
#' @examples
#'
#' ###############################################
#' ## Crowder seeds example from Breslow & Clayton
#' ###############################################
#'
#' summary(glmmPQL(cbind(r, n - r) ~ seed + extract,
#' random = diag(nrow(seeds)),
#' family = "binomial", data = seeds))
#'
#' summary(glmmPQL(cbind(r, n - r) ~ seed*extract,
#' random = diag(nrow(seeds)),
#' family = "binomial", data = seeds))
#'
#' @importFrom stats gaussian .getXlevels glm.control is.empty.model glm.control glm.fit model.frame model.matrix model.offset model.response model.weights optimize terms
#' @export
glmmPQL <- function(fixed, random = NULL, family = "binomial", data = NULL,
subset = NULL, weights = NULL, offset = NULL,
na.action = NULL, start = NULL, etastart = NULL,
mustart = NULL, control = glmmPQL.control(...),
sigma = 0.1, sigma.fixed = FALSE, model = TRUE,
x = FALSE, contrasts = NULL, ...) {
call <- match.call()
nm <- names(call)[-1]
if (is.null(random)) {
keep <- is.element(nm, c("family", "data", "subset", "weights",
"offset", "na.action"))
for (i in nm[!keep]) call[[i]] <- NULL
call$formula <- fixed
environment(call$formula) <- environment(fixed)
call[[1]] <- as.name("glm")
return(eval.parent(call))
}
modelTerms <- terms(fixed, data = data)
modelCall <- as.list(match.call(expand.dots = FALSE))
argPos <- match(c("data", "subset", "na.action", "weights", "offset"),
names(modelCall), 0)
modelData <- as.call(c(model.frame, list(formula = modelTerms,
drop.unused.levels = TRUE),
modelCall[argPos]))
modelData <- eval(modelData, parent.frame())
if (!is.matrix(random) || nrow(random) != nrow(modelData)) {
stop("`random` should be a matrix object, with ", nrow(modelData),
" rows.")
}
if (!is.null(modelCall$subset))
Z <- random[eval(modelCall$subset, data, parent.frame()),]
else Z <- random
if (!is.null(attr(modelData, "na.action")))
Z <- Z[-attr(modelData, "na.action"),]
nObs <- nrow(modelData)
y <- model.response(modelData, "numeric")
if (is.null(y))
y <- rep(0, nObs)
weights <- as.vector(model.weights(modelData))
if (!is.null(weights) && any(weights < 0))
stop("negative weights are not allowed")
if (is.null(weights))
weights <- rep.int(1, nObs)
offset <- as.vector(model.offset(modelData))
if (is.null(offset))
offset <- rep.int(0, nObs)
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family))
family <- family()
if (is.null(family$family)) {
print(family)
stop("`family' not recognized")
}
if (family$family == "binomial") {
if (is.factor(y) && NCOL(y) == 1)
y <- y != levels(y)[1]
else if (NCOL(y) == 2) {
n <- y[, 1] + y[, 2]
y <- ifelse(n == 0, 0, y[, 1]/n)
weights <- weights * n
}
}
## Use GLM to estimate fixed effects
empty <- is.empty.model(modelTerms)
if (!empty)
X <- model.matrix(formula(modelTerms), data = modelData, contrasts)
else
X <- matrix(, nObs, 0)
fit <- glmmPQL.fit(X = X, y = y, Z = Z, weights = weights, start = start,
etastart = etastart, mustart = mustart, offset = offset,
family = family, control = control, sigma = sigma,
sigma.fixed = sigma.fixed, ...)
if (sum(offset) && attr(modelTerms, "intercept") > 0) {
fit$null.deviance <- glm.fit(x = X[, "(Intercept)", drop = FALSE],
y = y, weights = weights, offset = offset, family = family,
control = glm.control(), intercept = TRUE)$deviance
}
if (model)
fit$model <- modelData
fit$na.action <- attr(modelData, "na.action")
if (x)
fit$x <- X
fit <- c(fit, list(call = call, formula = fixed, random = random,
terms = modelTerms,
data = data, offset = offset, control = control,
method = "glmmPQL.fit", contrasts = attr(X, "contrasts"),
xlevels = .getXlevels(modelTerms, modelData)))
class(fit) <- c("BTglmmPQL", "glm", "lm")
fit
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/glmmPQL.R
|
#' Control Aspects of the glmmPQL Algorithm
#'
#' Set control variables for the glmmPQL algorithm.
#'
#' This function provides an interface to control the PQL algorithm used by
#' [BTm()] for fitting Bradley Terry models with random effects.
#'
#' The algorithm iterates between a series of iterated weighted least squares
#' iterations to update the fixed effects and a single Fisher scoring iteration
#' to update the standard deviation of the random effects.
#'
#' Convergence of both the inner and outer iterations are judged by comparing
#' the squared components of the relevant score vector with corresponding
#' elements of the diagonal of the Fisher information matrix. If, for all
#' components of the relevant score vector, the ratio is less than
#' `tolerance^2`, or the corresponding diagonal element of the Fisher
#' information matrix is less than 1e-20, iterations cease.
#'
#' @param maxiter the maximum number of outer iterations.
#' @param IWLSiter the maximum number of iterated weighted least squares
#' iterations used to estimate the fixed effects, given the standard deviation
#' of the random effects.
#' @param tol the tolerance used to determine convergence in the IWLS
#' iterations and over all (see details).
#' @param trace logical: whether or not to print the score for the random
#' effects variance at the end of each iteration.
#' @return A list with the arguments as components.
#' @author Heather Turner
#' @seealso [glmmPQL()], [BTm()]
#' @references Breslow, N. E. and Clayton, D. G. (1993), Approximate inference
#' in Generalized Linear Mixed Models. *Journal of the American
#' Statistical Association* **88**(421), 9--25.
#' @keywords models
#' @examples
#'
#' ## Variation on example(flatlizards)
#' result <- rep(1, nrow(flatlizards$contests))
#'
#' ## BTm passes arguments on to glmmPQL.control()
#' args(BTm)
#' BTmodel <- BTm(result, winner, loser, ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..] + (1|..),
#' data = flatlizards, tol = 1e-3, trace = TRUE)
#' summary(BTmodel)
#'
#' @export
glmmPQL.control <- function (maxiter = 50, IWLSiter = 10, tol = 1e-6,
trace = FALSE) {
call <- as.list(match.call())
if (length(call) > 1) {
argPos <- match(c("maxiter", "IWLSiter", "tol"), names(call))
for (n in argPos[!is.na(argPos)]) {
if (!is.numeric(call[[n]]) || call[[n]] <= 0)
stop("value of '", names(call)[n], "' must be > 0")
}
}
list(maxiter = maxiter, IWLSiter = IWLSiter, tol = tol,
trace = trace)
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/glmmPQL.control.R
|
#' @importFrom utils flush.console
glmmPQL.fit <- function(X, y, Z, weights = rep(1, NROW(y)), start = NULL,
etastart = NULL, mustart = NULL,
offset = rep(0, NROW(y)), family = gaussian(),
control = glmmPQL.control(...),
sigma = NULL, sigma.fixed = FALSE, ...) {
matchCall <- as.list(match.call(expand.dots = FALSE))
dots <- names(matchCall[["..."]])
dots <- intersect(dots, setdiff(names(formals(glm)), "control"))
fit0 <- do.call("glm.fit", c(list(X, y, weights, start = start,
etastart = etastart, mustart = mustart,
offset = offset, family = family,
control = glm.control()),
matchCall[dots]))
w <- fit0$prior.weights
# QR missing from glm.fit if ncol(X) = 0
QR <- qr(X)
R <- qr.R(QR)
rank <- QR$rank
p <- ncol(R)
nm <- colnames(R)[seq(length = rank)]
if (rank < p) {
X0 <- X[,colnames(R)[-seq(length = rank)]]
X <- X[, nm]
}
empty <- !length(X)
if (empty) {
alpha <- numeric(0)
Xa <- matrix(0, length(y), 1)
}
eta <- fit0$linear.predictors
residuals <- fit0$residuals
Y <- eta + residuals - offset #working response
wy <- fit0$weights # iterative weights
wY <- sqrt(wy) * Y
wZ <- sqrt(wy) * Z
ZWy <- crossprod(wZ, wY)
ZWZ <- crossprod(wZ, wZ)
if (!empty) {
wX <- sqrt(wy) * X
XWy <- crossprod(wX, wY)
XWX <- crossprod(wX, wX)
ZWX <- crossprod(wZ, wX)
E <- chol(XWX)
J <- backsolve(E, t(ZWX), transpose = TRUE)
f <- backsolve(E, XWy, transpose = TRUE)
ZSy <- ZWy - crossprod(J, f)
ZSZ <- ZWZ - crossprod(J, J)
}
if (is.null(sigma)) sigma <- 0.1
logtheta <- log(sigma^2)
conv <- FALSE
for (i in 1:control$maxiter) {
## Update coefficients
for (j in 1:control$IWLSiter) {
IZWZD <- ZWZ * sigma^2
diag(IZWZD) <- 1 + diag(IZWZD)
A <- chol(IZWZD)
if (!empty) {
IZSZD <- ZSZ * sigma^2
diag(IZSZD) <- 1 + diag(IZSZD)
G <- chol(IZSZD)
g <- backsolve(G, ZSy, transpose = TRUE)
v <- backsolve(G, g)
B <- backsolve(A, sigma * ZWX, transpose = TRUE)
K <- chol(XWX - crossprod(B, B))
b <- backsolve(A, sigma * ZWy, transpose = TRUE)
c <- backsolve(K, XWy - t(B) %*% b, transpose = TRUE)
alpha <- backsolve(K, c)
Xa <- X %*% alpha
beta <- sigma^2 * v
}
else {
g <- backsolve(A, ZWy, transpose = TRUE)
v <- backsolve(A, g)
beta <- sigma^2 * v
}
eta <- c(Xa + Z %*% beta + offset)
## Update working response & weights
mu <- family$linkinv(eta)
mu.eta.val <- family$mu.eta(eta)
residuals <- (fit0$y - mu)/mu.eta.val
Y <- eta + residuals - offset
wy <- w * mu.eta.val^2/family$variance(mu)
wY <- sqrt(wy) * Y
wZ <- sqrt(wy) * Z
ZWy <- crossprod(wZ, wY)
ZWZ <- crossprod(wZ, wZ)
if (!empty) {
wX <- sqrt(wy) * X
XWy <- crossprod(wX, wY)
XWX <- crossprod(wX, wX)
ZWX <- crossprod(wZ, wX)
E <- chol(XWX)
J <- backsolve(E, t(ZWX), transpose = TRUE)
f <- backsolve(E, XWy, transpose = TRUE)
ZSy <- ZWy - crossprod(J, f)
ZSZ <- ZWZ - crossprod(J, J)
score <- c(crossprod(X, wy * residuals),
crossprod(Z, wy * residuals) - v)
diagInfo <- c(diag(XWX), diag(ZWZ))
if (all(diagInfo < 1e-20) ||
all(abs(score) <
control$tol * sqrt(control$tol + diagInfo))) {
if (sigma.fixed) conv <- TRUE
break
}
}
else {
score <- crossprod(Z, wy * residuals) - v
diagInfo <- diag(ZWZ)
if (all(diagInfo < 1e-20) ||
all(abs(score) <
control$tol * sqrt(control$tol + diagInfo))) {
if (sigma.fixed) conv <- TRUE
break
}
}
}
if (!sigma.fixed){
## Update sigma
## sigma^2 = exp(logtheta)
## One Fisher scoring iteration
IZWZD <- ZWZ * sigma^2
diag(IZWZD) <- 1 + diag(IZWZD)
A <- chol(IZWZD)
if (!empty) {
IZSZD <- ZSZ * sigma^2
diag(IZSZD) <- 1 + diag(IZSZD)
G <- chol(IZSZD)
g <- backsolve(G, ZSy, transpose = TRUE)
v <- backsolve(G, g)
h <- backsolve(G, ZSZ, transpose = TRUE)
H <- backsolve(G, h)
}
else {
g <- backsolve(A, ZWy, transpose = TRUE)
v <- backsolve(A, g)
h <- backsolve(A, ZWZ, transpose = TRUE)
H <- backsolve(A, h)
}
## Harville p326
score <- drop(-0.5 * sum(diag(H)) + 0.5 * crossprod(v, v)) *
sigma^2
Info <- 0.5 * sum(H^2) * sigma^4
if (control$trace) {
##B & K eq 5 - still not consistently increasing
cat("Iteration ", i,
". Score = ", abs(score) ,
"\n", sep = "")
flush.console()
}
## check for overall convergence
if (Info < 1e-20 ||
abs(score) < control$tol * sqrt(control$tol + Info)){
conv <- TRUE
break
}
## Cannot use beta to update t(YXa) %*% Vinv %*% YXa
ZWYXa <- crossprod(wZ, sqrt(wy) * (Y - Xa))
optfun <- function(logtheta) {
IZWZD <- ZWZ * exp(logtheta)
diag(IZWZD) <- 1 + diag(IZWZD)
A <- chol(IZWZD)
if (!empty) {
IZSZD <- ZSZ * exp(logtheta)
diag(IZSZD) <- 1 + diag(IZSZD)
G <- chol(IZSZD)
d <- backsolve(A, sqrt(exp(logtheta)) * ZWYXa,
transpose = TRUE)
sum(log(diag(G))) - 0.5 * crossprod(d, d)
}
else {
d <- backsolve(A, sqrt(exp(logtheta)) * ZWy,
transpose = TRUE)
sum(log(diag(A))) - 0.5 * crossprod(d, d)
}
}
optres <- optimize(optfun, c(-10, 10))
if (optfun(-10) < optfun(optres$minimum))
sigma <- 0
else {
if (abs(optres$minimum - (logtheta + score/Info)) > 0.1)
logtheta <- optres$minimum
else
logtheta <- logtheta + score/Info
sigma <- sqrt(exp(logtheta))
}
}
else if (conv)
break
}
if (!empty) varFix <- chol2inv(K)
else varFix <- matrix(, 0, 0)
rownames(varFix) <- colnames(varFix) <- colnames(X)
fit0$coef[nm] <- alpha
if (!sigma.fixed)
varSigma <- sigma^2/(4 * Info)
else
varSigma <- NA
glm <- identical(sigma, 0)
if (!empty) {
if (rank < p) QR <- qr(cbind(wX, sqrt(w) * X0))
else QR <- qr(wX)
R <- qr.R(QR)
}
list(coefficients = structure(fit0$coef, random = beta),
residuals = residuals,
fitted.values = mu,
#effect = ?
R = if (!empty) R,
rank = rank,
qr = if (!empty) QR,
family = family,
linear.predictors = eta,
deviance = if (glm) sum(family$dev.resids(y, mu, w)),
aic = if (glm)
family$aic(y, length(y), mu, w, sum(family$dev.resids(y, mu, w))) +
2 * rank,
null.deviance = if (glm) {
wtdmu <- family$linkinv(offset)
sum(family$dev.resids(y, wtdmu, w))
},
iter = ifelse(glm, NA, i),
weights = wy,
prior.weights = w,
df.residual = length(y) - rank,
df.null = if (glm) length(y) - sum(w == 0),
y = y,
sigma = sigma, sigma.fixed = sigma.fixed,
varFix = varFix, varSigma = varSigma, converged = conv)
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/glmmPQL.fit.R
|
#' College Hockey Men's Division I 2009-10 results
#'
#' Game results from American College Hockey Men's Division I composite
#' schedule 2009-2010.
#'
#' The Division I ice hockey teams are arranged in six conferences: Atlantic
#' Hockey, Central Collegiate Hockey Association, College Hockey America, ECAC
#' Hockey, Hockey East and the Western Collegiate Hockey Association, all part
#' of the National Collegiate Athletic Association. The composite schedule
#' includes within conference games and between conference games.
#'
#' The data set here contains only games from the regular season, the results
#' of which determine the teams that play in the NCAA national tournament.
#' There are six automatic bids that go to the conference tournament champions,
#' the remaining 10 teams are selected based upon ranking under the NCAA's
#' system of pairwise comparisons
#' (\url{https://www.collegehockeynews.com/info/?d=pwcrpi}). Some have argued
#' that Bradley-Terry rankings would be fairer
#' (\url{https://www.collegehockeynews.com/info/?d=krach}).
#'
#' @name icehockey
#' @docType data
#' @format A data frame with 1083 observations on the following 6 variables.
#' \describe{
#' \item{date}{a numeric vector}
#' \item{visitor}{a
#' factor with 58 levels `Alaska Anchorage` ... `Yale`}
#' \item{v_goals}{a numeric vector}
#' \item{opponent}{a factor
#' with 58 levels `Alaska Anchorage` ... `Yale`}
#' \item{o_goals}{a numeric vector}
#' \item{conference}{a factor
#' with levels `AH`, `CC`, `CH`, `EC`, `HE`,
#' `NC`, `WC`}
#' \item{result}{a numeric vector: 1 if visitor
#' won, 0.5 for a draw and 0 if visitor lost}
#' \item{home.ice}{a logical
#' vector: 1 if opponent on home ice, 0 if game on neutral ground} }
#' @references Schlobotnik, J. Build your own rankings:
#' \url{http://www.elynah.com/tbrw/2010/rankings.diy.shtml}.
#'
#' College Hockey News \url{https://www.collegehockeynews.com/}.
#'
#' Selections for 2010 NCAA tournament:
#' \url{https://www.espn.com/college-sports/news/story?id=5012918}.
#' @source \url{http://www.collegehockeystats.net/0910/schedules/men}.
#' @keywords datasets
#' @examples
#'
#' ### Fit the standard Bradley-Terry model
#' standardBT <- BTm(outcome = result,
#' player1 = visitor, player2 = opponent,
#' id = "team", data = icehockey)
#'
#' ## Bradley-Terry abilities
#' abilities <- exp(BTabilities(standardBT)[,1])
#'
#' ## Compute round-robin winning probability and KRACH ratings
#' ## (scaled abilities such that KRACH = 100 for a team with
#' ## round-robin winning probability of 0.5)
#' rankings <- function(abilities){
#' probwin <- abilities/outer(abilities, abilities, "+")
#' diag(probwin) <- 0
#' nteams <- ncol(probwin)
#' RRWP <- rowSums(probwin)/(nteams - 1)
#' low <- quantile(abilities, 0.45)
#' high <- quantile(abilities, 0.55)
#' middling <- uniroot(function(x) {sum(x/(x+abilities)) - 0.5*nteams},
#' lower = low, upper = high)$root
#' KRACH <- abilities/middling*100
#' cbind(KRACH, RRWP)
#' }
#'
#' ranks <- rankings(abilities)
#' ## matches those produced by Joe Schlobotnik's Build Your Own Rankings
#' head(signif(ranks, 4)[order(ranks[,1], decreasing = TRUE),])
#'
#' ## At one point the NCAA rankings gave more credit for wins on
#' ## neutral/opponent's ground. Home ice effects are easily
#' ## incorporated into the Bradley-Terry model, comparing teams
#' ## on a "level playing field"
#' levelBT <- BTm(result,
#' data.frame(team = visitor, home.ice = 0),
#' data.frame(team = opponent, home.ice = home.ice),
#' ~ team + home.ice,
#' id = "team", data = icehockey)
#'
#' abilities <- exp(BTabilities(levelBT)[,1])
#' ranks2 <- rankings(abilities)
#'
#' ## Look at movement between the two rankings
#' change <- factor(rank(ranks2[,1]) - rank(ranks[,1]))
#' barplot(xtabs(~change), xlab = "Change in Rank", ylab = "No. Teams")
#'
#' ## Take out regional winners and look at top 10
#' regional <- c("RIT", "Alabama-Huntsville", "Michigan", "Cornell", "Boston College",
#' "North Dakota")
#'
#' ranks <- ranks[!rownames(ranks) %in% regional]
#' ranks2 <- ranks2[!rownames(ranks2) %in% regional]
#'
#' ## compare the 10 at-large selections under both rankings
#' ## with those selected under NCAA rankings
#' cbind(names(sort(ranks, decr = TRUE)[1:10]),
#' names(sort(ranks2, decr = TRUE)[1:10]),
#' c("Miami", "Denver", "Wisconsin", "St. Cloud State",
#' "Bemidji State", "Yale", "Northern Michigan", "New Hampshire",
#' "Alsaka", "Vermont"))
#'
#'
"icehockey"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/icehockey.R
|
missToZero <- function(x, miss, dim = 1) {
if (dim == 1) x[miss, ] <- 0
else x[, miss] <- 0
x
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/missToZero.R
|
#' @importFrom stats model.frame
#' @export
model.matrix.BTm <- function(object, ...){
model.frame(object)$X
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/model.matrix.BTm.R
|
## P(win|not tie) in terms of expit(lambda_i - lambda_j)
GenDavidsonTie <- function(p){
scale <- match("tie.scale", substring(names(coef), 1, 9), 0)
if (scale != 0) scale <- exp(coef[scale])
else scale <- 1
tie.mode <- match("tie.mode", substring(names(coef), 1, 8), 0)
if (tie.mode != 0) tie.mode <- coef["tie.mode"]
delta <- coef[match("tie.max", substring(names(coef), 1, 7))]
## first player is at home
weight1 <- plogis(tie.mode)
weight2 <- 1 - weight1
## plogis = expit
plogis(delta - scale * (weight1 * log(weight1) + weight2 * log(weight2)) +
scale * (weight1 * log(p) + weight2 * log(1-p)))
}
#tmp <- eval(substitute(player1), data, parent.frame())
#' Plot Proportions of Tied Matches and Non-tied Matches Won
#'
#' Plot proportions of tied matches and non-tied matches won by the first
#' player, within matches binned by the relative player ability, as expressed
#' by the probability that the first player wins, given the match is not a tie.
#' Add fitted lines for each set of matches, as given by the generalized
#' Davidson model.
#'
#' If `home.adv` is specified, the results are re-ordered if necessary so
#' that the home player comes first; any matches played on neutral ground are
#' omitted.
#'
#' First the probability that the first player wins given that the match is not
#' a tie is computed: \deqn{expit(home.adv + abilities[player1] -
#' abilities[player2])} where `home.adv` and `abilities` are
#' parameters from a generalized Davidson model that have been estimated on the
#' log scale.
#'
#' The matches are then binned according to this probability, grouping together
#' matches with similar relative ability between the first player and the
#' second player. Within each bin, the proportion of tied matches is computed
#' and these proportions are plotted against the mid-point of the bin. Then the
#' bins are re-computed omitting the tied games and the proportion of non-tied
#' matches won by the first player is found and plotted against the new
#' mid-point.
#'
#' Finally curves are added for the probability of a tie and the conditional
#' probability of win given the match is not a tie, under a generalized
#' Davidson model with parameters as specified by `tie.max`,
#' `tie.scale` and `tie.mode`.
#'
#' The function can also be used to plot the proportions of wins along with the
#' fitted probability of a win under the Bradley-Terry model.
#'
#' @param win a logical vector: `TRUE` if player1 wins, `FALSE`
#' otherwise.
#' @param tie a logical vector: `TRUE` if the outcome is a tie,
#' `FALSE` otherwise (`NULL` if there are no ties).
#' @param loss a logical vector: `TRUE` if player1 loses, `FALSE`
#' otherwise.
#' @param player1 an ID factor specifying the first player in each contest,
#' with the same set of levels as `player2`.
#' @param player2 an ID factor specifying the second player in each contest,
#' with the same set of levels as `player2`.
#' @param abilities the fitted abilities from a generalized Davidson model (or
#' a Bradley-Terry model).
#' @param home.adv if applicable, the fitted home advantage parameter from a
#' generalized Davidson model (or a Bradley-Terry model).
#' @param tie.max the fitted parameter from a generalized Davidson model
#' corresponding to the maximum tie probability.
#' @param tie.scale if applicable, the fitted parameter from a generalized
#' Davidson model corresponding to the scale of dependence of the tie
#' probability on the probability that `player1` wins, given the outcome
#' is not a draw.
#' @param tie.mode if applicable, the fitted parameter from a generalized
#' Davidson model corresponding to the location of maximum tie probability, in
#' terms of the probability that `player1` wins, given the outcome is not
#' a draw.
#' @param at.home1 a logical vector: `TRUE` if `player1` is at home,
#' `FALSE` otherwise.
#' @param at.home2 a logical vector: `TRUE` if `player2` is at home,
#' `FALSE` otherwise.
#' @param data an optional data frame providing variables required by the
#' model, with one observation per match.
#' @param subset an optional logical or numeric vector specifying a subset of
#' observations to include in the plot.
#' @param bin.size the approximate number of matches in each bin.
#' @param xlab the label to use for the x-axis.
#' @param ylab the label to use for the y-axis.
#' @param legend text to use for the legend.
#' @param col a vector specifying colours to use for the proportion of non-tied
#' matches won and the proportion of tied matches.
#' @param \dots further arguments passed to plot.
#' @return A list of data frames: \item{win}{ a data frame comprising
#' `prop.win`, the proportion of non-tied matches won by the first player
#' in each bin and `bin.win`, the mid-point of each bin. } \item{tie}{
#' (when ties are present) a data frame comprising `prop.tie`, the
#' proportion of tied matches in each bin and `bin.tie`, the mid-point of
#' each bin. }
#' @note This function is designed for single match outcomes, therefore data
#' aggregated over player pairs will need to be expanded.
#' @author Heather Turner
#' @seealso [GenDavidson()], [BTm()]
#' @keywords models nonlinear
#' @examples
#'
#' #### A Bradley-Terry example using icehockey data
#'
#' ## Fit the standard Bradley-Terry model, ignoring home advantage
#' standardBT <- BTm(outcome = result,
#' player1 = visitor, player2 = opponent,
#' id = "team", data = icehockey)
#'
#' ## comparing teams on a "level playing field"
#' levelBT <- BTm(result,
#' data.frame(team = visitor, home.ice = 0),
#' data.frame(team = opponent, home.ice = home.ice),
#' ~ team + home.ice,
#' id = "team", data = icehockey)
#'
#' ## compare fit to observed proportion won
#' ## exclude tied matches as not explicitly modelled here
#' par(mfrow = c(1, 2))
#' plotProportions(win = result == 1, loss = result == 0,
#' player1 = visitor, player2 = opponent,
#' abilities = BTabilities(standardBT)[,1],
#' data = icehockey, subset = result != 0.5,
#' main = "Without home advantage")
#'
#' plotProportions(win = result == 1, loss = result == 0,
#' player1 = visitor, player2 = opponent,
#' home.adv = coef(levelBT)["home.ice"],
#' at.home1 = 0, at.home2 = home.ice,
#' abilities = BTabilities(levelBT)[,1],
#' data = icehockey, subset = result != 0.5,
#' main = "With home advantage")
#'
#' #### A generalized Davidson example using football data
#' if (require(gnm)) {
#'
#' ## subset to first and last season for illustration
#' football <- subset(football, season %in% c("2008-9", "2012-13"))
#'
#' ## convert to trinomial counts
#' football.tri <- expandCategorical(football, "result", idvar = "match")
#'
#' ## add variable to indicate whether team playing at home
#' football.tri$at.home <- !logical(nrow(football.tri))
#'
#' ## fit Davidson model
#' Dav <- gnm(count ~ GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri)
#'
#' ## fit shifted & scaled Davidson model
#' shifScalDav <- gnm(count ~
#' GenDavidson(result == 1, result == 0, result == -1,
#' home:season, away:season, home.adv = ~1,
#' tie.max = ~1, tie.scale = ~1, tie.mode = ~1,
#' at.home1 = at.home,
#' at.home2 = !at.home) - 1,
#' eliminate = match, family = poisson, data = football.tri)
#'
#' ## diagnostic plots
#' main <- c("Davidson", "Shifted & Scaled Davidson")
#' mod <- list(Dav, shifScalDav)
#' names(mod) <- main
#' alpha <- names(coef(Dav)[-(1:2)])
#'
#' ## use football.tri data so that at.home can be found,
#' ## but restrict to actual match results
#' par(mfrow = c(1,2))
#' for (i in 1:2) {
#' coef <- parameters(mod[[i]])
#' plotProportions(result == 1, result == 0, result == -1,
#' home:season, away:season,
#' abilities = coef[alpha],
#' home.adv = coef["home.adv"],
#' tie.max = coef["tie.max"],
#' tie.scale = coef["tie.scale"],
#' tie.mode = coef["tie.mode"],
#' at.home1 = at.home,
#' at.home2 = !at.home,
#' main = main[i],
#' data = football.tri, subset = count == 1)
#' }
#' }
#'
#' @importFrom graphics curve plot points
#' @importFrom stats na.omit
#' @export
plotProportions <- function(win, tie = NULL, loss,
player1,
player2,
abilities = NULL,
home.adv = NULL,
tie.max = NULL,
tie.scale = NULL,
tie.mode = NULL,
at.home1 = NULL,
at.home2 = NULL,
data = NULL,
subset = NULL,
bin.size = 20,
xlab = "P(player1 wins | not a tie)",
ylab = "Proportion",
legend = NULL,
col = 1:2,
...){
call <- as.list(match.call())
var <- intersect(names(call), c("win", "tie", "loss",
"player1", "player2",
"at.home1", "at.home2"))
var <- var[!vapply(call[var], is.null, logical(1))]
dat <- with(data, do.call("data.frame", call[var]))
if (!missing(subset)){
subset <- eval(substitute(subset), data, parent.frame())
dat <- subset(dat, subset)
}
if (!missing(tie) && sum(dat$tie) == 0) dat$tie <- NULL
if (!is.null(home.adv) && (missing(at.home1) || missing(at.home2)))
stop("at.home1 and at.home2 must be specified")
if (!is.null(home.adv)){
## exclude neutral contests, make sure home player is first
dat <- subset(dat, at.home1 | at.home2)
swap <- which(as.logical(dat$at.home2))
if (length(swap)) {
dat$win[swap] <- dat$loss[swap]
if (is.null(dat$tie)) dat$loss[swap] <- !dat$win[swap]
else dat$loss[swap] <- !(dat$win[swap] | dat$tie[swap])
tmp <- dat$player1[swap]
dat$player1[swap] <- dat$player2[swap]
dat$player2[swap] <- tmp
dat$at.home1[swap] <- TRUE
dat$at.home2[swap] <- FALSE
}
} else home.adv <- 0
### get proportions
p <- with(dat, plogis(home.adv + abilities[as.character(player1)] -
abilities[as.character(player2)]))
## Depending on the distribution of p_ij (across all matches),
## divide the range of probabilities p_ij into discrete "bins", each
## of which has at least (say) 20 matches in it
getBins <- function(p, bin.size) {
## alternatively estimate bins to same size intervals
## at least bin.size - distribute extra evenly over range
min.size <- bin.size
n <- length(p)
r <- n %% min.size
size <- rep(min.size, n %/% min.size)
if (r > 0) {
step <- length(size)/r
extra <- round(seq(from = step/2 + 0.01,
to = step/2 + 0.01 + (r - 1)*step, by = step))
size[extra] <- min.size + 1
}
bin <- factor(rep(seq(length(size)), size))[match(p, sort(p))]
low <- sort(p)[cumsum(c(1, size[-length(size)]))] #first
high <- sort(p)[cumsum(size)] #last
mid <- (high - low)/2 + low
list(bin = bin, mid = mid)
}
winBin <- getBins(p, bin.size)
## Within each bin b, calculate
## d_b = proportion of matches in that bin that were drawn
if (!is.null(dat$tie)) {
tieBin <- winBin
tri <- with(dat, win - (!win & !tie))
d_b <- tapply(tri, tieBin$bin, function(x) sum(x == 0)/length(x))
## recompute bins omitting ties
winBin <- getBins(p[!dat$tie], bin.size)
}
## h_b = proportion of *non-drawn* matches in that bin that were won
## by the home team
if (!is.null(dat$tie)) {
h_b <- tapply(tri[!dat$tie], winBin$bin,
function(x) sum(x == 1)/length(x))
}
else h_b <- tapply(dat$win, winBin$bin, function(x) sum(x == 1)/length(x))
## Plot d_b and h_b against the bin midpoints, in a plot with
## axis limits both (0,1)
plot(h_b ~ winBin$mid, xlim = c(0, 1), ylim = c(0, 1),
xlab = xlab, ylab = ylab, ...)
if (missing(legend)) {
if (is.null(dat$tie)) legend <- "Matches won"
else legend <- c("Non-tied matches won", "Matches tied")
}
legend("topleft", legend, col = col[c(1, 2[!missing(tie)])],
pch = 1)
if (!is.null(dat$tie)) points(d_b ~ tieBin$mid, col = col[2])
## Add to the plot the lines/curves
## y = x
## y = expit(log(nu * sqrt(p_ij * (1 - p_ij))))
## The d_b should lie around the latter curve, and the h_b should
## lie around the former line. Any clear patterns of departure are
## of interest.
curve(I, 0, 1, add = TRUE)
env <- new.env()
environment(GenDavidsonTie) <- env
coef <- na.omit(c(home.adv = unname(home.adv),
tie.max = unname(tie.max),
tie.scale = unname(tie.scale),
tie.mode = unname(tie.mode)))
assign("coef", coef, envir=env)
curve(GenDavidsonTie, 0, 1, col = col[2], add = TRUE)
out <- list(win = data.frame(prop.win = h_b, bin.win = winBin$mid))
if (!is.null(dat$tie))
out <- c(out, tie = data.frame(prop.tie = d_b, bin.tie = tieBin$mid))
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/plotProportions.R
|
#' Predict Method for BTglmmPQL Objects
#'
#' Obtain predictions and optionally standard errors of those predictions from
#' a `"BTglmmPQL"` object.
#'
#' If `newdata` is omitted the predictions are based on the data used for
#' the fit. In that case how cases with missing values in the original fit are
#' treated is determined by the `na.action` argument of that fit. If
#' `na.action = na.omit` omitted cases will not appear in the residuals,
#' whereas if `na.action = na.exclude` they will appear (in predictions
#' and standard errors), with residual value `NA`. See also
#' `napredict`.
#'
#' Standard errors for the predictions are approximated assuming the variance
#' of the random effects is known, see Booth and Hobert (1998).
#'
#' @param object a fitted object of class `"BTglmmPQL"`
#' @param newdata (optional) a data frame in which to look for variables with
#' which to predict. If omitted, the fitted linear predictors are used.
#' @param newrandom if `newdata` is provided, a corresponding design
#' matrix for the random effects, will columns corresponding to the random
#' effects estimated in the original model.
#' @param level an integer vector giving the level(s) at which predictions are
#' required. Level zero corresponds to population-level predictions (fixed
#' effects only), whilst level one corresponds to the individual-level
#' predictions (full model) which are NA for contests involving individuals not
#' in the original data. By default `level = 0` if the model converged to a
#' fixed effects model, `1` otherwise.
#' @param type the type of prediction required. The default is on the scale of
#' the linear predictors; the alternative `"response"` is on the scale of
#' the response variable. Thus for a default binomial model the default
#' predictions are of log-odds (probabilities on logit scale) and `type =
#' "response"` gives the predicted probabilities. The `"terms"` option
#' returns a matrix giving the fitted values of each term in the model formula
#' on the linear predictor scale (fixed effects only).
#' @param se.fit logical switch indicating if standard errors are required.
#' @param terms with `type ="terms"` by default all terms are returned. A
#' character vector specifies which terms are to be returned.
#' @param na.action function determining what should be done with missing
#' values in `newdata`. The default is to predict `NA`.
#' @param \dots further arguments passed to or from other methods.
#' @return If `se.fit = FALSE`, a vector or matrix of predictions. If
#' `se = TRUE`, a list with components \item{fit }{Predictions}
#' \item{se.fit }{Estimated standard errors}
#' @author Heather Turner
#' @seealso [predict.glm()], [predict.BTm()]
#' @references Booth, J. G. and Hobert, J. P. (1998). Standard errors of
#' prediction in Generalized Linear Mixed Models. *Journal of the American
#' Statistical Association* **93**(441), 262 -- 272.
#' @keywords models
#' @examples
#'
#' seedsModel <- glmmPQL(cbind(r, n - r) ~ seed + extract,
#' random = diag(nrow(seeds)),
#' family = binomial,
#' data = seeds)
#'
#' pred <- predict(seedsModel, level = 0)
#' predTerms <- predict(seedsModel, type = "terms")
#'
#' all.equal(pred, rowSums(predTerms) + attr(predTerms, "constant"))
#'
#' @importFrom stats .checkMFClasses coef delete.response family model.frame model.matrix na.exclude na.pass napredict
#' @export
predict.BTglmmPQL <- function(object, newdata = NULL, newrandom = NULL,
level = ifelse(object$sigma == 0, 0, 1),
type = c("link", "response", "terms"),
se.fit = FALSE, terms = NULL,
na.action = na.pass, ...) {
## only pass on if a glm
if (object$sigma == 0) {
if (level != 0) warning("Fixed effects model: setting level to 0")
return(NextMethod())
}
if (!all(level %in% c(0, 1))) stop("Only level %in% c(0, 1) allowed")
type <- match.arg(type)
if (!is.null(newdata) || type == "terms") tt <- terms(object)
if (!is.null(newdata)) {
## newdata should give variables in terms formula
Terms <- delete.response(tt)
m <- model.frame(Terms, newdata, na.action = na.action,
xlev = object$xlevels)
na.action <- attr(m, "na.action")
if (!is.null(cl <- attr(Terms, "dataClasses")))
.checkMFClasses(cl, m)
D <- model.matrix(Terms, m, contrasts.arg = object$contrasts)
np <- nrow(D) # n predictions
offset <- rep(0, np)
if (!is.null(off.num <- attr(tt, "offset")))
for (i in off.num) offset <- offset + eval(attr(tt,
"variables")[[i + 1]], newdata)
if (!is.null(object$call$offset))
offset <- offset + eval(object$call$offset, newdata)
}
else {
D <- model.matrix(object)
newrandom <- object$random
na.action <- object$na.action
offset <- object$offset
}
cf <- coef(object)
keep <- !is.na(cf)
aa <- attr(D, "assign")[keep]
cf <- cf[keep]
D <- D[, keep, drop = FALSE]
if (se.fit == TRUE) {
sigma <- object$sigma
w <- sqrt(object$weights)
wX <- w * model.matrix(object)[, keep]
wZ <- w * object$random
XWX <- crossprod(wX)
XWZ <- crossprod(wX, wZ)
ZWZ <- crossprod(wZ, wZ)
diag(ZWZ) <- diag(ZWZ) + 1/sigma^2
K <- cbind(XWX, XWZ)
K <- chol(rbind(K, cbind(t(XWZ), ZWZ)))
if (type == "terms" || 0 %in% level){
## work out (chol of inverse of) topleft of K-inv directly
A <- backsolve(chol(ZWZ), t(XWZ), transpose = TRUE)
A <- chol(XWX - t(A) %*% A)
}
}
if (type == "terms") { # ignore level
if (1 %in% level)
warning("type = \"terms\": setting level to 0", call. = FALSE)
ll <- attr(tt, "term.labels")
if (!is.null(terms)) {
include <- ll %in% terms
ll <- ll[include]
}
hasintercept <- attr(tt, "intercept") > 0L
if (hasintercept) {
avx <- colMeans(model.matrix(object))
termsconst <- sum(avx * cf) #NA coefs?
D <- sweep(D, 2, avx)
}
pred0 <- matrix(ncol = length(ll), nrow = NROW(D))
colnames(pred0) <- ll
if (se.fit) {
A <- chol2inv(A)
se.pred0 <- pred0
}
for (i in seq(length.out = length(ll))){
ind <- aa == which(attr(tt, "term.labels") == ll[i])
pred0[, i] <- D[, ind, drop = FALSE] %*% cf[ind]
if (se.fit) {
se.pred0[, i] <- sqrt(diag(D[, ind] %*%
tcrossprod(A[ind, ind], D[, ind])))
}
}
if (hasintercept) attr(pred0, "constant") <- termsconst
if (se.fit) return(list(fit = pred0, se.fit = se.pred0))
return(pred0)
}
if (0 %in% level) {
pred0 <- napredict(na.action, c(D %*% cf) + offset)
if (type == "response")
pred0 <- family(object)$linkinv(pred0)
if (se.fit == TRUE) {
na.act <- attr(na.exclude(pred0), "na.action")
H <- backsolve(A, t(na.exclude(D)), transpose = TRUE)
## se.pred0 <-
## sqrt(diag(D %*% chol2inv(K)[1:ncol(D), 1:ncol(D)] %*% t(D)))
se.pred0 <- napredict(na.action,
napredict(na.act, sqrt(colSums(H^2))))
if (type == "response")
se.pred0 <- se.pred0*abs(family(object)$mu.eta(pred0))
pred0 <- list(fit = pred0, se.fit = se.pred0)
}
if (identical(level, 0)) return(pred0)
}
r <- nrow(D)
## newrandom should give new design matrix for original random effects
if (!is.null(newdata)){
if(is.null(newrandom))
stop("newdata specified without newrandom")
if (!is.null(na.action))
newrandom <- newrandom[-na.action, , drop = FALSE]
}
if (!identical(dim(newrandom), c(r, ncol(object$random))))
stop("newrandom should have ", r, " rows and ",
ncol(object$random), " columns")
D <- cbind(D, newrandom)
cf <- c(cf, attr(coef(object), "random"))
pred <- napredict(na.action, c(D %*% cf) + offset)
if (type == "response")
pred <- family(object)$linkinv(pred)
if (se.fit == TRUE) {
##se.pred <- sqrt(diag(D %*% chol2inv(K) %*% t(D)))
na.act <- attr(na.exclude(pred), "na.action")
H <- backsolve(K, t(na.exclude(D)), transpose = TRUE)
se.pred <- napredict(na.action, napredict(na.act, sqrt(colSums(H^2))))
if (type == "response")
se.pred <- se.pred*abs(family(object)$mu.eta(pred))
pred <- list(fit = pred, se.fit = se.pred)
}
if (0 %in% level)
list(population = pred0, individual = pred)
else pred
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/predict.BTglmmPQL.R
|
#' Predict Method for Bradley-Terry Models
#'
#' Obtain predictions and optionally standard errors of those predictions from
#' a fitted Bradley-Terry model.
#'
#' If `newdata` is omitted the predictions are based on the data used for
#' the fit. In that case how cases with missing values in the original fit are
#' treated is determined by the `na.action` argument of that fit. If
#' `na.action = na.omit` omitted cases will not appear in the residuals,
#' whereas if `na.action = na.exclude` they will appear (in predictions
#' and standard errors), with residual value `NA`. See also
#' `napredict`.
#'
#' @param object a fitted object of class `"BTm"`
#' @param newdata (optional) a data frame in which to look for variables with
#' which to predict. If omitted, the fitted linear predictors are used.
#' @param level for models with random effects: an integer vector giving the
#' level(s) at which predictions are required. Level zero corresponds to
#' population-level predictions (fixed effects only), whilst level one
#' corresponds to the player-level predictions (full model) which are NA for
#' contests involving players not in the original data. By default, `level = 0`
#' for a fixed effects model, `1` otherwise.
#' @param type the type of prediction required. The default is on the scale of
#' the linear predictors; the alternative `"response"` is on the scale of
#' the response variable. Thus for a default Bradley-Terry model the default
#' predictions are of log-odds (probabilities on logit scale) and
#' `type = "response"` gives the predicted probabilities. The `"terms"` option
#' returns a matrix giving the fitted values of each term in the model formula
#' on the linear predictor scale (fixed effects only).
#' @param se.fit logical switch indicating if standard errors are required.
#' @param dispersion a value for the dispersion, not used for models with
#' random effects. If omitted, that returned by `summary` applied to the
#' object is used, where applicable.
#' @param terms with `type ="terms"` by default all terms are returned. A
#' character vector specifies which terms are to be returned.
#' @param na.action function determining what should be done with missing
#' values in `newdata`. The default is to predict `NA`.
#' @param \dots further arguments passed to or from other methods.
#' @return If `se.fit = FALSE`, a vector or matrix of predictions. If
#' `se = TRUE`, a list with components \item{fit }{Predictions}
#' \item{se.fit }{Estimated standard errors}
#' @author Heather Turner
#' @seealso [predict.glm()], [predict.glmmPQL()]
#' @keywords models
#' @examples
#'
#' ## The final model in example(flatlizards)
#' result <- rep(1, nrow(flatlizards$contests))
#' Whiting.model3 <- BTm(1, winner, loser, ~ throat.PC1[..] + throat.PC3[..] +
#' head.length[..] + SVL[..] + (1|..),
#' family = binomial(link = "probit"),
#' data = flatlizards, trace = TRUE)
#'
#' ## `new' data for contests between four of the original lizards
#' ## factor levels must correspond to original levels, but unused levels
#' ## can be dropped - levels must match rows of predictors
#' newdata <- list(contests = data.frame(
#' winner = factor(c("lizard048", "lizard060"),
#' levels = c("lizard006", "lizard011",
#' "lizard048", "lizard060")),
#' loser = factor(c("lizard006", "lizard011"),
#' levels = c("lizard006", "lizard011",
#' "lizard048", "lizard060"))
#' ),
#' predictors = flatlizards$predictors[c(3, 6, 27, 33), ])
#'
#' predict(Whiting.model3, level = 1, newdata = newdata)
#'
#' ## same as
#' predict(Whiting.model3, level = 1)[1:2]
#'
#' ## introducing a new lizard
#' newpred <- rbind(flatlizards$predictors[c(3, 6, 27),
#' c("throat.PC1","throat.PC3", "SVL", "head.length")],
#' c(-5, 1.5, 1, 0.1))
#' rownames(newpred)[4] <- "lizard059"
#'
#' newdata <- list(contests = data.frame(
#' winner = factor(c("lizard048", "lizard059"),
#' levels = c("lizard006", "lizard011",
#' "lizard048", "lizard059")),
#' loser = factor(c("lizard006", "lizard011"),
#' levels = c("lizard006", "lizard011",
#' "lizard048", "lizard059"))
#' ),
#' predictors = newpred)
#'
#' ## can only predict at population level for contest with new lizard
#' predict(Whiting.model3, level = 0:1, se.fit = TRUE, newdata = newdata)
#'
#' ## predicting at specific levels of covariates
#'
#' ## consider a model from example(CEMS)
#' table6.model <- BTm(outcome = cbind(win1.adj, win2.adj),
#' player1 = school1, player2 = school2,
#' formula = ~ .. +
#' WOR[student] * Paris[..] +
#' WOR[student] * Milano[..] +
#' WOR[student] * Barcelona[..] +
#' DEG[student] * St.Gallen[..] +
#' STUD[student] * Paris[..] +
#' STUD[student] * St.Gallen[..] +
#' ENG[student] * St.Gallen[..] +
#' FRA[student] * London[..] +
#' FRA[student] * Paris[..] +
#' SPA[student] * Barcelona[..] +
#' ITA[student] * London[..] +
#' ITA[student] * Milano[..] +
#' SEX[student] * Milano[..],
#' refcat = "Stockholm",
#' data = CEMS)
#'
#' ## estimate abilities for a combination not seen in the original data
#'
#' ## same schools
#' schools <- levels(CEMS$preferences$school1)
#' ## new student data
#' students <- data.frame(STUD = "other", ENG = "good", FRA = "good",
#' SPA = "good", ITA = "good", WOR = "yes", DEG = "no",
#' SEX = "female", stringsAsFactors = FALSE)
#' ## set levels to be the same as original data
#' for (i in seq_len(ncol(students))){
#' students[,i] <- factor(students[,i], levels(CEMS$students[,i]))
#' }
#' newdata <- list(preferences =
#' data.frame(student = factor(500), # new id matching with `students[1,]`
#' school1 = factor("London", levels = schools),
#' school2 = factor("Paris", levels = schools)),
#' students = students,
#' schools = CEMS$schools)
#'
#' ## warning can be ignored as model specification was over-parameterized
#' predict(table6.model, newdata = newdata)
#'
#' ## if treatment contrasts are use (i.e. one player is set as the reference
#' ## category), then predicting the outcome of contests against the reference
#' ## is equivalent to estimating abilities with specific covariate values
#'
#' ## add student with all values at reference levels
#' students <- rbind(students,
#' data.frame(STUD = "other", ENG = "good", FRA = "good",
#' SPA = "good", ITA = "good", WOR = "no", DEG = "no",
#' SEX = "female", stringsAsFactors = FALSE))
#' ## set levels to be the same as original data
#' for (i in seq_len(ncol(students))){
#' students[,i] <- factor(students[,i], levels(CEMS$students[,i]))
#' }
#' newdata <- list(preferences =
#' data.frame(student = factor(rep(c(500, 502), each = 6)),
#' school1 = factor(schools, levels = schools),
#' school2 = factor("Stockholm", levels = schools)),
#' students = students,
#' schools = CEMS$schools)
#'
#' predict(table6.model, newdata = newdata, se.fit = TRUE)
#'
#' ## the second set of predictions (elements 7-12) are equivalent to the output
#' ## of BTabilities; the first set are adjust for `WOR` being equal to "yes"
#' BTabilities(table6.model)
#'
#' @importFrom stats model.matrix na.pass reformulate
#' @export
predict.BTm <- function (object, newdata = NULL,
level = ifelse(is.null(object$random), 0, 1),
type = c("link", "response", "terms"), se.fit = FALSE,
dispersion = NULL, terms = NULL,
na.action = na.pass, ...) {
type <- match.arg(type)
if (!is.null(newdata)) {
## need to define X so will work with model terms
setup <- match(c("player1", "player2", "formula", "id",
"separate.ability", "refcat", "weights",
"subset", "offset", "contrasts"), names(object$call),
0L)
setup <- do.call(BTm.setup,
c(as.list(object$call)[setup], list(data = newdata)),
envir = environment(object$formula))
nfix <- length(object$coefficients)
newdata <- data.frame(matrix(, nrow(setup$X), 0))
keep <- as.logical(match(colnames(setup$X), names(object$coefficients),
nomatch = 0))
if (any(!keep)){
## new players with missing data - set to NA
missing <- rowSums(setup$X[,!keep, drop = FALSE]) != 0
setup$X <- setup$X[, keep, drop = FALSE]
setup$X[missing,] <- NA
}
if (ncol(setup$X) != nfix) {
## newdata does not include original players with missing data
X <- matrix(0, nrow(setup$X), nfix,
dimnames = list(rownames(setup$X),
names(object$coefficients)))
X[, colnames(setup$X)] <- setup$X
newdata$X <- X
}
else newdata$X <- setup$X
nran <- length(attr(object$coefficients, "random"))
if (1 %in% level && !is.null(object$random) && type != "terms"){
if (ncol(setup$random) != nran) {
## expand to give col for every random effect
Z <- matrix(0, nrow(setup$random), nran,
dimnames = list(rownames(setup$random),
colnames(object$random))) #ranef need names!!
## set to NA for contests with new players
## (with predictors present)
miss <- !colnames(setup$random) %in% colnames(Z)
Z[, colnames(setup$random)[!miss]] <- setup$random[,!miss]
if (any(miss)) {
miss <- rowSums(setup$random[, miss, drop = FALSE] != 0) > 0
Z[miss,] <- NA
}
newrandom <- Z
}
else newrandom <- setup$random
return(NextMethod(newrandom = newrandom))
}
}
if (type == "terms") {
object$x <- model.matrix(object)
attr(object$x, "assign") <- object$assign
id <- unique(object$assign)
terms <- paste("X", id, sep = "")
object$terms <- terms(reformulate(c(0, terms)))
splitX <- function(X) {
newdata <- data.frame(matrix(, nrow(X), 0))
for (i in seq(id))
newdata[terms[i]] <- X[,object$assign == id[i]]
newdata
}
if (is.null(newdata)) newdata <- splitX(object$x)
else newdata <- splitX(newdata$X)
tmp <- NextMethod(newdata = newdata)
#tmp$fit[tmp$se.fit == 0] <- NA
tmp$se.fit[tmp$se.fit == 0] <- NA
colnames(tmp$fit) <- colnames(tmp$se.fit) <-
c("(separate)"[0 %in% id], object$term.labels)
return(tmp)
}
else NextMethod()
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/predict.BTm.R
|
#' @importFrom stats coef naprint
#' @export
print.BTglmmPQL <- function (x, digits = max(3, getOption("digits") - 3), ...)
{
if (identical(x$sigma, 0)){
cat("PQL algorithm converged to fixed effects model\n")
return(NextMethod())
}
cat("\nCall: ", deparse(x$call), "\n", sep = "", fill = TRUE)
if (length(coef(x))) {
cat("Fixed effects:\n\n")
print.default(format(x$coefficients, digits = digits),
print.gap = 2, quote = FALSE)
}
else cat("No fixed effects\n\n")
cat("\nRandom Effects Std. Dev.:", x$sigma, "\n")
if (nzchar(mess <- naprint(x$na.action)))
cat("\n", mess, "\n", sep = "")
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/print.BTglmmPQL.R
|
#' @export
print.BTm <- function (x, ...)
{
cat("Bradley Terry model fit by ")
cat(x$method, "\n")
NextMethod()
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/print.BTm.R
|
#' @importFrom stats naprint printCoefmat symnum
#' @export
print.summary.BTglmmPQL <- function(x, digits = max(3, getOption("digits") - 3),
symbolic.cor = x$symbolic.cor,
signif.stars =
getOption("show.signif.stars"),
...) {
if (identical(x$sigma, 0)){
cat("PQL algorithm converged to fixed effects model\n")
return(NextMethod("print.summary"))
}
cat("\nCall:\n", deparse(x$call), sep = "", fill = TRUE)
p <- length(x$aliased)
tidy.zeros <- function(vec) ifelse(abs(vec) < 100 * .Machine$double.eps,
0, vec)
if (p == 0) {
cat("\nNo Fixed Effects\n")
}
else {
if (nsingular <- p - x$rank) {
cat("\nFixed Effects: (", nsingular,
" not defined because of singularities)\n", sep = "")
cn <- names(x$aliased)
pars <- matrix(NA, p, 4, dimnames = list(cn, colnames(x$fixef)))
pars[!x$aliased, ] <- tidy.zeros(x$fixef)
}
else {
cat("\nFixed Effects:\n")
pars <- tidy.zeros(x$fixef)
}
printCoefmat(pars, digits = digits, signif.stars = signif.stars,
na.print = "NA", ...)
}
cat("\n(Dispersion parameter for ", x$family$family,
" family taken to be 1)\n", sep = "")
cat("\nRandom Effects:\n")
pars <- tidy.zeros(x$ranef)
printCoefmat(pars, digits = digits, signif.stars = signif.stars,
na.print = "NA", ...)
if (nzchar(mess <- naprint(x$na.action)))
cat("\n", mess, "\n", sep = "")
cat("\nNumber of iterations: ", x$iter, "\n", sep = "")
correl <- x$correlation
if (!is.null(correl)) {
if (x$rank > 1) {
cat("\nCorrelation of Coefficients:\n")
if (is.logical(symbolic.cor) && symbolic.cor) {
print(symnum(correl, abbr.colnames = NULL))
}
else {
correl <- format(round(correl, 2), nsmall = 2,
digits = digits)
correl[!lower.tri(correl)] <- ""
print(correl[-1, -x$rank, drop = FALSE], quote = FALSE)
}
}
}
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/print.summary.glmmPQL.R
|
#' Quasi Variances for Estimated Abilities
#'
#' A method for [qvcalc::qvcalc()] to compute a set of quasi variances (and
#' corresponding quasi standard errors) for estimated abilities from a
#' Bradley-Terry model as returned by [BTabilities()].
#'
#' For details of the method see Firth (2000), Firth (2003) or Firth and de
#' Menezes (2004). Quasi variances generalize and improve the accuracy of
#' \dQuote{floating absolute risk} (Easton et al., 1991). This device for
#' economical model summary was first suggested by Ridout (1989).
#'
#' Ordinarily the quasi variances are positive and so their square roots
#' (the quasi standard errors) exist and can be used in plots, etc.
#'
#' @param object a `"BTabilities"` object as returned by [BTabilities()].
#' @param ... additional arguments, currently ignored.
#' @return A list of class `"qv"`, with components
#' \item{covmat}{The full variance-covariance matrix for the estimated
#' abilities.}
#' \item{qvframe}{A data frame with variables `estimate`, `SE`, `quasiSE` and
#' `quasiVar`, the last two being a quasi standard error and quasi-variance
#' for each ability.}
#' \item{dispersion}{`NULL` (dispersion is fixed to 1).}
#' \item{relerrs}{Relative errors for approximating the standard errors of all
#' simple contrasts.}
#' \item{factorname}{The name of the ID factor identifying players in the `BTm`
#' formula.}
#' \item{coef.indices}{`NULL` (no required for this method).}
#' \item{modelcall}{The call to `BTm` to fit the Bradley-Terry model from which
#' the abilities were estimated.}
#' @references
#' Easton, D. F, Peto, J. and Babiker, A. G. A. G. (1991) Floating absolute
#' risk: an alternative to relative risk in survival and case-control analysis
#' avoiding an arbitrary reference group. *Statistics in Medicine* **10**,
#' 1025--1035.
#'
#' Firth, D. (2000) Quasi-variances in Xlisp-Stat and on the web.
#' *Journal of Statistical Software* **5.4**, 1--13.
#' \url{https://www.jstatsoft.org/article/view/v005i04}.
#'
#' Firth, D. (2003) Overcoming the reference category problem in the
#' presentation of statistical models. *Sociological Methodology*
#' **33**, 1--18.
#'
#' Firth, D. and de Menezes, R. X. (2004) Quasi-variances.
#' *Biometrika* **91**, 65--80.
#'
#' Menezes, R. X. de (1999) More useful standard errors for group and factor
#' effects in generalized linear models. *D.Phil. Thesis*,
#' Department of Statistics, University of Oxford.
#'
#' Ridout, M.S. (1989). Summarizing the results of fitting generalized
#' linear models to data from designed experiments. In: *Statistical
#' Modelling: Proceedings of GLIM89 and the 4th International
#' Workshop on Statistical Modelling held in Trento, Italy, July 17--21,
#' 1989* (A. Decarli et al., eds.), pp 262--269. New York: Springer.
#' @author David Firth
#' @seealso [qvcalc::worstErrors()], [qvcalc::plot.qv()].
#' @examples
#' example(baseball)
#' baseball.qv <- qvcalc(BTabilities(baseballModel2))
#' print(baseball.qv)
#' plot(baseball.qv, xlab = "team",
#' levelNames = c("Bal", "Bos", "Cle", "Det", "Mil", "NY", "Tor"))
#' @method qvcalc BTabilities
#' @importFrom qvcalc qvcalc.default
#' @importFrom stats coef vcov
#' @export
qvcalc.BTabilities <- function(object, ...){
vc <- vcov(object)
cf <- coef(object)
factorname <- attr(object, "factorname")
modelcall <- attr(object, "modelcall")
qvcalc.default(vc,
factorname = factorname,
estimates = cf,
modelcall = modelcall)
}
#' @importFrom qvcalc qvcalc
#' @export
qvcalc::qvcalc
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/qvcalc.BTabilities.R
|
#' Residuals from a Bradley-Terry Model
#'
#' Computes residuals from a model object of class `"BTm"`. In additional
#' to the usual options for objects inheriting from class `"glm"`, a
#' `"grouped"` option is implemented to compute player-specific residuals
#' suitable for diagnostic checking of a predictor involving player-level
#' covariates.
#'
#' For `type` other than `"grouped"` see [residuals.glm()].
#'
#' For `type = "grouped"` the residuals returned are weighted means of
#' working residuals, with weights equal to the binomial denominators in the
#' fitted model. These are suitable for diagnostic model checking, for example
#' plotting against candidate predictors.
#'
#' @param object a model object for which `inherits(model, "BTm")` is
#' `TRUE`.
#' @param type the type of residuals which should be returned. The
#' alternatives are: `"deviance"` (default), `"pearson"`,
#' `"working"`, `"response"`, and `"partial"`.
#' @param by the grouping factor to use when `type = "grouped"`.
#' @param ... arguments to pass on other methods.
#' @return A numeric vector of length equal to the number of players, with a
#' `"weights"` attribute.
#' @author David Firth and Heather Turner
#' @seealso [BTm()], [BTabilities()]
#' @references Firth, D. (2005) Bradley-Terry models in R. *Journal of
#' Statistical Software* **12**(1), 1--12.
#'
#' Turner, H. and Firth, D. (2012) Bradley-Terry models in R: The BradleyTerry2
#' package. *Journal of Statistical Software*, **48**(9), 1--21.
#' @keywords models
#' @examples
#'
#' ##
#' ## See ?springall
#' ##
#' springall.model <- BTm(cbind(win.adj, loss.adj),
#' col, row,
#' ~ flav[..] + gel[..] +
#' flav.2[..] + gel.2[..] + flav.gel[..] + (1 | ..),
#' data = springall)
#' res <- residuals(springall.model, type = "grouped")
#' with(springall$predictors, plot(flav, res))
#' with(springall$predictors, plot(gel, res))
#' ## Weighted least-squares regression of these residuals on any variable
#' ## already included in the model yields slope coefficient zero:
#' lm(res ~ flav, weights = attr(res, "weights"),
#' data = springall$predictors)
#' lm(res ~ gel, weights = attr(res, "weights"),
#' data = springall$predictors)
#'
#' @importFrom stats as.formula model.frame model.matrix terms
#' @export
residuals.BTm <- function(object, type = c("deviance", "pearson", "working",
"response", "partial", "grouped"), by = object$id,
...) {
type <- match.arg(type)
if (type != "grouped") return(NextMethod())
## for glm, lm would just be
## X <- model.matrix(formula, data = object$data)
formula <- as.formula(paste("~", by, "- 1"))
mt <- terms(formula)
mf1 <- model.frame(mt, data = c(object$player1, object$data))
X1 <- model.matrix(mt, data = mf1)
mf2 <- model.frame(mt, data = c(object$player2, object$data))
X2 <- model.matrix(mt, data = mf2)
X <- X1 - X2
r <- object$residuals ## the "working" residuals
w <- object$weights
total.resid <- crossprod(X, r * w)
total.weight <- crossprod(abs(X), w)
result <- total.resid / total.weight
attr(result, "weights") <- total.weight
result
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/residuals.BTm.R
|
#' Seed Germination Data from Crowder (1978)
#'
#' Data from Crowder(1978) giving the proportion of seeds germinated for 21
#' plates that were arranged according to a 2x2 factorial layout by seed
#' variety and type of root extract.
#'
#'
#' @name seeds
#' @docType data
#' @format A data frame with 21 observations on the following 4 variables.
#' \describe{
#' \item{r}{the number of germinated seeds.}
#' \item{n}{the total number of seeds.}
#' \item{seed}{the seed
#' variety.}
#' \item{extract}{the type of root extract.} }
#' @seealso [glmmPQL()]
#' @references Breslow, N. E. and Clayton, D. G. (1993) Approximate inference
#' in Generalized Linear Mixed Models. *Journal of the American
#' Statistical Association*, **88**(421), 9--25.
#' @source Crowder, M. (1978) Beta-Binomial ANOVA for proportions.
#' *Applied Statistics*, **27**, 34--37.
#' @keywords datasets
#' @examples
#'
#' summary(glmmPQL(cbind(r, n - r) ~ seed + extract,
#' random = diag(nrow(seeds)),
#' family = binomial,
#' data = seeds))
#'
"seeds"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/seeds.R
|
#' Kousgaard (1984) Data on Pair Comparisons of Sound Fields
#'
#' The results of a series of factorial subjective room acoustic experiments
#' carried out at the Technical University of Denmark by A C Gade.
#'
#' The variables `win1.adj` and `win2.adj` are provided in order to
#' allow a simple way of handling ties (in which a tie counts as half a win and
#' half a loss), which is slightly different numerically from the Davidson
#' (1970) method that is used by Kousgaard (1984): see the examples.
#'
#' @name sound.fields
#' @docType data
#' @format A list containing two data frames, `sound.fields$comparisons`,
#' and `sound.fields$design`.
#'
#' The `sound.fields$comparisons` data frame has 84 observations on the
#' following 8 variables: \describe{
#' \item{field1}{a factor with levels
#' `c("000", "001", "010", "011", "100", "101", "110", "111")`, the first
#' sound field in a comparison}
#' \item{field2}{a factor with the same
#' levels as `field1`; the second sound field in a comparison}
#' \item{win1}{integer, the number of times that `field1` was
#' preferred to `field2`}
#' \item{tie}{integer, the number of times
#' that no preference was expressed when comparing `field1` and
#' `field2`}
#' \item{win2}{integer, the number of times that
#' `field2` was preferred to `field1`}
#' \item{win1.adj}{numeric, equal to `win1 + tie/2`}
#' \item{win2.adj}{numeric, equal to `win2 + tie/2`}
#' \item{instrument}{a factor with 3 levels, `c("cello", "flute",
#' "violin")`} }
#'
#' The `sound.fields$design` data frame has 8 observations (one for each
#' of the sound fields compared in the experiment) on the following 3
#' variables: \describe{
#' \item{a")}{a factor with levels `c("0",
#' "1")`, the *direct sound* factor (0 for *obstructed sight line*, 1
#' for *free sight line*); contrasts are sum contrasts}
#' \item{b}{a
#' factor with levels `c("0", "1")`, the *reflection* factor (0 for
#' *-26dB*, 1 for *-20dB*); contrasts are sum contrasts}
#' \item{c}{a factor with levels `c("0", "1")`, the
#' *reverberation* factor (0 for *-24dB*, 1 for *-20dB*);
#' contrasts are sum contrasts} }
#' @author David Firth
#' @references Davidson, R. R. (1970) Extending the Bradley-Terry model to
#' accommodate ties in paired comparison experiments. *Journal of the
#' American Statistical Association* **65**, 317--328.
#' @source Kousgaard, N. (1984) Analysis of a Sound Field Experiment by a Model
#' for Paired Comparisons with Explanatory Variables. *Scandinavian
#' Journal of Statistics* **11**, 51--57.
#' @keywords datasets
#' @examples
#'
#' ##
#' ## Fit the Bradley-Terry model to data for flutes, using the simple
#' ## 'add 0.5' method to handle ties:
#' ##
#' flutes.model <- BTm(cbind(win1.adj, win2.adj), field1, field2, ~ field,
#' id = "field",
#' subset = (instrument == "flute"),
#' data = sound.fields)
#' ##
#' ## This agrees (after re-scaling) quite closely with the estimates given
#' ## in Table 3 of Kousgaard (1984):
#' ##
#' table3.flutes <- c(-0.581, -1.039, 0.347, 0.205, 0.276, 0.347, 0.311, 0.135)
#' plot(c(0, coef(flutes.model)), table3.flutes)
#' abline(lm(table3.flutes ~ c(0, coef(flutes.model))))
#' ##
#' ## Now re-parameterise that model in terms of the factorial effects, as
#' ## in Table 5 of Kousgaard (1984):
#' ##
#' flutes.model.reparam <- update(flutes.model,
#' formula = ~ a[field] * b[field] * c[field]
#' )
#' table5.flutes <- c(.267, .250, -.088, -.294, .062, .009, -0.070)
#' plot(coef(flutes.model.reparam), table5.flutes)
#' abline(lm(table5.flutes ~ coef(flutes.model.reparam)))
#'
"sound.fields"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/sound.fields.R
|
#' Springall (1973) Data on Subjective Evaluation of Flavour Strength
#'
#' Data from Section 7 of the paper by Springall (1973) on Bradley-Terry
#' response surface modelling. An experiment to assess the effects of gel and
#' flavour concentrations on the subjective assessment of flavour strength by
#' pair comparisons.
#'
#' The variables `win.adj` and `loss.adj` are provided in order to
#' allow a simple way of handling ties (in which a tie counts as half a win and
#' half a loss), which is slightly different numerically from the Rao and
#' Kupper (1967) model that Springall (1973) uses.
#'
#' @name springall
#' @docType data
#' @format A list containing two data frames, `springall$contests` and
#' `springall$predictors`.
#'
#' The `springall$contests` data frame has 36 observations (one for each
#' possible pairwise comparison of the 9 treatments) on the following 7
#' variables: \describe{
#' \item{row}{a factor with levels `1:9`,
#' the row number in Springall's dataset} #
#' \item{col}{a factor with
#' levels `1:9`, the column number in Springall's dataset}
#' \item{win}{integer, the number of wins for column treatment over row
#' treatment}
#' \item{loss}{integer, the number of wins for row treatment
#' over column treatment}
#' \item{tie}{integer, the number of ties
#' between row and column treatments}
#' \item{win.adj}{numeric, equal to
#' `win + tie/2`}
#' \item{loss.adj}{numeric, equal to `loss + tie/2`} }
#'
#' The `predictors` data frame has 9 observations (one for each treatment)
#' on the following 5 variables: \describe{
#' \item{flav}{numeric, the
#' flavour concentration}
#' \item{gel}{numeric, the gel concentration}
#' \item{flav.2}{numeric, equal to `flav^2`}
#' \item{gel.2}{numeric, equal to `gel^2`}
#' \item{flav.gel}{numeric, equal to `flav * gel`} }
#' @author David Firth
#' @references Rao, P. V. and Kupper, L. L. (1967) Ties in paired-comparison
#' experiments: a generalization of the Bradley-Terry model. *Journal of
#' the American Statistical Association*, **63**, 194--204.
#' @source Springall, A (1973) Response surface fitting using a generalization
#' of the Bradley-Terry paired comparison method. *Applied Statistics*
#' **22**, 59--68.
#' @keywords datasets
#' @examples
#'
#' ##
#' ## Fit the same response-surface model as in section 7 of
#' ## Springall (1973).
#' ##
#' ## Differences from Springall's fit are minor, arising from the
#' ## different treatment of ties.
#' ##
#' ## Springall's model in the paper does not include the random effect.
#' ## In this instance, however, that makes no difference: the random-effect
#' ## variance is estimated as zero.
#' ##
#' summary(springall.model <- BTm(cbind(win.adj, loss.adj), col, row,
#' ~ flav[..] + gel[..] +
#' flav.2[..] + gel.2[..] + flav.gel[..] +
#' (1 | ..),
#' data = springall))
#'
"springall"
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/springall.R
|
#' @importFrom stats coef pnorm
#' @export
summary.BTglmmPQL <- function(object, dispersion = NULL, correlation = FALSE,
symbolic.cor = FALSE, ...) {
if (identical(object$sigma, 0)){
ans <- NextMethod("summary")
ans$sigma <- 0
class(ans) <- c("summary.BTglmmPQL", class(ans))
return(ans)
}
aliased <- is.na(coef(object))
coefs <- coef(object)[!aliased]
cov.scaled <- cov.unscaled <- object$varFix # when dispersion != 1?
dn <- c("Estimate", "Std. Error", "z value", "Pr(>|z|)")
if (object$rank > 0) {
sterr <- sqrt(diag(cov.scaled))
tvalue <- coefs/sterr
pvalue <- 2 * pnorm(-abs(tvalue))
fixef.table <- cbind(coefs, sterr, tvalue, pvalue)
dimnames(fixef.table) <- list(names(coefs), dn)
}
else {
fixef.table <- matrix(, 0, 4)
dimnames(fixef.table) <- list(NULL, dn)
}
sterr <- sqrt(object$varSigma)
tvalue <- object$sigma/sterr
pvalue <- 2 * pnorm(-abs(tvalue))
ranef.table <- cbind(object$sigma, sterr, tvalue, pvalue)
dimnames(ranef.table) <- list("Std. Dev.", dn)
ans <- c(object[c("call", "family", "iter", "rank", "na.action")],
list(fixef = fixef.table, ranef = ranef.table,
aliased = aliased, dispersion = 1,
cov.unscaled = cov.unscaled))
if (correlation & object$rank > 0) {
dd <- sqrt(diag(cov.unscaled))
ans$correlation <- cov.unscaled/outer(dd, dd)
ans$symbolic.cor <- symbolic.cor
}
class(ans) <- "summary.BTglmmPQL"
ans
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/summary.BTglmmPQL.R
|
#' @export
vcov.BTglmmPQL <- function (object, ...)
{
so <- summary(object, corr = FALSE, ...)
so$dispersion * so$cov.unscaled
}
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/R/vcov.BTglmmPQL.R
|
### R code from vignette source 'BradleyTerry.Rnw'
### Encoding: UTF-8
###################################################
### code chunk number 1: set_options
###################################################
options(prompt = "R> ", continue = "+ ", width = 70,
useFancyQuotes = FALSE, digits = 7)
###################################################
### code chunk number 2: LoadBradleyTerry2
###################################################
library("BradleyTerry2")
###################################################
### code chunk number 3: CitationData
###################################################
data("citations", package = "BradleyTerry2")
###################################################
### code chunk number 4: CitationData2
###################################################
citations
###################################################
### code chunk number 5: countsToBinomial
###################################################
citations.sf <- countsToBinomial(citations)
names(citations.sf)[1:2] <- c("journal1", "journal2")
citations.sf
###################################################
### code chunk number 6: citeModel
###################################################
citeModel <- BTm(cbind(win1, win2), journal1, journal2, ~ journal,
id = "journal", data = citations.sf)
citeModel
###################################################
### code chunk number 7: citeModelupdate
###################################################
update(citeModel, refcat = "JASA")
###################################################
### code chunk number 8: citeModelupdate2
###################################################
update(citeModel, br = TRUE)
###################################################
### code chunk number 9: lizModel
###################################################
options(show.signif.stars = FALSE)
data("flatlizards", package = "BradleyTerry2")
lizModel <- BTm(1, winner, loser, ~ SVL[..] + (1|..),
data = flatlizards)
###################################################
### code chunk number 10: summarize_lizModel
###################################################
summary(lizModel)
###################################################
### code chunk number 11: lizModel2
###################################################
lizModel2 <- BTm(1, winner, loser,
~ throat.PC1[..] + throat.PC3[..] +
head.length[..] + SVL[..] + (1|..),
data = flatlizards)
summary(lizModel2)
###################################################
### code chunk number 12: baseball
###################################################
data("baseball", package = "BradleyTerry2")
head(baseball)
###################################################
### code chunk number 13: baseballModel
###################################################
baseballModel1 <- BTm(cbind(home.wins, away.wins), home.team, away.team,
data = baseball, id = "team")
summary(baseballModel1)
###################################################
### code chunk number 14: baseballDataUpdate
###################################################
baseball$home.team <- data.frame(team = baseball$home.team, at.home = 1)
baseball$away.team <- data.frame(team = baseball$away.team, at.home = 0)
###################################################
### code chunk number 15: baseballModelupdate
###################################################
baseballModel2 <- update(baseballModel1, formula = ~ team + at.home)
summary(baseballModel2)
###################################################
### code chunk number 16: CEMSmodel
###################################################
data("CEMS", package = "BradleyTerry2")
table8.model <- BTm(outcome = cbind(win1.adj, win2.adj),
player1 = school1, player2 = school2, formula = ~ .. +
WOR[student] * LAT[..] + DEG[student] * St.Gallen[..] +
STUD[student] * Paris[..] + STUD[student] * St.Gallen[..] +
ENG[student] * St.Gallen[..] + FRA[student] * London[..] +
FRA[student] * Paris[..] + SPA[student] * Barcelona[..] +
ITA[student] * London[..] + ITA[student] * Milano[..] +
SEX[student] * Milano[..],
refcat = "Stockholm", data = CEMS)
###################################################
### code chunk number 17: BTabilities
###################################################
BTabilities(baseballModel2)
###################################################
### code chunk number 18: BTabilities2
###################################################
head(BTabilities(lizModel2), 4)
###################################################
### code chunk number 19: residuals
###################################################
res.pearson <- round(residuals(lizModel2), 3)
head(cbind(flatlizards$contests, res.pearson), 4)
###################################################
### code chunk number 20: BTresiduals
###################################################
res <- residuals(lizModel2, type = "grouped")
# with(flatlizards$predictors, plot(throat.PC2, res))
# with(flatlizards$predictors, plot(head.width, res))
###################################################
### code chunk number 21: residualWLS
###################################################
lm(res ~ throat.PC1, weights = attr(res, "weights"),
data = flatlizards$predictors)
lm(res ~ head.length, weights = attr(res, "weights"),
data = flatlizards$predictors)
###################################################
### code chunk number 22: baseballModel2_call
###################################################
baseballModel2$call
###################################################
### code chunk number 23: str_baseball
###################################################
str(baseball, vec.len = 2)
###################################################
### code chunk number 24: first_comparison
###################################################
baseball$home.team[1,]
baseball$away.team[1,]
###################################################
### code chunk number 25: first_outcome
###################################################
baseball[1, c("home.wins", "away.wins")]
###################################################
### code chunk number 26: str_CEMS
###################################################
str(CEMS, vec.len = 2)
###################################################
### code chunk number 27: student-specific_data
###################################################
library("prefmod")
student <- cemspc[c("ENG", "SEX")]
student$ENG <- factor(student$ENG, levels = 1:2,
labels = c("good", "poor"))
student$SEX <- factor(student$SEX, levels = 1:2,
labels = c("female", "male"))
###################################################
### code chunk number 28: student_factor
###################################################
cems <- list(student = student)
student <- gl(303, 1, 303 * 15) #303 students, 15 comparisons
contest <- data.frame(student = student)
###################################################
### code chunk number 29: binomial_response
###################################################
win <- cemspc[, 1:15] == 0
lose <- cemspc[, 1:15] == 2
draw <- cemspc[, 1:15] == 1
contest$win.adj <- c(win + draw/2)
contest$lose.adj <- c(lose + draw/2)
###################################################
### code chunk number 30: school_factors
###################################################
lab <- c("London", "Paris", "Milano", "St. Gallen", "Barcelona",
"Stockholm")
contest$school1 <- factor(sequence(1:5), levels = 1:6, labels = lab)
contest$school2 <- factor(rep(2:6, 1:5), levels = 1:6, labels = lab)
###################################################
### code chunk number 31: cems_data
###################################################
cems$contest <- contest
###################################################
### code chunk number 32: functions
###################################################
## cf. prompt
options(width = 55)
for (fn in getNamespaceExports("BradleyTerry2")) {
name <- as.name(fn)
args <- formals(fn)
n <- length(args)
arg.names <- arg.n <- names(args)
arg.n[arg.n == "..."] <- "\\dots"
is.missing.arg <- function(arg) typeof(arg) == "symbol" &&
deparse(arg) == ""
Call <- paste(name, "(", sep = "")
for (i in seq_len(n)) {
Call <- paste(Call, arg.names[i], if (!is.missing.arg(args[[i]]))
paste(" = ", paste(deparse(args[[i]]),
collapse = "\n"), sep = ""), sep = "")
if (i != n)
Call <- paste(Call, ", ", sep = "")
}
Call <- paste(Call, ")", sep = "")
cat(deparse(parse(text = Call)[[1]], width.cutoff = 50), fill = TRUE)
}
options(width = 60)
|
/scratch/gouwar.j/cran-all/cranData/BradleyTerry2/inst/doc/BradleyTerry.R
|
### This file is for internal functions that may be re-used by a variety of graph types.
## Annotating different types of diagrams.
##
## Histogram annotation.
# removed .AddXMLhistogram = function(diag) {
# doc
# }
## Annotating title elements
.AddXMLAddTitle <- function(root, title = "", longTitle = paste("Title:", title), id = NULL) {
titleId <- ifelse(is.null(id), .AddXMLmakeId("main", "1.1"), id)
annotation <- .AddXMLAddAnnotation(root, position = 1, titleId, kind = "active")
XML::addAttributes(annotation$root, speech = paste("Title:", title), speech2 = longTitle, type = "Title")
return(invisible(annotation))
}
## Annotating axes
##
## Add axis to XML it is important that you give it a correct axis
.AddXMLAddAxis <- function(root, values = NULL, label = "", groupPosition = ifelse(axis == "x", 2, 3), axis, name = paste(axis, "axis:"), groupId = paste0(axis, "axis"), labelId = paste0(axis, "lab"), lineId = ifelse(axis == "x", "bottom", "left"), ...) {
position <- 0
labelNode <- .AddXMLAxisLabel(root,
label = label, position = position <- position + 1,
id = labelId, axis = groupId, ...
)
# Shouldn't try to add lineNode if this is a ggplot
lineNode <- .AddXMLAxisLine(root, id = lineId, axis = groupId)
tickNodes <- .AddXMLAxisValues(root,
values = values,
position = position <- position + 1, id = lineId, axis = groupId, ...
)
annotations <- c(list(labelNode, lineNode), tickNodes)
.AddXMLAxisGroup(root, groupId, name,
values = values, label = label,
annotations = annotations, position = groupPosition, ...
)
}
## Aux method for axis group
.AddXMLAxisGroup <- function(root, id, name, values = NULL, label = "", annotations = NULL, position = 1, speechShort = paste(name, label), speechLong = paste(name, label, "with values from", values[1], "to", values[length(values)]), ...) {
annotation <- .AddXMLAddAnnotation(root, position = position, id = id, kind = "grouped")
.AddXMLAddComponents(annotation, annotations)
.AddXMLAddChildren(annotation, annotations)
.AddXMLAddParents(annotation, annotations)
XML::addAttributes(annotation$root,
speech = speechShort,
speech2 = speechLong,
type = "Axis"
)
return(invisible(annotation))
}
## Aux methods for axes annotation.
##
## Axis labelling
.AddXMLAxisLabel <- function(root, label = "", position = 1, id = "", axis = "", speechShort = paste("Label", label),
speechLong = speechShort, fullLabelId = NULL, ...) {
labelId <- ifelse(is.null(fullLabelId), .AddXMLmakeId(id, "1.1"), fullLabelId)
annotation <- .AddXMLAddAnnotation(root, position = position, id = labelId, kind = "active")
XML::addAttributes(annotation$root, speech = speechShort, speech2 = speechLong, type = "Label")
return(invisible(annotation))
}
## Axis line
.AddXMLAxisLine <- function(root, position = 1, id = "", axis = "") {
annotation <- .AddXMLAddAnnotation(root,
position = position,
id = .AddXMLmakeId(id, "axis", "line", "1.1"), kind = "passive"
)
XML::addAttributes(annotation$root, type = "Line")
return(invisible(annotation))
}
## Axis values and ticks
.AddXMLAxisValues <- function(root, values = NULL, detailedValues = values, position = 1, id = "", axis = "",
fullTickLabelId = NULL, ...) {
annotations <- list()
if (length(values) <= 0) {
return(invisible(annotations))
}
for (i in 1:length(values)) {
valueId <- ifelse(is.null(fullTickLabelId),
.AddXMLmakeId(id, "axis", "labels", paste("1.1", i, sep = ".")),
paste(fullTickLabelId, i, sep = ".")
)
value <- .AddXMLAddAnnotation(root,
position = position + i - 1,
id = valueId, kind = "active"
)
XML::addAttributes(value$root, speech = paste("Tick mark", values[i]), speech2 = detailedValues[i], type = "Value")
tickId <- .AddXMLmakeId(id, "axis", "ticks", paste("1.1", i, sep = "."))
tick <- .AddXMLAddAnnotation(root, id = tickId, kind = "passive")
XML::addAttributes(tick$root, type = "Tick")
.AddXMLAddNode(value$component, "passive", tickId)
.AddXMLAddNode(tick$component, "active", valueId)
annotations[[2 * i - 1]] <- value
annotations[[2 * i]] <- tick
}
return(invisible(annotations))
}
## Constructs the center of the histogram
.AddXMLAddHistogramCenter <- function(root, hist = NULL) {
annotation <- .AddXMLAddAnnotation(root, position = 4, id = "center", kind = "grouped")
XML::addAttributes(annotation$root,
speech = "Histogram bars",
speech2 = paste("Histogram with", length(hist$mids), "bars"),
type = "Center"
)
annotations <- list()
for (i in 1:length(hist$mids)) {
annotations[[i]] <- .AddXMLGGplotGeomItem.bar(root,
position = i, x = hist$mids[i],
count = hist$counts[i], density = hist$density[i],
start = hist$breaks[i], end = hist$breaks[i + 1],
categorical = FALSE
)
}
.AddXMLAddComponents(annotation, annotations)
.AddXMLAddChildren(annotation, annotations)
.AddXMLAddParents(annotation, annotations)
return(invisible(annotation))
}
#' Summarise a ggplot layer data.
#'
#' This will create a list with a elements that summarise a certain section of data.
#' It uses the .SplitData function which is also used by the RewriteSVG function so
#' it should all line up.
#'
#' You will know the element names of each of the section elements in the returned list
#' as you will have given the function that processes the dfs.
#'
#' @param data The data for particular layer
#' @param FUN The function which will summarise the certain sections of data
#' @param overlap Whether the data sections should have overlapping elements at their ends.
#' It is used for GeomLines and such where they are connected.
#'
#' @note
#' You should use the .data$ prefix when references the value in the data frame. This helps prevent a note in the cmd check
#'
#' @return A list of length <= 5 that has each element as summary of the section of data.
.AddXMLSummariseGGPlotLayer <- function(data, FUN = function(x) {
x
}, overlap = FALSE) {
.SplitData(seq_along(data$x), overlapping = overlap) |>
lapply(function(indexs) {
data |>
dplyr::slice(indexs) |>
tidyr::drop_na(.data$x, .data$y) |>
dplyr::distinct() |>
FUN()
})
}
#' Add XML elements to make it work with a ggplot layers svg elements
#'
#' The layer classes it uses are the ones which are given by the VIstruct command.
#' So rather then GeomLine it line and GeomPoint is point etc.
#'
#' @param root the XML annotation tag root.
#' @param layerRoot The root of this layer annotation used to add the speech to it which is layer specific.
#' @param graphObjectStruct This is the struct that is produced by sending the ggplot graph to VIstruct
#' It should only be for the specific layer.
#' @param geomID This is the geomID and should match the SVG element ID that encompasses
#' All of the individual layer svg elements
#' @param panel The panel of te plot this is on. There is currently no implementation
#' that supports the panel
#' @param summarisedSections How many sections data should be summarised to.
#' This is also the max amount of data that can exist before it is summarised
#' @param ... These can be passed on to specific layer geoms.
#' However due to how this is called in the AddXML it isnt used.
#'
#' @return The annotation that covers this graph layer
.AddXMLAddGGPlotLayer <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
UseMethod(".AddXMLAddGGPlotLayer", graphObjectStruct)
}
.AddXMLAddGGPlotLayer.point <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
# Rmeove all the NAs in the data
data <- graphObjectStruct$data |>
tidyr::drop_na(.data$x, .data$y)
numberOfPoints <- nrow(data)
XML::addAttributes(layerRoot,
speech = "Point graph",
speech2 = paste("Point graph with", numberOfPoints, "points"),
type = "Center"
)
# Going to provide warning about using unknown shapes
if (!all(data$shape %in% c(16, 19))) {
warning("You are using a non default point shape. Currently the location of that point in the webpage is incorrect. The summaring information is unaffected.")
}
# Summarise into section when greater than 10 points
if (numberOfPoints > 5) {
mean_sd_num <- data |>
arrange(.data$x) |>
.AddXMLSummariseGGPlotLayer(function(data) {
data |>
dplyr::summarise(mean = mean(.data$y), sd = ifelse(is.na(sd(.data$y)), 0, sd(.data$y)), count = n())
})
# Get the order of points
orderOfIDs <- data.frame(x = data$x, id = 1:length(data$x)) |>
dplyr::arrange(.data$x) |>
select(id) |>
unlist()
pointGroups <- .SplitData(1:numberOfPoints)
# For each summarized section create a annotation and return the list of annotations
mapply(
function(summarizedSectionNum, summarisedData) {
# Add summarized section
desc <- paste(
"mean:", .AddXMLFormatNumber(summarisedData$mean),
"sd:", .AddXMLFormatNumber(summarisedData$sd),
"n:", .AddXMLFormatNumber(summarisedData$count)
)
summarizedSectionAnnotation <- .AddXMLAddAnnotation(root,
summarizedSectionNum,
id = paste(geomID, letters[summarizedSectionNum], sep = "."),
kind = "grouped",
attributes = list(speech = desc)
)
# Add individual points
# Only do so if there are less than 100 points
# This is because the time taken to add all of the annotations is too long.
# TODO:: optimize XML interactions to allow more data to be handled.
if (length(data$x) < 100) {
pointsNumberToAdd <- orderOfIDs[pointGroups[[summarizedSectionNum]]]
pointAnnotations <- list()
pointAnnotations <- lapply(pointsNumberToAdd, function(pointID) {
i <- match(pointID, pointsNumberToAdd)
shape <- data$shape[pointID]
colour <- data$fill[pointID]
if (is.na(colour)) colour <- "black"
size <- data$size[pointID]
desc2 <- paste("Shape:", shape, "colour:", colour[1], "size:", .AddXMLFormatNumber(size))
.AddXMLAddAnnotation(root,
position = i,
id = paste(geomID, pointID, sep = "."),
attributes =
list(
speech = paste0("(", data$x[pointID], ", ", data$y[pointID], ")"),
speech2 = desc2
)
)
})
.AddXMLAddChildren(summarizedSectionAnnotation, pointAnnotations)
.AddXMLAddComponents(summarizedSectionAnnotation, pointAnnotations)
.AddXMLAddParents(summarizedSectionAnnotation, pointAnnotations)
}
summarizedSectionAnnotation
},
summarizedSectionNum = seq_along(mean_sd_num),
summarisedData = mean_sd_num,
SIMPLIFY = FALSE
)
} else {
# If there a so few points just create annotatino for each point and return list
mapply(
function(pointNum, pointData) {
desc <- paste0(
"(", .AddXMLFormatNumber(pointData$x),
.AddXMLFormatNumber(pointData$y), ")"
)
.AddXMLGGplotGeomItem(root,
graphObjectStruct,
position = pointNum,
id = paste(geomID, pointNum, sep = "."),
speech = desc
)
},
pointNum = seq_along(data$x),
pointData = data,
SIMPLIFY = FALSE
)
}
}
.AddXMLAddGGPlotLayer.smooth <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
data <- graphObjectStruct$data
XML::addAttributes(layerRoot,
speech = "Smoother graph",
speech2 = paste0("Smoother graph", ifelse(graphObjectStruct$ci, paste(" with", graphObjectStruct$level, "confidence bands"), ""), ""),
type = "Center"
)
if (!graphObjectStruct$ci) {
data$ymin <- 0
data$ymax <- 0
}
summarisedData <- .AddXMLSummariseGGPlotLayer(data, function(data) {
data |>
dplyr::mutate(startX = .data$x, endX = lead(.data$x), startY = .data$y, endY = lead(.data$y)) |>
dplyr::mutate(CIWidth = .data$ymax - .data$ymin) |>
tidyr::drop_na() |>
dplyr::mutate(slope = (.data$startY - .data$endY) / (.data$startX - .data$endX)) |>
dplyr::summarise(
min = min(.data$slope), max = max(.data$slope),
mean = mean(.data$slope), median = median(.data$slope),
avg_width = mean(.data$CIWidth), median_width = median(.data$CIWidth),
rangeCI = max(.data$CIWidth) - min(.data$CIWidth)
) |>
as.list()
})
# Go thorugh each summarised section and create a annotation for it.
mapply(
function(summarisedSectionData, i) {
sectionDesc <- paste(
"average slope: ", .AddXMLFormatNumber(summarisedSectionData$mean),
ifelse(graphObjectStruct$ci, paste("CI width:", .AddXMLFormatNumber(summarisedSectionData$avg_width), ""), "")
)
lineDesc <- paste(
"slope range:", paste0("(", .AddXMLFormatNumber(summarisedSectionData$min), ",", .AddXMLFormatNumber(summarisedSectionData$max), ")"),
"median slope:", .AddXMLFormatNumber(summarisedSectionData$median)
)
ciDesc <- ifelse(graphObjectStruct$ci,
paste(
"median CI width:", .AddXMLFormatNumber(summarisedSectionData$median_width),
"width range:", .AddXMLFormatNumber(summarisedSectionData$rangeCI)
), ""
)
.AddXMLGGplotGeomItem(root,
graphObjectStruct,
position = i,
id = geomID,
speech = sectionDesc,
lineDesc = lineDesc,
ciDesc = ciDesc,
layer = graphObjectStruct$layernum
)
},
summarisedSectionData = summarisedData,
i = seq_along(summarisedData),
SIMPLIFY = FALSE
)
}
.AddXMLAddGGPlotLayer.line <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
numberOfLines <- length(graphObjectStruct$lines)
XML::addAttributes(layerRoot,
speech = "Line graph",
speech2 = paste("Line graph with", numberOfLines, "lines"),
# Better to report #lines or #segs?
# Line can be discontinuous (comprised of polylines 1a, 1b, ...)
type = "Center"
)
# Loop through each line in the layer and create a annotation for each one of them.
mapply(
function(lineNum, lineData) {
lineData <- lineData$scaledata
disjointLine <- .IsGeomLineDisjoint(lineData)
# ID of the line g tag
lineGTagID <- .CreateID(geomID, lineNum)
## Create line g tag annotation with descriptions
lineGTagAnnotation <- .AddXMLAddAnnotation(root,
position = lineNum,
id = lineGTagID, kind = "grouped"
)
XML::addAttributes(lineGTagAnnotation$root,
speech = paste("Line", lineNum),
speech2 = ifelse(disjointLine,
paste("Line", lineNum, "is disjoint"),
paste("Line", lineNum, "with", lineData$x |> length() - 1, "segments")
),
type = "Center"
)
# Test if the lineData has na and by extension if there will be disjointness
if (disjointLine) {
# This bit of code was made iwth help from SO:
# https://stackoverflow.com/questions/75379649/split-a-df-into-a-list-with-groups-of-values-withouts-nas
disjointLines <- lineData |>
group_by(group = cumsum(is.na(.data$y))) |>
filter(!(is.na(.data$y) & n() > 1)) |>
group_split() |>
Filter(function(x) nrow(x) >= 2, x = _)
numOfDisjointLines <- length(disjointLines)
lineSeq <- seq_along(disjointLines)
} else {
lineSeq <- c(1)
}
# Make sure there are enough points to consitute a line
# If there are then loop through each of the disjoint lines
# When the line is whole it is simply treated as a special case of a single disjoint line.
segmentAnnotations <- if (disjointLine && numOfDisjointLines == 0) {
noLineAnnotation <- .AddXMLAddAnnotation(root,
position = 1,
id = geomID, kind = "active"
)
XML::addAttributes(noLineAnnotation,
speech = "There are not enough points for this line to actually be drawn.",
speech2 = "This means there are less than 2 points without that are sequential to each other in the data"
)
noLineAnnotation
} else {
# Create annotation for each disjoint line or single whole line
mapply(
function(disjointLineIndex) {
if (disjointLine) {
lineData <- disjointLines[[disjointLineIndex]]
lineCount <- lineData$x |> length() - 1
disjointLineGTag <- paste(geomID, paste0(lineNum, letters[disjointLineIndex]), sep = ".")
disjointLineAnnotation <- .AddXMLAddAnnotation(root,
position = disjointLineIndex,
id = disjointLineGTag, kind = "grouped"
)
XML::addAttributes(disjointLineAnnotation$root,
speech = paste("Disjoint Line", disjointLineIndex),
speech2 = paste(
"Disjoint Line", disjointLineIndex,
"with", lineCount, "segments"
)
)
} else {
lineCount <- nrow(lineData) - 1
}
if (lineCount > summarisedSections) {
slope_Range_Median <- .AddXMLSummariseGGPlotLayer(lineData, function(data) {
data |>
dplyr::mutate(startX = .data$x, endX = lead(.data$x), startY = .data$y, endY = lead(.data$y)) |>
tidyr::drop_na() |>
dplyr::select(matches("(start|end)\\w")) |>
dplyr::mutate(slope = (.data$startY - .data$endY) / (.data$startX - .data$endX)) |>
dplyr::summarise(min = min(.data$slope), max = max(.data$slope), median = median(.data$slope)) |>
as.list()
}, overlap = TRUE)
summarised <- TRUE
lineCount <- summarisedSections
} else {
summarised <- FALSE
# This just needs some value for the mapply to loop through correctly
slope_Range_Median <- 1:lineCount
}
splitData <- lineData$x |>
seq_along() |>
.SplitData(overlapping = TRUE)
subLineSegmentsAnnotations <- mapply(
function(i, splitIndices, lineData, summary) {
if (summarised) {
desc <- paste(
"slope range",
.AddXMLFormatNumber(summary$min),
"to",
.AddXMLFormatNumber(summary$max),
"with median",
.AddXMLFormatNumber(summary$median)
)
desc2 <- paste(
"x from ",
lineData$x[splitIndices[1]],
"to",
lineData$x[splitIndices |> tail(n = 1)],
"y from ",
lineData$y[splitIndices[1]],
"to",
lineData$y[splitIndices |> tail(n = 1)]
)
} else {
desc <- paste(
.AddXMLFormatNumber((lineData$y[i + 1] - lineData$y[i]) / (lineData$x[i + 1] - lineData$x[i])),
"slope from x",
.AddXMLFormatNumber(lineData$x[i]),
"to x",
.AddXMLFormatNumber(lineData$x[i + 1])
)
desc2 <- paste0(
"line from (",
.AddXMLFormatNumber(lineData$x[i]),
",",
.AddXMLFormatNumber(lineData$y[i]),
") to (",
.AddXMLFormatNumber(lineData$x[i + 1]),
",",
.AddXMLFormatNumber(lineData$y[i + 1]),
")"
)
}
.AddXMLGGplotGeomItem(root,
graphObjectStruct,
position = i,
id = .CreateID(ifelse(disjointLine, disjointLineGTag, lineGTagID), letters[i]),
speech = desc, speech2 = desc2
)
},
i = if (summarised) seq_along(splitData) else 1:lineCount,
splitIndices = splitData,
summary = slope_Range_Median,
MoreArgs = list(lineData = lineData),
SIMPLIFY = FALSE
) |>
suppressWarnings()
# If there are disjoint lines this loop through mutliple times
# If not this will looop through once and so it needs to just return the one element
if (disjointLine) {
.AddXMLAddComponents(disjointLineAnnotation, subLineSegmentsAnnotations)
.AddXMLAddChildren(disjointLineAnnotation, subLineSegmentsAnnotations)
.AddXMLAddParents(disjointLineAnnotation, subLineSegmentsAnnotations)
disjointLineAnnotation
} else {
subLineSegmentsAnnotations
}
},
disjointLineIndex = lineSeq,
SIMPLIFY = FALSE
)
}
# This is to effectivly delist the segment annotation.
if (!disjointLine) {
segmentAnnotations <- segmentAnnotations[[1]]
}
.AddXMLAddComponents(lineGTagAnnotation, segmentAnnotations)
.AddXMLAddChildren(lineGTagAnnotation, segmentAnnotations)
.AddXMLAddParents(lineGTagAnnotation, segmentAnnotations)
lineGTagAnnotation
},
lineNum = seq_along(graphObjectStruct$lines),
lineData = graphObjectStruct$lines,
SIMPLIFY = FALSE
)
}
.AddXMLAddGGPlotLayer.bar <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
data <- graphObjectStruct$data
barCount <- nrow(data)
XML::addAttributes(layerRoot,
speech = "Bar graph",
speech2 = paste("Bar graph with", barCount, "bars"),
type = "Center"
)
# TODO: histogram bars have density but other geom_bar objects won't
# Need to not fail if density not present
# Generally, need to deal with missing values better
mapply(
function(i, x, y, ymax, ymin, xmin, xmax, density) {
barId <- .CreateID(geomID, i)
# If no density values then assume it's a categorical x-axis
.AddXMLGGplotGeomItem(
root,
graphObjectStruct,
position = i,
x = signif(x, 4),
count = ymax - ymin,
density = ifelse(is.null(density), NA, density[i]),
start = signif(xmin, 4),
end = signif(xmax, 4),
id = barId,
categorical = is.null(density)
)
},
i = seq_along(data$y),
x = data$x,
y = data$y,
ymax = data$ymax, ymin = data$ymin,
xmax = data$xmax, xmin = data$xmin,
MoreArgs = (list(density = data$density)),
SIMPLIFY = FALSE
)
}
.AddXMLAddGGPlotLayer.default <- function(root, layerRoot, graphObjectStruct, geomID, panel = 1, summarisedSections = 5, ...) {
warning("This layer type: ", class(graphObjectStruct), " is not supported by MakeAccessibleSVG")
return(invisible())
}
#' Add geom item to the XML
#'
#' These functions are used by the .AddXMLAddGGplotLayer functions
#' There should be one function for each of the layer types.
#'
#' For some of them they are quite simple so they are defered to other types.
#' For other ones they can be quite complex.
#'
#' @param root This the the annotation root of the document
#' @param position The position of the item
#' @param id the text which will be in the first element which is a active/grouped etc tag.
#' @param speech The first description of the annotation
#' @param speech2 The second slightly more detailed description. Or it can be used to tell different information.
#' @param ... Extra parameters for particular types.
#' @param graphObject This is what the dispatch is run on.
#'
#' @return Wil return invisibly the annotation object as there are cases where it is
#' just the side effects you are after.
.AddXMLGGplotGeomItem <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech, ...) {
UseMethod(".AddXMLGGplotGeomItem", graphObject)
}
.AddXMLGGplotGeomItem.default <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech, ...) {
stop("This type is not supported: ", class(graphObject))
}
.AddXMLGGplotGeomItem.smooth <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech, lineDesc, ciDesc, layer, ...) {
annotation <- .AddXMLAddAnnotation(root, position = position, id = paste(id, letters[position], sep = "."), kind = "grouped")
XML::addAttributes(annotation$root, speech = speech, speech2 = speech2)
# Add in a reference to the seGrob if it exists
items <- .AddXMLAddAnnotation(root, 1,
id = .CreateID(layer, "smoother_line", letters[position]),
attributes = list(speech = lineDesc)
) |>
list()
if (ciDesc != "") {
items <- .AddXMLAddAnnotation(root, 2,
id = .CreateID(layer, "smoother_ci", letters[position]),
attributes = list(speech = ciDesc)
) |>
list() |>
append(items, values = _)
}
.AddXMLAddChildren(annotation, items)
.AddXMLAddComponents(annotation, items)
.AddXMLAddParents(annotation, items)
return(invisible(annotation))
}
.AddXMLGGplotGeomItem.point <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech, ...) {
annotation <- .AddXMLAddAnnotation(root, position = position, id = id, kind = "active")
XML::addAttributes(annotation$root, speech = speech, speech2 = speech)
return(invisible(annotation))
}
.AddXMLGGplotGeomItem.bar <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech,
x = NULL, count = NULL, density = NULL, start = NULL, end = NULL,
categorical = TRUE, ...) {
rectId <- ifelse(is.null(id), .AddXMLmakeId("rect", .CreateID("1.1", position)), id)
annotation <- .AddXMLAddAnnotation(root,
position = position,
id = rectId,
kind = "active"
)
if (categorical) {
XML::addAttributes(annotation$root,
speech = paste("Bar", position, "at", x, "with value", count),
speech2 = paste("Bar", position, "at x value", x, " with y value", count),
type = "Bar"
)
} else {
XML::addAttributes(annotation$root,
speech = paste("Bar", position, "at", x, "with value", count),
speech2 = paste(
"Bar", position, "between x values", start,
"and", end, " with y value", count, "and density", signif(density, 3)
),
type = "Bar"
)
}
return(invisible(annotation))
}
.AddXMLGGplotGeomItem.line <- function(root, graphObject, position = 1, id = NULL, speech, speech2 = speech, ...) {
return(.AddXMLGGplotGeomItem.point(root, graphObject, position, id, speech, speech2))
}
## Auxiliary methods for annotations
##
## Construct a gridSVG id.
.AddXMLmakeId <- function(...) {
paste("graphics-plot-1", ..., sep = "-")
}
## Construct an SRE annotation element.
.AddXMLAddAnnotation <- function(root, position = 1, id = "", kind = "active", attributes = NULL) {
children <- list(
element = .AddXMLAddNode(NULL, kind, id),
position = .AddXMLAddNode(NULL, "position", position),
parents = .AddXMLAddNode(NULL, "parents"),
children = .AddXMLAddNode(NULL, "children"),
component = .AddXMLAddNode(NULL, "component"),
neighbours = .AddXMLAddNode(NULL, "neighbours")
)
annotation <- .AddXMLAddNode(root, "annotation", children = children, attrs = attributes)
node <- list(
root = annotation,
element = children$element,
position = children$position,
parents = children$parents,
children = children$children,
component = children$component,
neighbours = children$neighbours
)
return(invisible(node))
}
## Construct the basic XML annotation document.
.AddXMLDocument <- function(tag = "histogram") {
doc <- XML::newXMLDoc()
top <- XML::newXMLNode(tag, doc = doc)
XML::ensureNamespace(top, c(sre = "http://www.chemaccess.org/sre-schema"))
return(invisible(doc))
}
## Add a new node with tag name and optionally text content to the given root.
.AddXMLAddNode <- function(root, tag, content = NULL, children = list(content), attrs = NULL) {
node <- XML::newXMLNode(paste("sre:", tag, sep = ""),
content,
parent = root,
.children = children,
attrs = attrs
)
return(invisible(node))
}
# A shallow clone function for leaf nodes only. Avoids problems with duplicating
# namespaces.
.AddXMLclone <- function(root, node) {
newNode <- XML::newXMLNode(XML::xmlName(node, full = TRUE), XML::xmlValue(node), parent = root)
return(invisible(newNode))
}
## Add components to an annotation
.AddXMLAddComponents <- function(annotation, nodes) {
clone <- function(x) {
.AddXMLclone(annotation$component, x$element)
}
lapply(nodes, clone)
}
## Add children to an annotation
.AddXMLAddChildren <- function(annotation, nodes) {
clone <- function(x) {
if (XML::xmlName(x$element) != "passive") {
.AddXMLclone(annotation$children, x$element)
}
}
lapply(nodes, clone)
}
## Add parent to annotations
.AddXMLAddParents <- function(parent, nodes) {
clone <- function(x) .AddXMLclone(x$parents, parent$element)
lapply(nodes, clone)
}
## Store components for top level Element
# moved into the XML.histogram()
# assign(".AddXMLcomponents",list(), envir=BrailleR)
# not allowed.
.AddXMLStoreComponent <- function(CompSet, id, element) {
CompSet[[id]] <- element
return(invisible(CompSet))
}
# jg .AddXMLstoreComponent = function(id, element) {
# jg assign(".AddXMLcomponents[[id]]", element, envir = BrailleR)
# jg }
# vs We need to get the components into the topmost element.
.AddXMLAddChart <- function(root, children = NULL, speech = "", speech2 = "", type = "") {
annotation <- .AddXMLAddAnnotation(root, id = "chart", kind = "grouped")
XML::addAttributes(annotation$root, speech = speech, speech2 = speech2, type = type)
# jg .AddXMLAddComponents(annotation, get(.AddXMLcomponents, envir=BrailleR))
.AddXMLAddChildren(annotation, children)
.AddXMLAddParents(annotation, children)
return(invisible(annotation))
}
## Constructs the center of the timeseries
.AddXMLAddTimeseriesCenter <- function(root, ts = NULL) {
annotation <- .AddXMLAddAnnotation(root, position = 4, id = "center", kind = "grouped")
gs <- ts$GroupSummaries
len <- length(gs$N)
if (ts$Continuous) {
XML::addAttributes(
annotation$root,
speech = "Timeseries graph",
speech2 = paste(
"Continuous timeseries graph divided into",
len, "sub intervals of equal length"
),
type = "Center"
)
} else {
XML::addAttributes(
annotation$root,
speech = "Timeseries graph",
speech2 = paste("Timeseries graph with", len, "discrete segments"),
type = "Center"
)
}
annotations <- list()
for (i in 1:len) {
annotations[[i]] <- .AddXMLtimeseriesSegment(
root,
position = i, mean = gs$Mean[i], median = gs$Median[i], sd = gs$SD[i], n = gs$N[i]
)
}
annotations[[i + 1]] <- .AddXMLAddAnnotation(
root,
position = 0, id = .AddXMLmakeId("box", "1.1.1"), kind = "passive"
)
.AddXMLAddComponents(annotation, annotations)
.AddXMLAddChildren(annotation, annotations)
.AddXMLAddParents(annotation, annotations)
return(invisible(annotation))
}
.AddXMLtimeseriesSegment <-
function(root, position = 1, mean = NULL, median = NULL, sd = NULL, n = NULL) {
annotation <- .AddXMLAddAnnotation(
root,
position = position,
id = .AddXMLmakeId("lines", paste("1.1.1", intToUtf8(utf8ToInt("a") + (position - 1)), sep = "")),
kind = "active"
)
speech2 <- paste(
"Segment", position, "with", n, "data points, mean", signif(mean, 3),
"and median", signif(median, 3)
)
if (!is.na(sd)) {
speech2 <- paste(speech2, "and standard deviation", signif(sd, 3))
}
XML::addAttributes(annotation$root,
speech = paste("Segment", position, "with mean", signif(mean, 3)),
speech2 = speech2, type = "Segment"
)
return(invisible(annotation))
}
## Constructs the center of the histogram
.AddXMLAddBoxplotCenter <- function(root, boxplot = NULL) {
annotation <- .AddXMLAddAnnotation(root, position = 4, id = "center", kind = "grouped")
## vs sort out grammar:
## singular vs plural with $IsAre,
## sequence with commata and "and"
XML::addAttributes(annotation$root,
speech = paste(boxplot$Boxplots, boxplot$VertHorz),
speech2 = paste(
boxplot$Boxplots, boxplot$VertHorz,
"for", paste(boxplot$names, collapse = ", ")
),
type = "Center"
)
annotations <- list()
lastPos <- 8
i <- 0
outCount <- 1
for (i in 1:boxplot$NBox) {
quartiles <- boxplot$stats[, c(i)]
outliers <- boxplot$out[boxplot$group == i]
annotations[[i]] <- .AddXMLAddSingleBoxplot(root,
position = i, counter = lastPos,
quartiles = quartiles, outliers = outliers,
datapoints = boxplot$n[i], outCount = outCount,
name = boxplot$names[i]
)
lastPos <- ifelse(length(outliers) == 0, lastPos + 6, lastPos + 8)
outCount <- outCount + ifelse(length(outliers) > 0, 2, 1)
}
annotations[[i + 1]] <- .AddXMLAddAnnotation(
root,
position = 0, id = .AddXMLmakeId("box", "1.1.1"), kind = "passive"
)
.AddXMLAddComponents(annotation, annotations)
.AddXMLAddChildren(annotation, annotations)
.AddXMLAddParents(annotation, annotations)
return(invisible(annotation))
}
.AddXMLAddSingleBoxplot <-
function(root, position = 1, counter = 8, quartiles = NULL, outliers = NULL, datapoints = 0, name = "", outCount = 1) {
## Speech computations
## q1: Minimum or lower whisker
## q2: Lower Quartile
## q3: Median
## q4: Upper Quartile
## q5: Maximum or upper whisker
##
## References:
## http://www.bbc.co.uk/schools/gcsebitesize/maths/statistics/representingdata3hirev6.shtml
## https://www.khanacademy.org/math/probability/data-distributions-a1/box--whisker-plots-a1/v/reading-box-and-whisker-plots
q1 <- ifelse(suppressWarnings(min(outliers)) < quartiles[1],
paste("Lower whisker", quartiles[1]),
paste("Minimum", quartiles[1])
)
q2 <- paste("Lower quartile", quartiles[2])
q3 <- paste("Median", quartiles[3])
q4 <- paste("Upper quartile", quartiles[4])
q5 <- ifelse(suppressWarnings(max(outliers)) > quartiles[5],
paste("Upper whisker", quartiles[5]),
paste("Maximum", quartiles[5])
)
## Position counting:
## We go via the root element.
##
## We start at 8, always. Then count up 6 or 8 elements, depending on whether
## outliers a present.
##
## 1. Middle bar (median)
## 2. omitted
## 3. dashed bar
## 4. end bars
## 5. inner box
## 6. omitted
## 7. outliers (if present)
## 8. omitted (if 7 present)
annotation <- .AddXMLAddAnnotation(root,
position = position,
id = paste0("boxplot", position),
kind = "grouped"
)
annotations <- list()
annotations[[1]] <- .AddXMLAddAnnotation(
root,
position = 1, id = paste0("graphics-root.", counter), kind = "active"
)
XML::addAttributes(annotations[[1]]$root, speech = q3, type = "component")
annotations[[2]] <- .AddXMLAddAnnotation(
root,
position = 2, id = paste0("graphics-root.", counter + 2), kind = "passive"
)
annotations[[3]] <- .AddXMLAddAnnotation(
root,
position = 3, id = paste0("graphics-root.", counter + 4), kind = "active"
)
XML::addAttributes(annotations[[3]]$root,
speech = paste0(paste(q2, "and", q4), "."),
type = "component"
)
annotations[[4]] <- .AddXMLAddAnnotation(
root,
position = 4, id = paste0("graphics-root.", counter + 3), kind = "active"
)
XML::addAttributes(annotations[[4]]$root,
speech = paste0(paste(q1, "and", q5), "."),
type = "component"
)
speech <- paste(
"Boxplot", ifelse(name == "", "", paste("for", name)),
"and quartiles in", paste(quartiles, collapse = ", ")
)
speech2 <- paste(
"Boxplot", ifelse(name == "", "", paste("for", name)),
"for", datapoints, "datapoints.",
paste0(paste(q1, q2, q3, q4, q5, sep = ", "), ".")
)
if (length(outliers) > 0) {
## Add outliers
if (length(outliers) > 1) {
annotations[[5]] <- .AddXMLAddAnnotation(root,
position = 5,
id = paste0("outliers", position),
kind = "grouped"
)
.AddXMLOutliers(root, annotations[[5]], outliers, position = 1, outCount = outCount + 1)
name <- "outliers"
} else {
annotations[[5]] <- .AddXMLAddAnnotation(
root,
position = 5, id = paste0("graphics-root.", counter + 6), kind = "active"
)
name <- "outlier"
}
speech <- paste(speech, "and", length(outliers), name)
descr <- paste(length(outliers), name, "at", paste(outliers, collapse = ", "))
speech2 <- paste(speech2, descr)
XML::addAttributes(annotations[[5]]$root, speech = descr, type = "component")
} else {
speech2 <- paste(speech2, "No outliers")
}
XML::addAttributes(annotation$root, speech = speech, speech2 = speech2, type = "boxplot")
.AddXMLAddComponents(annotation, annotations)
.AddXMLAddChildren(annotation, annotations)
.AddXMLAddParents(annotation, annotations)
return(invisible(annotation))
}
.AddXMLOutliers <- function(root, parent, outliers, position = 1, id = "", outCount = 1) {
annotations <- list()
sortOut <- sort(outliers)
for (v in sortOut) {
annotation <- .AddXMLAddAnnotation(
root,
position = position,
id = .AddXMLmakeId("points", paste(outCount, "1", match(v, outliers), sep = ".")),
kind = "active"
)
XML::addAttributes(annotation$root,
speech = v,
speech2 = paste("Outlier", v), type = "point"
)
annotations <- append(annotations, list(annotation))
}
.AddXMLAddComponents(parent, annotations)
.AddXMLAddChildren(parent, annotations)
.AddXMLAddParents(parent, annotations)
return(invisible(annotations))
}
.AddXMLFormatNumber <- function(x) {
if (!is.nan(x) & ifelse(abs(x) < 1, nchar(as.character((abs(x)))) - 2, nchar(as.character((abs(x))))) > 8) {
useScientific <- TRUE
} else {
useScientific <- FALSE
}
format(x, digits = 4, scientific = useScientific)
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/AddXMLInternal.R
|
AddXML <- function(x, file) {
UseMethod("AddXML")
}
AddXML.default <-
function(x, file) {
return(invisible("nothing done"))
}
AddXML.boxplot <- function(x, file) {
doc <- .AddXMLDocument("boxplot")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddAxis(root, axis = "y", "annotations")
title <- .AddXMLAddTitle(annotations, title = x$ExtraArgs$main)
if (x$horizontal) {
xValues <- x$xTicks
yValues <- x$names
YMin <- min(xValues)
YMax <- max(xValues)
} else {
xValues <- x$names
yValues <- x$yTicks
YMin <- min(yValues)
YMax <- max(yValues)
}
if (x$horizontal) {
xSpeech <- paste("x axis", x$ExtraArgs$xlab, "ranges from", YMin, "to", YMax)
ySpeech <- paste("y axis with values", paste(yValues, collapse = ", "))
} else {
xSpeech <- paste("x axis with values", paste(xValues, collapse = ", "))
ySpeech <- paste("y axis", x$ExtraArgs$ylab, "ranges from", YMin, "to", YMax)
}
xAxis <- .AddXMLAddAxis(annotations, axis = "x", label = x$ExtraArgs$xlab, values = xValues, speechLong = xSpeech)
yAxis <- .AddXMLAddAxis(annotations, axis = "y", label = x$ExtraArgs$ylab, values = yValues, speechLong = ySpeech)
center <- .AddXMLAddBoxplotCenter(annotations, boxplot = x)
chart <- .AddXMLAddChart(annotations,
type = "BoxPlot",
speech = paste(x$Boxplots, "for", x$ExtraArgs$main),
speech2 = paste(x$Boxplots, "for", x$ExtraArgs$xlab, paste(x$names, collapse = ", ")),
children = list(title, xAxis, yAxis, center)
)
.AddXMLAddComponents(chart, list(title, xAxis, yAxis, center))
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.dotplot <- function(x, file) {
doc <- .AddXMLDocument("dotplot")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
.AddXMLAddAxis(annotations, axis = "x", label = x$ExtraArgs$xlab)
.AddXMLAddAxis(annotations, axis = "y", label = x$ExtraArgs$ylab)
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.eulerr <- function(x, file) {
doc <- .AddXMLDocument("eulerr")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.ggplot <- function(x, file) {
grid.force()
xs <- .VIstruct.ggplot(x)
doc <- .AddXMLDocument("ggplot")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
components <- list()
backgroundGrob <- grid.grep(gPath("panel.background..rect"), grep = TRUE)
titleGrob <- grid.grep(gPath("plot.title", "text"), grep = TRUE)
if (length(titleGrob) > 0) {
titleId <- paste0(titleGrob$name, ".1")
title <- .AddXMLAddTitle(annotations, title = xs$title, id = titleId)
components[[length(components) + 1]] <- title
}
xAxisLabelGrob <- paste0(
grid.grep(
gPath("xlab-b", "titleGrob", "text"),
grep = TRUE
)$name,
".1"
)
xAxisTickLabelGrob <- paste0(
grid.grep(
gPath("axis-b", "absoluteGrob", "axis", "axis", "titleGrob", "text"),
grep = TRUE
)$name,
".1"
)
xAxis <- .AddXMLAddAxis(annotations,
axis = "x",
label = xs$xaxis$xlabel,
values = xs$xaxis$xticklabels,
fullLabelId = xAxisLabelGrob,
fullTickLabelId = xAxisTickLabelGrob
)
components[[length(components) + 1]] <- xAxis
yAxisLabelGrob <- paste0(
grid.grep(
gPath("ylab-l", "titleGrob", "text"),
grep = TRUE
)$name,
".1"
)
yAxisTickLabelGrob <- paste0(
grid.grep(
gPath("axis-l", "absoluteGrob", "axis", "axis", "titleGrob", "text"),
grep = TRUE
)$name,
".1"
)
yAxis <- .AddXMLAddAxis(annotations,
axis = "y",
label = xs$yaxis$ylabel,
values = xs$yaxis$yticklabels,
fullLabelId = yAxisLabelGrob,
fullTickLabelId = yAxisTickLabelGrob
)
components[[length(components) + 1]] <- yAxis
if (xs$npanels == 1) {
for (layerNum in 1:xs$nlayers) {
layerGroupID <- paste("center", 1, layerNum, sep = "-")
layerAnnotation <- .AddXMLAddAnnotation(annotations,
position = 3 + layerNum,
id = layerGroupID, kind = "grouped"
)
layerStruct <- xs$panels[[1]]$panellayers[[layerNum]]
layerAnnotations <- .AddXMLAddGGPlotLayer(
annotations,
layerAnnotation$root,
structure(layerStruct, class = layerStruct$type),
.GetGeomID(x, layerNum)
)
# Keep moving if this layer is not supported
if (is.null(layerAnnotations)) {
next
}
.AddXMLAddComponents(layerAnnotation, layerAnnotations)
.AddXMLAddChildren(layerAnnotation, layerAnnotations)
.AddXMLAddParents(layerAnnotation, layerAnnotations)
components[[length(components) + 1]] <- layerAnnotation
}
}
# Else, should warn about not handling faceted charts -- or else handle them!
chart <- .AddXMLAddChart(annotations,
type = "Chart",
speech = paste(
ifelse(
is.null(xs$title),
"Chart",
paste("Chart with title ", xs$title)
),
" with x-axis ", xs$xaxis$xlabel,
" and y-axis ", xs$yaxis$ylabel
),
# Currently speech2 is same as speech
speech2 = paste(
ifelse(
is.null(xs$title),
"Chart",
paste("Chart with title ", xs$title)
),
" with x-axis ", xs$xaxis$xlabel,
" and y-axis ", xs$yaxis$ylabel
),
children = components
)
.AddXMLAddComponents(chart, components)
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.histogram <- function(x, file) {
doc <- .AddXMLDocument("histogram")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
# still need to allow for main and sub titles
title <- .AddXMLAddTitle(annotations, title = x$ExtraArgs$main)
xValues <- x$xTicks
XMax <- max(x$breaks, x$xTicks)
xAxis <- .AddXMLAddAxis(annotations,
axis = "x", label = x$ExtraArgs$xlab, values = xValues,
speechLong = paste("x axis", x$ExtraArgs$xlab, "ranges from 0 to", XMax)
)
AboveY <- x$yTicks
for (i in 1:length(x$yTicks)) {
AboveY[i] <- length(x$counts[x$counts > x$yTicks[i]])
}
yValues <- x$yTicks
DetYValues <- paste(AboveY, "of the", x$NBars, "bars exceed the", x$ExtraArgs$ylab, x$yTicks)
YMax <- max(x$counts, x$yTicks)
yAxis <- .AddXMLAddAxis(annotations,
axis = "y", label = x$ExtraArgs$ylab,
values = yValues, detailedValues = DetYValues,
speechLong = paste("y axis", x$ExtraArgs$ylab, "ranges from 0 to", YMax)
)
center <- .AddXMLAddHistogramCenter(annotations, hist = x)
chart <- .AddXMLAddChart(annotations,
type = "Histogram",
speech = paste("Histogram of", x$ExtraArgs$xlab),
speech2 = paste(
"Histogram showing ", x$NBars, "bars for ",
x$ExtraArgs$xlab, "over the range", min(x$breaks),
"to", max(x$breaks), "and", x$ExtraArgs$ylab,
"from 0 to", max(x$counts)
), # must allow for density
children = list(title, xAxis, yAxis, center)
)
.AddXMLAddComponents(chart, list(title, xAxis, yAxis, center))
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.scatterplot <- function(x, file) {
doc <- .AddXMLDocument("scatterplot")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
# still need to allow for main and sub titles
title <- .AddXMLAddTitle(annotations, title = x$ExtraArgs$main)
xValues <- x$xTicks
XMin <- min(x$xTicks)
XMax <- max(x$xTicks)
xAxis <- .AddXMLAddAxis(
annotations,
axis = "x", label = x$ExtraArgs$xlab, values = xValues,
speechLong = paste("x axis", x$ExtraArgs$xlab, "ranges from", XMin, "to", XMax)
)
yValues <- x$yTicks
YMin <- min(x$yTicks)
YMax <- max(x$yTicks)
yAxis <- .AddXMLAddAxis(
annotations,
axis = "y", label = x$ExtraArgs$ylab, values = yValues,
speechLong = paste("y axis", x$ExtraArgs$ylab, "ranges from", YMin, "to", YMax)
)
## now to add the other content related bits
center <- .AddXMLAddScatterCenter(annotations, sp = x)
chart <- .AddXMLAddChart(annotations,
type = "ScatterPlot",
speech = paste("Scatter plot of", x$ExtraArgs$ylab),
speech2 = paste(
"Scatter plot showing ",
x$ExtraArgs$ylab, "over the range", YMin,
"to", YMax, "for", x$ExtraArgs$ylab,
"which ranges from", XMin, "to", XMax
),
children = list(title, xAxis, yAxis, center)
)
.AddXMLAddComponents(chart, list(title, xAxis, yAxis, center))
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
AddXML.tsplot <- function(x, file) {
doc <- .AddXMLDocument("timeseriesplot")
root <- XML::xmlRoot(doc)
annotations <- .AddXMLAddNode(root, "annotations")
# still need to allow for main and sub titles
title <- .AddXMLAddTitle(annotations, title = x$ExtraArgs$main)
xValues <- x$xTicks
XMin <- min(x$xTicks)
XMax <- max(x$xTicks)
xAxis <- .AddXMLAddAxis(
annotations,
axis = "x", label = x$ExtraArgs$xlab, values = xValues,
speechLong = paste("x axis", x$ExtraArgs$xlab, "ranges from", XMin, "to", XMax)
)
yValues <- x$yTicks
YMin <- min(x$yTicks)
YMax <- max(x$yTicks)
yAxis <- .AddXMLAddAxis(
annotations,
axis = "x", label = x$ExtraArgs$ylab, values = yValues,
speechLong = paste("y axis", x$ExtraArgs$ylab, "ranges from", YMin, "to", YMax)
)
## now to add the other content related bits
center <- .AddXMLAddTimeseriesCenter(annotations, ts = x)
chart <- .AddXMLAddChart(annotations,
type = "TimeSeriesPlot",
speech = paste("Time series plot of", x$ExtraArgs$ylab),
speech2 = paste(
"Time series plot showing ",
x$ExtraArgs$ylab, "over the range", YMin,
"to", YMax, "for", x$ExtraArgs$ylab,
"which ranges from", XMin, "to", XMax
),
children = list(title, xAxis, yAxis, center)
)
.AddXMLAddComponents(chart, list(title, xAxis, yAxis, center))
XML::saveXML(doc = doc, file = file)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/AddXMLMethod.R
|
Augment = function(x) {
UseMethod("Augment")
}
Augment.default =
function(x) {
.NothingDoneGraph()
return(invisible(x))
}
Augment.Augmented =
function(x) {
return(invisible(x))
}
Augment.boxplot = function(x) {
x=.AugmentBase(x)
x$NBox = length(x$n)
x$VarGroup = .ifelse(x$NBox > 1, 'group', 'variable')
x$VarGroupUpp = .ifelse(x$NBox > 1, 'Group', 'This variable')
x$IsAre = .ifelse(x$NBox > 1, 'are', 'is')
x$Boxplots = .ifelse(x$NBox > 1, paste(x$NBox, 'boxplots'), 'a boxplot')
x$VertHorz = .ifelse(x$horizontal, 'horizontally', 'vertically')
##vs This should be done when one actually wants to use the names
##
## if (x$NBox > 1) {
## x$names = paste0('"', x$names, '"')
## } else {
## x$names = NULL
## }
return(invisible(x))
}
Augment.dotplot = function(x) {
x=.AugmentBase(x)
x$NPlot = length(x$vals)
x$VarGroup = .ifelse(x$NPlot > 1, 'group', 'variable')
x$VarGroupUpp = .ifelse(x$NPlot > 1, 'Group', 'This variable')
x$IsAre = .ifelse(x$NPlot > 1, 'are', 'is')
x$dotplots = .ifelse(x$NPlot > 1, paste(x$NPlot, 'dotplots'), 'a dotplot')
x$VertHorz = .ifelse(x$vertical, 'vertically', 'horizontally')
return(invisible(x))
}
Augment.eulerr =
function(x) {
X <- x[["coefficients"]][, 1L]
Y <- x[["coefficients"]][, 2L]
r <- x[["coefficients"]][, 3L]
x$TextPositions=list(x=X, y=Y)
return(invisible(x))
}
Augment.gg = Augment.ggplot = function(x) {
x$ExtraArgs$main <- .ifelse(is.null(x$labels$title), "", x$labels$title)
x$ExtraArgs$sub <- .ifelse(is.null(x$labels$subtitle), "", x$labels$subtitle)
x$ExtraArgs$xlab <- .ifelse(is.null(x$labels$x), "", x$labels$x)
x$ExtraArgs$ylab <- .ifelse(is.null(x$labels$y), "", x$labels$y)
class(x)=c(class(x), "Augmented") # order change here means updates are possible using functions in UpdateGraphs.R
return(invisible(x))
}
Augment.histogram = function(x) {
x$ExtraArgs$main <- if (is.null(x$ExtraArgs$main)) {paste("Histogram of", x$xname)} else {x$ExtraArgs$main}
x$ExtraArgs$xlab <- if (is.null(x$ExtraArgs$xlab)) {x$xname} else {x$ExtraArgs$xlab}
x$ExtraArgs$ylab <- if (is.null(x$ExtraArgs$ylab)) {"Frequency"} else {x$ExtraArgs$ylab}
x$NBars = length(x$counts)
x=.AugmentBase(x)
return(invisible(x))
}
Augment.scatterplot =
function(x) {
x=.AugmentBase(x)
VLength = nrow(x$data)
NBreaks= 6 #specified as something from 6 to 10 depending on how many obs there are.
Breaks = round(seq(0, VLength, length.out= NBreaks+1),0)
BinEnds =Breaks[-1]
BinStarts = Breaks[-(NBreaks+1)] + 1 # not overlapping
POI = list(MeanX=0, MedianX=0, MinX=0, MaxX=0, SDX=0, MeanY=0, MedianY=0, MinY=0, MaxY=0, SDY=0, CorXY=0, N=0) # and whatever else we like
for(i in 1:NBreaks){
POI$MeanX[i] = mean(x$data[BinStarts[i]:BinEnds[i], "x"])
POI$MeanY[i] = mean(x$data[BinStarts[i]:BinEnds[i], "y"])
POI$MedianX[i] = median(x$data[BinStarts[i]:BinEnds[i], "x"])
POI$MedianY[i] = median(x$data[BinStarts[i]:BinEnds[i], "y"])
POI$MinX[i] = min(x$data[BinStarts[i]:BinEnds[i], "x"])
POI$MinY[i] = min(x$data[BinStarts[i]:BinEnds[i], "y"])
POI$MaxX[i] = max(x$data[BinStarts[i]:BinEnds[i], "x"])
POI$MaxY[i] = max(x$data[BinStarts[i]:BinEnds[i], "y"])
POI$SDX[i] = sd(x$data[BinStarts[i]:BinEnds[i], "x"])
POI$SDY[i] = sd(x$data[BinStarts[i]:BinEnds[i], "y"])
POI$N[i] = nrow(x$data[BinStarts[i]:BinEnds[i], ])
POI$CorXY[i] = cor(x$data[BinStarts[i]:BinEnds[i], "x"], x$data[BinStarts[i]:BinEnds[i], "y"])
}
x$GroupSummaries = POI
return(invisible(x))
}
Augment.tsplot =
function(x) {
x$ExtraArgs$xlab <- if (is.null(x$ExtraArgs$xlab)) {"Time"} else {x$ExtraArgs$xlab}
x=.AugmentBase(x)
series =x [[1]]
if (is.na(match(NA, series))) {
x$GroupSummaries <- .TsSplitEqual(series, breaks=10)
x$Continuous <- TRUE
} else {
x$GroupSummaries <- .TsSplitDiscont(series)
x$Continuous <- FALSE
}
return(invisible(x))
}
.TsSplitDiscont = function(series) {
POI = list(Mean=vector(), Median=vector(), SD=vector(), N=vector())
current <- vector()
for(i in 1:length(series)) {
if (!is.na(series[i])) {
current <- append(current, series[i])
next
}
if (length(current) > 0) {
POI <- .TsSumSegment(POI, current)
current <- vector()
}
}
if (length(current) > 0) {
POI <- .TsSumSegment(POI, current)
}
}
.TsSumSegment = function(poi, segment, position=length(poi$N)+1) {
poi$Mean[position] = mean(segment, na.rm=T)
poi$Median[position] = median(segment, na.rm=T)
poi$SD[position] = sd(segment, na.rm=T)
poi$N[position] = sum(!is.na(segment))
return(invisible(poi))
}
.TsSplitEqual = function(series, breaks=10) {
NBreaks= 10 #specified as something from 6 to 10 depending on how many obs there are.
VLength = length(series)
Breaks = round(seq(0, VLength, length.out= NBreaks+1),0)
BinEnds =Breaks[-1]
BinStarts = Breaks[-(NBreaks+1)] + 1 # not overlapping
POI = list(Mean=0, Median= 0, SD=0, N=0) # and whatever else we like
for(i in 1:NBreaks){
POI <- .TsSumSegment(POI, series[BinStarts[i]:BinEnds[i]], i)
}
return(invisible(POI))
}
.AugmentBase = function(x){
x$par$xaxp = par()$xaxp
x$par$yaxp = par()$yaxp
x$xTicks = seq(x$par$xaxp[1], x$par$xaxp[2], length.out=x$par$xaxp[3]+1)
x$yTicks = seq(x$par$yaxp[1], x$par$yaxp[2], length.out=x$par$yaxp[3]+1)
x$ExtraArgs$main <- if (is.null(x$ExtraArgs$main)) {""} else {x$ExtraArgs$main}
x$ExtraArgs$sub <- if (is.null(x$ExtraArgs$sub)) {""} else {x$ExtraArgs$sub}
x$ExtraArgs$xlab <- if (is.null(x$ExtraArgs$xlab)) {""} else {x$ExtraArgs$xlab}
x$ExtraArgs$ylab <- if (is.null(x$ExtraArgs$ylab)) {""} else {x$ExtraArgs$ylab}
class(x)=c("Augmented", class(x))
return(invisible(x))
}
.AugmentedGrid = function(x){
# x$xTicks = seq(x$xaxp[1], x$xaxp[2], length.out=x$xaxp[3]+1)
# x$yTicks = seq(x$yaxp[1], x$yaxp[2], length.out=x$yaxp[3]+1)
class(x)=c("Augmented", class(x))
return(invisible(x))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Augment.R
|
AutoSpellCheck =
function(file) {
if (interactive()) {
if (require(BrailleR)) {
ChangeList = read.csv(paste0(getOption("BrailleR.Folder"),
"AutoSpellList.csv"))
for (i in 1:length(ChangeList$OldString)) {
FindReplace(file, ChangeList$OldString[i], ChangeList$NewString[i])
}
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/AutoSpellCheck.R
|
# @rdname BRLThis
# @title Convert a graph to a pdf ready for embossing
# @aliases BRLThis
# @description The first argument to this function must be a call to create a graph, such as a histogram. Instead of opening a new graphics device, the graph will be created in a pdf file, with all text being presented using a braille font. The function is somewhat experimental as the best braille font is not yet confirmed, and a number of examples need to be tested on a variety of embossers before full confidence in the function is given.
# @details The user's chosen braille font must be installed. This might include the default font shipped as part of the package.
# @return Nothing within the R session, but a pdf file will be created in the user's working directory.
# @author A. Jonathan R. Godfrey.
# @examples
#; data(airquality)
# with(airquality,
# BRLThis(hist(Ozone), "Ozone-hist.pdf"))
# @export BRLThis
# @param x the call to create a graph
# @param file A character string giving the filename where the image is to be saved.
BRLThis =
function(x, file) {
extrafont::loadfonts(quiet = TRUE)
# need to add these arguments to the call
# family="Braille Normal", cex=1, cex.axis=1, cex.main=1, cex.lab=1, cex.sub=1)
eval({
pdf(file, pointsize = 29)
x
dev.off()
extrafont::embed_fonts(file) # , outfile=file)
}, parent.frame())
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/BRLThis.R
|
BrailleRHome =
function() {
if (interactive()) {
browseURL("https://R-Resources.massey.ac.nz/BrailleR/")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
BrailleRInAction =
function() {
if (interactive()) {
browseURL("https://R-Resources.massey.ac.nz/BrailleRInAction/")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
LURN = function(BlindVersion = getOption("BrailleR.VI")) {
if (interactive()) {
if (BlindVersion) {
browseURL("https://R-Resources.massey.ac.nz/LURNBlind/")
} else {
browseURL("https://R-Resources.massey.ac.nz/LURN/")
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
google = Google =
function() {
if (interactive()) {
browseURL("https://www.google.com")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
R4DS = r4ds =
function() {
if (interactive()) {
browseURL("http://r4ds.had.co.nz/")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
WriteRHome =
function() {
if (interactive()) {
browseURL("https://R-Resources.massey.ac.nz/WriteR/")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/BrailleRUsefulLinks.R
|
# Currently only supports working the current directory.
BrowseSVG <- function(file = "test", key = TRUE, footer = TRUE, view = interactive(), ggplot_object = NULL) {
# Required file for correct execution
xmlFileName <- paste0(file, ".xml")
svgFileName <- paste0(file, ".svg")
if (!(file.exists(xmlFileName) && file.exists(svgFileName))) {
warning("You do not have both a svg and xml file in current wd. Please create these with SVGThis()/AddXML() or use MakeAccessibleSVG()")
return(invisible())
}
# Read and clean xml file
xmlString <- xmlFileName |>
readLines() |>
gsub("sre:", "", x = _) |>
gsub(" *<[a-zA-Z]+/>", "", x = _)
# Read svg file
svgString <- svgFileName |>
readLines()
# Add Describe and VI
# Some formatting is to be done to make it work with the templates
if (!is.null(ggplot_object)) {
# Get the Describe output
Description <- Describe(ggplot_object, whichLayer = "all")
if (isa(Description, "multiDescription")) {
Description <- unclass(Description)
Description <- lapply(seq_along(Description), function(i) {
Description[[i]]$name <- names(Description)[[i]]
Description[[i]]
})
} else {
Description <- unclass(Description)
}
# setNames(rep(NULL, length(length(ggplot_object$layers))))
# Get the VI output
VI <- VI(ggplot_object)
# Need to make a list with names to get mustache list looping working.
VI.text <- as.list(VI$text) |>
stats::setNames(rep("text", length(VI$text)))
} else {
VI.text <- Description <- NULL
}
# Whiskers prep and rendering
data <- list(
xml = xmlString,
svg = svgString,
footer = footer,
key = key,
title = file,
description = Description,
has_description = !is.null(Description),
vi = VI.text
)
htmlTemplate <- system.file("whisker/SVG/template.html", package = "BrailleR") |>
readLines()
renderedText <- whisker.render(htmlTemplate, data = data) |>
# Remove commas that are added to the data instead of new lines.
gsub("(> *)(,)( *<)", "\\1\n\\3", x = _) |> # In SVG and XML
gsub("(\\.)(,)", "\\1<br>", x = _) # In the VI and the Describe
# Write the rendered text to html file
fileName <- paste0(file, ".html")
writeLines(renderedText, con = paste0(file, ".html"))
close(file(fileName))
if (view) {
browseURL(fileName)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/BrowseSVG.R
|
CleanCSV =
function(file) {
if (interactive()) {
for (ThisFile in file) {
cat(paste0(ThisFile, ": "))
if (file.exists(ThisFile)) {
file.copy(ThisFile, paste0(ThisFile, ".bak"))
for (FixString in c(", ", " ,", "\t,", ",\t")) {
FindReplace(ThisFile, FixString, ",")
}
.Done()
} # end ThisFile exists condition
else {
.FileDoesNotExist()
}
} # end for loop for files
} # end interactive ondition
else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/CleanCSV.R
|
DataViewer =
function(x, Update = FALSE, New = NULL, Filename = NULL) {
# only for interactive sessions
if (interactive()) {
# check here that x is one of data.frame, matrix, or a vector.
if (!is.data.frame(x) & !is.matrix(x) & !is.vector(x)) {
.NotViewable()
}
if (is.null(Filename)) {
Filename = tempfile(pattern = "DV-", tmpdir = ".", fileext = ".csv")
}
write.csv(x, file = Filename)
browseURL(Filename)
readline( # waits for return value normally
"Press <enter> once the viewing and editing is completed. \nOtherwise the temporary file will not be removed.")
if (Update) {
if (is.null(New)) {
New = "New"
}
BringBack = read.csv(Filename, row.names = 1)
# check for class of x
if (is.matrix(x)) {
BringBack = as.matrix(BringBack)
}
if (is.vector(x)) {
BringBack = BringBack[, 1]
}
assign(New, BringBack, envir = parent.frame())
} # end Update
file.remove(Filename)
} # end interactive
else {
.InteractiveOnly()
} # end not interactive
invisible(NULL)
} # end function
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/DataViewer.R
|
# The heavy lifting of this function is done with these internal functions which
# Interact with the mustache templates.
# This method is somewhat inefficient as it will just get slower and slower as more templates are added.
.readTxtCSV <- function(location) {
temp <- read.csv(system.file(paste0("whisker/", location), package = "BrailleR"), header = T, as.is = T)
sublists <- length(temp) > 2
templates <- list()
for (plot in 1:length(temp[, 1])) {
templates[[temp[plot, 1]]] <- if (sublists) {
sublist <- as.list(gsub("\n", "", temp[plot, 2:length(temp)]))
names(sublist) <- colnames(temp)[2:length(temp)]
sublist
} else {
gsub("\n", "", temp[plot, 2])
}
}
return(templates)
}
.renderDescription <- function(name, baseR = T) {
if (baseR) {
template <- .readTxtCSV("Describe/baseR.txt")
} else {
template <- .readTxtCSV("Describe/ggplot.txt")
}
generics <- .readTxtCSV("Describe/generics.txt")
rendered <- list(
title = whisker::whisker.render(template = template[[name]]["title"], data = generics),
general = whisker::whisker.render(template = template[[name]]["general"], data = generics),
RHints = whisker::whisker.render(template = template[[name]]["RHints"], data = generics)
)
class(rendered) <- "description"
return(rendered)
}
Describe <-
function(x, VI = FALSE, ...) {
UseMethod("Describe")
}
print.description <-
function(x, ...) {
template <- paste(readLines(system.file("whisker/Describe/Describedefault.txt", package = "BrailleR")), collapse = "\n")
output <- whisker::whisker.render(template, x)
cat(output, "\n\n")
return(invisible(NULL))
}
print.multiDescription <-
function(x, ...) {
for (element in x) {
print(element)
}
}
Describe.default <-
function(x, VI = FALSE, ...) {
if (VI) VI(x)
.renderDescription("default")
}
Describe.histogram <-
function(x, VI = FALSE, ...) {
if (VI) VI(x)
.renderDescription("histogram")
}
Describe.scatterplot <-
function(x, VI = FALSE, ...) {
if (VI) VI(x)
.renderDescription("scatterplot")
}
Describe.tsplot <-
function(x, VI = FALSE, ...) {
if (VI) VI(x)
.renderDescription("tsplot")
}
Describe.ggplot <-
function(x, VI = FALSE, whichLayer = NULL, ...) {
if (VI) VI(x)
layers <- x$layers
# Interactive version to find out which layers to print
if (length(layers) == 1) {
whichLayer <- 1
} else if (is.null(whichLayer) && interactive()) {
cat("Please select which layers you will want to see descriptions for:\n")
for (i in seq_along(layers)) {
cat(i, ": ", class(layers[[i]]$geom)[1], "\n")
}
cat("Each layer should be seperated by a comma\n")
userInput <- readline(prompt = "Which layers do you want to see? ")
whichLayer <- gsub(" ", "", userInput) |>
strsplit(split = ",") |>
lapply(FUN = strtoi) |>
unlist()
# Default for non interactive is to print all layers
} else if (!interactive() || whichLayer == "all") {
whichLayer <- 1:length(layers)
}
# Filter out any number that arent
whichLayer <- whichLayer[whichLayer %in% 1:length(layers)]
# Get the descriptions of the layers
descriptions <- list()
for (layer in whichLayer) {
currentClass <- class(layers[[layer]]$geom)[1]
descriptions[[currentClass]] <- .renderDescription(currentClass, F)
}
# Make sure that all descriptions actually have a valid descriptions
descriptions <- descriptions[
lapply(
descriptions,
\(desc) {
nchar(desc$title) + nchar(desc$general) + nchar(desc$RHints) != 0
}
) |> unlist()
]
# Output multiple descriptions
if (length(descriptions) > 1) {
class(descriptions) <- "multiDescription"
return(descriptions)
# No valid indexes
} else if (length(whichLayer) == 0) {
warning("You havent entered any valid layer indexes")
return(NULL)
# No available description
} else if (length(descriptions) == 0) {
warning("None of your selected layers have a description yet.")
return(NULL)
# Only one description
} else {
return(descriptions[[1]])
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Describe.R
|
FindReplace =
function(file, find, replace) {
if (file.exists(file)) {
cat("\n", file = file, append = TRUE) # otherwise problems on
# readLines() below
OldText <- readLines(con = file)
NoLines = length(OldText)
if (NoLines > 2) {
if (all(OldText[c(NoLines - 1, NoLines)] == "\n")) {
NoLines = NoLines - 1
}
}
writeLines(gsub(find, replace, OldText, fixed=TRUE)[1:NoLines], con = file)
} else {
.FileDoesNotExist()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/FindReplace.R
|
GetExampleText =
function (topic, package = NULL, lib.loc = NULL, character.only = FALSE,
outFile = "")
{
if (!character.only) {
topic <- substitute(topic)
if (!is.character(topic))
topic <- deparse(topic)[1L]
}
pkgpaths <- find.package(package, lib.loc, verbose = FALSE)
NS <- getNamespace("utils")
index.search <- get("index.search", NS)
.getHelpFile <- get(".getHelpFile", NS)
file <- index.search(topic, pkgpaths, TRUE)
if (!length(file)) {
warning(gettextf("no help found for %s", sQuote(topic)),
domain = NA)
return(invisible())
}
packagePath <- dirname(dirname(file))
pkgname <- basename(packagePath)
lib <- dirname(packagePath)
if(outFile=="") outFile = tempfile("Rex")
tools::Rd2ex(.getHelpFile(file), outFile, commentDontrun = TRUE,
commentDonttest = TRUE)
if (!file.exists(outFile)) {
warning(gettextf("%s has a help file but no examples",
sQuote(topic)), domain = NA)
return(invisible())
}
ExLines = readLines(outFile)
headerEnds = which(ExLines=="### ** Examples")
return(ExLines[-c(1:headerEnds)])
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/GetExampleText.R
|
GetPython27 = function(...){
.DeprecatedFunction()
}
GetWxPython27 = function(...){
.DeprecatedFunction()
}
TestPython = function(){
HasPython=nzchar(Sys.which("python"))
if(HasPython){
.PythonVersion()
}
else{
.NoSeePython()
}
return(invisible(HasPython))
}
TestWX = function(){
if(TestPython()){
if (interactive()) {
if (.Platform$OS.type == "windows") {
shell(paste("python", system.file("Python/TestWX.py", package="BrailleR")))
} else {
.WindowsOnly()
}
}
if(.IsWxAvailable()){
.CanSeeWxPython()
.CanUseWriteR()
return(invisible(TRUE))}
else{ .CannotSeeWxPython()
return(invisible(FALSE))}
}
}
.IsWxAvailable =
function(){
TestWx = system('python -c "import wx"')
return(TestWx == 0)
}
GetPython3 =
function(x64=TRUE) {
.GetPython(3, x64=x64)
return(invisible(NULL))
}
.GetPython =
function(version, x64=x64) {
if (interactive()) {
if (.Platform$OS.type == "windows") {
if (requireNamespace("BrailleR")) {
if (requireNamespace("installr")) {
.DownloadAFile()
bit = .ifelse(x64, 64, 32)
installr::install.python(version_number = version, download_dir=getOption("BrailleR.Folder"), keep_install_file = TRUE, x64=x64)
.Added2MyBrailleR()
.DeleteAnytime()
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
.PullWxUsingPip = function(){
if(.IsWxAvailable()){
system("pip install --user -U wxPython")
}
else{
system("pip install --user wxPython")
}
return(invisible(TRUE))
}
GetWxPython3 =
function() {
Success = FALSE
if (interactive()) {
if (.Platform$OS.type == "windows") {
if(TestPython()){
.PullWxUsingPip()
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(Success))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/GetPython.R
|
GetPandoc =
function() {
if (interactive()) {
if (.Platform$OS.type == "windows") {
if (requireNamespace("BrailleR")) {
if (requireNamespace("installr")) {
.DownloadAFile()
installr::install.pandoc(
download_dir = getOption("BrailleR.Folder"),
keep_install_file = TRUE)
.Added2MyBrailleR()
.DeleteAnytime ()
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
GetRStudio =
function() {
if (interactive()) {
if (.Platform$OS.type == "windows") {
if (requireNamespace("BrailleR")) {
if (requireNamespace("installr")) {
.DownloadAFile()
installr::install.RStudio(
download_dir = getOption("BrailleR.Folder"),
keep_install_file = TRUE)
.Added2MyBrailleR()
.DeleteAnytime ()
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
Get7zip =
function() {
if (interactive()) {
if (.Platform$OS.type == "windows") {
if (requireNamespace("BrailleR")) {
if (requireNamespace("installr")) {
.DownloadAFile()
installr::install.7zip(download_dir = getOption("BrailleR.Folder"),
keep_install_file = TRUE)
.Added2MyBrailleR()
.DeleteAnytime ()
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
GetCygwin =
function(x64=TRUE) {
if (interactive()) {
if (.Platform$OS.type == "windows") {
if (requireNamespace("BrailleR")) {
if (requireNamespace("installr")) {
.DownloadAFile()
bit = .ifelse(x64, 64, 32)
installr::install.cygwin(bit=bit,
download_dir = getOption("BrailleR.Folder"),
keep_install_file = TRUE)
.Added2MyBrailleR()
.DeleteAnytime ()
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/GetSoftware.R
|
### problems so temporary override follows experimental work
GetWriteR =
function() {
if (interactive()) {
if (.Platform$OS.type == "windows") {
.DownloadAFile()
download.file(
"https://R-Resources.massey.ac.nz/writer/WriteRInstaller.exe",
"WriteRInstaller.exe")
file.rename("WriteRInstaller.exe",
paste0(getOption("BrailleR.Folder"), "WriteRInstaller.exe"))
.Added2MyBrailleR()
.DeleteAnytime()
} else {
.WindowsOnly
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/GetWriteR.R
|
GetGoing =
function() {
if (interactive()) {
.AnswerQuestionsMSG()
.AuthorNameMSG()
name = readLines(n = 1)
if (name != "") SetAuthor(name)
.PValueDigitsMSG()
digits = as.numeric(readLines(n = 1))
if (!is.na(digits)) SetSigLevel(digits)
.DefaultSignificanceMSG()
alpha = as.numeric(readLines(n = 1))
if (!is.na(alpha)) SetSigLevel(alpha)
message(
"\nThe following questions are yes/no questions. Use T or TRUE for yes, F or FALSE for no.")
message(
"\nDo you want to process R scripts and Rmd files outside R? (TRUE)")
batch = as.logical(readLines(n = 1))
if (is.na(batch)) batch = TRUE
if (batch) MakeBatch()
message(
"\nDo you want to incorporate output from R into LaTeX files? (TRUE)")
latex = as.logical(readLines(n = 1))
if (is.na(latex)) latex = TRUE
if (latex) {
LatexOn()
} else {
LatexOff()
}
message(
"\nDo you want to automatically open HTML files of R output? (TRUE)")
view = as.logical(readLines(n = 1))
if (is.na(view)) view = TRUE
if (view) {
ViewOn()
} else {
ViewOff()
}
message(
"\nBrailleR assumes you are blind. Is this how you will work? (TRUE)")
vi = as.logical(readLines(n = 1))
if (is.na(vi)) vi = TRUE
if (vi) {
GoBlind()
} else {
GoSighted()
}
#end interactive section.
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/GettingStarted.R
|
.ifelse = function(condition, yes, no){
if(condition){
return(yes)}
else {
return(no)}
}
FindCSSFile =
function(file) {
out = NULL
if (file.exists(paste0(getOption("BrailleR.Folder"), "/css/", file))) {
out = normalizePath(paste0(getOption("BrailleR.Folder"), "/css/", file))
}
if (file.exists(file)) {
out = file
}
return(out)
}
InQuotes = function(x) {
Out = paste0('"', x, '"')
}
### from examples for toupper() with slight alteration to allow for BrailleR options.
.simpleCap <- function(x) {
if (getOption("BrailleR.MakeUpper")) {
s <- strsplit(x, " ")[[1]]
out = paste0(toupper(substring(s, 1, 1)), substring(s, 2))
} else {
out = x
}
return(out)
}
.GetOldStyleScatterText = function(ResponseName, PredictorName, DataName){
TextOut = paste0(
'```{r ScatterPlot, fig.cap="Scatter Plot"}
# Remove the missing values
completeCases <- complete.cases(Data[ResponseName])*complete.cases(Data[PredictorName])
assign(DataName, Data[completeCases==1,])
plot(',
ResponseName, '~', PredictorName, ', data=', DataName, ', ylab=',
.simpleCap(ResponseName), ', xlab=', .simpleCap(PredictorName),
')
attach(', DataName, ')
WhereXY(', ResponseName, ',',
PredictorName, ')
detach(', DataName, ')
``` \n\n')
return(TextOut)
}
.GetModernStyleScatterText = function(ResponseName, PredictorName, DataName){
TextOut=UseTemplate(file="ScatterPlot.Rmd", find=c("library\\(ggplot2\\)", "DataName", "ResponseName", "PredictorName"),
replace=c("# N.B. using the ggplot2 package", DataName, ResponseName, PredictorName))
return(TextOut)
}
.GetOldStyleFittedText = function(ResponseName, PredictorName, DataName, ModelName){
TextOut = paste0('
```{r FittedLinePlot}
plot(', ResponseName, '~',
PredictorName, ', data=', DataName, ', ylab=',
.simpleCap(ResponseName), ', xlab=', .simpleCap(PredictorName),
')
abline(', ModelName,
')
```\n\n')
return(TextOut)
}
.GetModernStyleFittedText = function(ResponseName, PredictorName, DataName, ModelName){
TextOut=UseTemplate(file="FittedLinePlot.Rmd", find=c("library\\(ggplot2\\)", "DataName", "ResponseName", "PredictorName"),
replace=c("# N.B. using the ggplot2 package", DataName, ResponseName, PredictorName))
return(TextOut)
}
.GetOldStyleResidualText = function(ModelName){
TextOut=paste0('
```{r SimpleLinModResAnal, fig.cap="Residual analysis"}
par(mfrow=c(2,2))
plot(',
ModelName, ')
``` \n\n')
return(TextOut)
}
.GetModernStyleResidualText = function(ModelName){
TextOut=UseTemplate(file="ResidualAnalysis.Rmd", find=c("library\\(ggfortify\\)", "ModelName"),
replace=c("# N.B. using the ggfortify package", ModelName))
return(TextOut)
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Internal.R
|
ThankYou =
function() {
if (interactive()) {
create.post(
address = "[email protected]",
subject = "Thank you for BrailleR",
instructions = "Hello Jonathan,\n\n",
info = "Please let me know a little about yourself, where you are working or studying, and how you learned about BrailleR.\n")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
JoinBlindRUG =
function() {
if (interactive()) {
create.post(
address = "[email protected]", subject = "subscribe",
instructions = "end",
info = "Just send this message without altering it in any way; wait for an automated reply from the mail server. Just press reply to that message and send it back. You will be joined to BlindRUG very soon afterwards.\n")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/JoinBlindRUG.R
|
#' This r file is to be a store for all of the fucntions that are used when making
#' the xml and svg then putting it togather. It is only for functions that are
#' used by both the svg and xml pathways
#' Search graphic for ID of Geom
#' @rdname MakeAccessibleSVGInternal
#' This can be used by the AddXML function as well as SVG functions to know how to
#' modify and create the XML / svg. These IDs are the link that is between the XML and the SVG
#'
#' It is very important to remember that the graph must be current plotted for the
#' grid.grep style commands to work
#'
#' @param graphObject The graph object you want to be getting the id from
#' @param layer Which layer is this geom.
#'
#' @return A ID string that is the overall string needed in the svg and xml
#' If there are many elements then it is the most overarching selection
.GetGeomID <- function(graphObject, layer = 1) {
graphLayers <- graphObject$layers
thisLayerIDBase <- graphLayers[[layer]]$geom |>
.GetGeomIDBase()
if (is.null(thisLayerIDBase)) {
return()
}
geomGrobs <- grid.grep(gPath("panel", "panel-1", thisLayerIDBase), grep = TRUE, global = TRUE) |>
Filter(function(element) {
element$n == 4
}, x = _)
numberOfPreviousMatches <- if (layer == 1) {
# No previous matches if this is the first layer
0
} else {
graphLayers[1:(layer - 1)] |>
lapply(function(layer) {
thisLayerIDBase == .GetGeomIDBase(layer$geom)
}) |>
unlist() |>
sum()
}
geomGrob <- geomGrobs[[numberOfPreviousMatches + 1]]
# Always need to add the .1 to the end.
.CreateID(geomGrob$name, "1")
}
#' @rdname MakeAccessibleSVgInternal
#'
#' This is more or less a dictionary that will return what the base g tag
#' Id for the geom will start with.
#'
#' For Example a geom_line layer will have a g tag that starts with GRID.poyline
#' This function is used by the .GetGeomID to get the correct layers base g tag id.
#'
#' @param layerClass The geom object that has the layer class.
#'
.GetGeomIDBase <- function(layerClass) {
UseMethod(".GetGeomIDBase")
}
.GetGeomIDBase.default <- function(layerClass) {
# Nothing to happen on return
}
.GetGeomIDBase.GeomLine <- function(layerClass) {
return("GRID.polyline")
}
.GetGeomIDBase.GeomPoint <- function(layerClass) {
return("geom_point")
}
.GetGeomIDBase.GeomSmooth <- function(layerClass) {
return("geom_smooth")
}
.GetGeomIDBase.GeomBar <- function(layerClass) {
return("geom_rect")
}
#' @rdname MakeAccessibleSVGInternal
#'
#' Split a vector into a certain number of sections with either overlapping or not.
#'
#' @param overlapping Whether the data should overlap on the upper breaks.
#' This is needed by the svg tags.
#' @param dataToBeSplit A vector of numbers to be split
.SplitData <- function(dataToBeSplit, overlapping = FALSE) {
nSections <- 5
pointsSplit <- split(
dataToBeSplit,
cut(seq_along(dataToBeSplit),
nSections,
labels = FALSE,
include.lowest = TRUE
)
)
if (overlapping) {
pointsSplit |>
seq_along() |>
lapply(function(i) {
if (i != length(pointsSplit)) {
c(pointsSplit[[i]], pointsSplit[[i + 1]][1])
} else {
pointsSplit[[i]]
}
})
} else {
pointsSplit
}
}
#' Create label from parts
#'
#' This shold be used rather than doing a manual paste to help prevent any changes
#' in the future from being to damaging.
#'
#' @param ... These should be strings to be added togather
.CreateID <- function(...) {
paste(..., sep = ".")
}
#' Find out if a GeomLine line is disjoint
#'
#' Given the scale data for a line find out if it is disjoint or not.
#'
#' @param scaleData Scale data from the ggplot_build object. Can easily be retirieved
#' from the .VIStruct
#'
#' @return A Boolean value as to whether this line from the line data is disjoint.
.IsGeomLineDisjoint <- function(scaledata) {
any(is.na(scaledata$y))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeAccessibleSVGInternal.R
|
MakeAccessibleSVG <- function(x, file = paste0(deparse(substitute(x)), "-SVG"), view = interactive(), cleanup = TRUE, ...) {
UseMethod("MakeAccessibleSVG")
}
MakeAccessibleSVG.default <-
function(x, file = paste0(deparse(substitute(x)), "-SVG"), view = interactive(), cleanup = TRUE, ...) {
svgfile <- SVGThis(x, paste0(file, ".svg"))
xmlfile <- AddXML(x, paste0(file, ".xml"))
BrowseSVG(file = file, view = view, ...)
.SVGAndXMLMade()
if (cleanup) {
unlink(paste0(file, ".xml"))
unlink(paste0(file, ".svg"))
}
return(invisible(NULL))
}
MakeAccessibleSVG.histogram <- MakeAccessibleSVG.scatterplot <- MakeAccessibleSVG.default
MakeAccessibleSVG.tsplot <-
function(x, file = paste0(deparse(substitute(x)), "-SVG"), view = interactive(), cleanup = TRUE, ...) {
svgfile <- SVGThis(x, paste0(file, ".svg"))
if (x$Continuous) {
.RewriteSVG.tsplot(x, paste0(file, ".svg"))
}
xmlfile <- AddXML(x, paste0(file, ".xml"))
BrowseSVG(file = file, view = view, ...)
.SVGAndXMLMade()
if (cleanup) {
unlink(paste0(file, ".xml"))
unlink(paste0(file, ".svg"))
}
return(invisible(NULL))
}
MakeAccessibleSVG.ggplot <-
function(x, file = paste0(deparse(substitute(x)), "-SVG"), view = interactive(), cleanup = TRUE, VI_and_Describe = TRUE, ...) {
pdf(NULL) # create non-displaying graphics device for SVGThis and AddXML
svgfile <- SVGThis(x, paste0(file, ".svg"), createDevice = FALSE)
xmlfile <- AddXML(x, paste0(file, ".xml"))
dev.off() # destroy graphics device, now that we're done with it
if (VI_and_Describe) {
BrowseSVG(file = file, view = view, ggplot_object = x, ...)
} else {
BrowseSVG(file = file, view = view, ...)
}
.SVGAndXMLMade()
if (cleanup) {
unlink(paste0(file, ".xml"))
unlink(paste0(file, ".svg"))
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeAccessibleSVGMethod.R
|
# getting some useful batch files for admin tasks
# Windows users only
MakeAdminBatch =
function() {
if (interactive()) {
if (.Platform$OS.type == "windows") {
MyBrailleRFolder = .MyBrailleRName()
.MakeRBatch(MyBrailleRFolder)
.FileCreated("RBatch.bat")
.MakeRTerminal(MyBrailleRFolder)
.FileCreated("RTerminal.bat")
.MakeRenderAllMd(MyBrailleRFolder)
.FileCreated("RenderAllMD.bat")
.MakeRenderAllQmd(MyBrailleRFolder)
.FileCreated("RenderAllQmd.bat")
.MakeRenderAllRmd(MyBrailleRFolder)
.FileCreated("RenderAllRmd.bat")
.MakeUpdatePackages(MyBrailleRFolder) # needs commands
.MoveOntoPath()
.ConsultHelpPage()
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
.FindRInstallPathText = '@echo off
FOR /F "skip=2 tokens=2,*" %%A IN (\'reg.exe query "HKlm\\Software\\R-core\\r" /v "InstallPath"\') DO set "InstallPath=%%B"
\n'
.RFolderText = '"%InstallPath%\\bin\\x64\\'
.RTerminalText = paste0(.FindRInstallPathText, .RFolderText, 'rterm.exe" --save\n')
.RScriptText = paste0(.FindRInstallPathText, .RFolderText, 'rscript.exe"')
.RBatchText = paste0(.FindRInstallPathText, .RFolderText, 'r.exe" CMD BATCH --vanilla --quiet %1\n')
.MakeRScriptBatch = function(commands="getRversion()", where=".",file="test.bat"){
.FullRScriptText = paste0(.RScriptText, ' -e "', commands, '"\n')
cat(.FullRScriptText, file=paste0(where, "/", file))
return(invisible(NULL))
}
.MakeRBatch = function(where="."){
cat(.RBatchText, file=paste0(where, "/RBatch.bat"))
return(invisible(NULL))
}
.MakeRTerminal = function(where="."){
cat(.RTerminalText, file=paste0(where, "/RTerminal.bat"))
return(invisible(NULL))
}
.MakeUpdatePackages = function(where="."){
UpdatePkgsComs = paste(readLines(system.file("Scripts/UpdatePackages.R", package = "BrailleR")), collapse=";")
.MakeRScriptBatch(commands=UpdatePkgsComs, where=where, file="UpdateRPackages.bat")
return(invisible(NULL))
}
.MakeRenderAllMd = function(where="."){
cat(.RenderAllMdText, file=paste0(where, "/RenderAllMD.bat"))
return(invisible(NULL))
}
.MakeRenderAllQmd = function(where="."){
cat(.RenderAllQmdText, file=paste0(where, "/RenderAllQmd.bat"))
return(invisible(NULL))
}
.RenderAllQmdText = '@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%f IN (*.Qmd) DO (
SET NewName=%%f
quarto render "!NewName!"
)\n'
.RenderAllMdText = '@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%f IN (*.md) DO (
SET MDName=%%f
SET HTMLName=!MDName:.md=.html!
pandoc "!MDName!" -o "!HTMLName!"
)\n'
.MakeRenderAllRmd = function(where="."){
.MakeRScriptBatch(commands="BrailleR::ProcessAllRmd()", where=where, file="RenderAllRmd.bat")
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeAdminBatch.R
|
MakeAllFormats =
function(RmdFile, BibFile = "") {
Settings = readLines(system.file("Foo.pandoc", package = "BrailleR"))
FullFile = unlist(strsplit(RmdFile, split = ".", fixed = TRUE))[1]
# switch foo.bib to BibFile
Settings = gsub("foo.bib", BibFile, Settings)
# switch all Foo to RmdFile stem
Settings = gsub("foo", FullFile, Settings)
writeLines(Settings, con = paste0(FullFile, ".pandoc"))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeAllFormats.R
|
# getting some useful batch files for processing R scripts and Rmarkdown files.
# Windows users only
MakeBatch =
function(file = NULL, static=FALSE) {
if (interactive()) {
if (.Platform$OS.type == "windows") {
RHome = .ifelse(static,
paste0('"', gsub("/", "\\\\", R.home())), paste0(.FindRInstallPathText, '"%InstallPath%'))
if (is.null(file)) {
# write a batch file for processing R scripts
cat(paste0(RHome, '\\bin\\R.exe" CMD BATCH --vanilla --quiet %1\n'),
file = "RBatch.bat")
.NewFile(file = "RBatch.bat")
# write a batch file for processing a specific R markdown file
cat(paste0(RHome,
'\\bin\\RScript.exe" --vanilla -e \"rmarkdown::render(\'%1\')\"\n'),
file = "RmdBatch.bat")
.NewFile(file = "RmdBatch.bat")
# write a batch file for processing all R markdown files
cat(paste0(RHome, '\\bin\\Rscript.exe" --vanilla -e "BrailleR::ProcessAllRmd()"\n'),
file = "ProcessAllRmd.bat")
.NewFile(file = "ProcessAllRmd.bat")
# write a batch file for processing all markdown files
cat(paste0(RHome, '\\bin\\Rscript.exec" --vanilla -e "BrailleR::ProcessAllMd()"\n'),
file = "ProcessAllMd.bat")
.NewFile(file = "ProcessAllMd.bat")
.MoveOntoPath()
# write a file to show the system path settings
cat(Sys.getenv("PATH"), file = "path.txt")
.SavedInPath()
# write a test Rmd file
cat("# a test file
## created by the BrailleR package
My R version is `r getRversion()` and is being used to create this test file
It will then be used to process the test file later once the necessary actions are taken in Windows Explorer. \n",
file = "test1.Rmd")
.NewFile(file="test1.Rmd")
MakeBatch("test1.Rmd")
# write a test R script
cat("# a test file
## created by the BrailleR package
MySample=sample(100, 10)
MySample
mean(MySample) \n",
file = "test2.R")
cat("test2.R created successfully.\n")
MakeBatch("test2.R")
.ConsultHelpPage()
} else {
if (!file.exists(file))
.FileDoesNotExist (file)
FullFile = unlist(strsplit(file, split = ".", fixed = TRUE))
if (endsWith(file, ".R") | endsWith(file, ".r")) {
# write a batch file for processing the R script
cat(paste0(RHome, '\\bin\\R.exe" CMD BATCH --vanilla --quiet ',
FullFile[1], '.R\n'),
file = paste0(FullFile[1], ".bat"))
.NewFile(file = paste0(FullFile[1], ".bat"))
}
if (endsWith(file, ".Qmd") | endsWith(file, ".qmd")) {
# write batch files for rendering and previewing the quarto file
cat(paste0('quarto preview "', file, '"'),
file = paste0(FullFile[1], "Preview.bat"))
.NewFile(file = paste0(FullFile[1], "Preview.bat"))
cat(paste0('quarto render "', file, '"'),
file = paste0(FullFile[1], ".bat"))
.NewFile(file = paste0(FullFile[1], "Render.bat"))
}
if (endsWith(file, ".Rmd") | endsWith(file, ".rmd")) {
# write a batch file for processing the R markdown file
cat(paste0(RHome, '\\bin\\RScript.exe" -e "rmarkdown::render(\'',
FullFile[1], '.Rmd\')"\n'),
file = paste0(FullFile[1], ".bat"))
.NewFile(file = paste0(FullFile[1], ".bat"))
}
}
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeBatch.R
|
History2Qmd =
function(file = "History.Qmd") {
if (interactive()) {
TempFile = tempfile(fileext = "R")
savehistory(TempFile)
Lines = readLines(TempFile)
LineNo = 1:length(Lines)
cat(paste0('---\ntitle: "History from R session on ', format(Sys.Date(), "%A %d %B %Y"),
'"\nauthor: "by ', getOption("BrailleR.Author"), '"\ndate: ', format(Sys.Date(), "%A %d %B %Y"), '\n---\n\n```{r setup, nclude=FALSE}\nlibrary(knitr)
opts_chunk$set(comment="", fig.cap="to fix")
```\n\n'), file = file)
cat(paste0("```{r}
#| line", LineNo, "\n", Lines, "\n``` \n\n"),
file = file, append = TRUE)
.NewFile(file)
return(file)
} else {
.InteractiveOnly()
return(invisible(NULL))
}
}
R2Qmd =
function(ScriptFile) {
if (file.exists(ScriptFile)) {
QmdFile = gsub(".Qmd", ".Qmd", paste0(ScriptFile, "md"))
Lines = readLines(ScriptFile)
NoLines = length(Lines)
GoodLines = Lines > ""
GoodLines2 = c(FALSE, GoodLines[1:(NoLines - 1)])
ShowLines = GoodLines | GoodLines2
#if(Lines[1]=="") ShowLines[1]=FALSE
Lines[Lines == ""] = "``` \n\n```{r} "
Lines = Lines[ShowLines]
cat(paste0('---\ntitle: ""\nauthor: "', getOption("BrailleR.Author"), '"\ndate: ', format(Sys.Date(), "%A %d %B %Y"), '\n---\n\n```{r}'),
file = QmdFile)
cat(paste0("\n", Lines, " "), file = QmdFile, append = TRUE)
cat("\n# end of input \n``` \n\n", file = QmdFile, append = TRUE)
.NewFile(file = QmdFile)
return(QmdFile)
} else {
.FileDoesNotExist(file)
return(invisible(NULL))
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeQmdFiles.R
|
MakeReadable =
function(pkg) {
if (.Platform$OS.type == "windows") {
if (requireNamespace(pkg, ) ) {
# move files here for subsequent conversion
VignetteFolder = paste0(system.file(package = pkg), "/doc")
RnwFiles = c(list.files(path = VignetteFolder, pattern = "Rnw", full.names=TRUE),
list.files(path = VignetteFolder, pattern = "rnw", full.names=TRUE))
MyVignettesFolder =
paste0(getOption("BrailleR.Folder"), "/Vignettes/")
if (!dir.exists(MyVignettesFolder)) dir.create(MyVignettesFolder)
FinalMoveTo = paste0(MyVignettesFolder, pkg, "/")
if (!dir.exists(FinalMoveTo)) dir.create(FinalMoveTo)
FinalMoveTo = MyVignettesFolder
OriginalDir = getwd()
MoveTo=pkg
dir.create(MoveTo)
file.copy(RnwFiles,
MoveTo, overwrite = TRUE)
setwd(MoveTo)
RnwFiles = c(list.files(pattern = "Rnw"),
list.files(pattern = "rnw"))
# Copying and converting line breaks
for (i in RnwFiles) {
try(Sweave(i))
}
TeXFiles = list.files(pattern=".tex")
#if(nzchar(Sys.which("htmlblahlatex"))){
# try to use tex4ht
# shoudl fail because if() is flaweed on purpose while developing.
#} else {
# use pandoc
HTMLFile=gsub(".tex", ".html", i)
shell(paste("pandoc", i, "-o", HTMLFile))
#}
setwd(OriginalDir)
file.copy(MoveTo, FinalMoveTo, overwrite=TRUE)
unlink(MoveTo)
} else {
.PkgNotFound()
}
} else {
.WindowsOnly()
}
return(invisible(NULL))
}
.RemoveWhiteSpace = function(file){
.Done()
writeLines(gsub(" *", " ", readLines(file)), file)
return(invisible(NULL))
}
.RemoveTabs = function(file){
# Converting tabs to spaces
writeLines(gsub("\t", " ", readLines(file)), file)
# shell(paste0(system.file(
# "Python/RemoveTabs.py", package = "BrailleR"),
# ' "', file, '"'))
return(invisible(NULL))
}
.MakeBackUp = function(file){
OldFile=paste0(file, ".bak")
file.copy(file, OldFile)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeReadable.R
|
History2Rmd =
function(file = "History.Rmd") {
if (interactive()) {
TempFile = tempfile(fileext = "R")
savehistory(TempFile)
Lines = readLines(TempFile)
LineNo = 1:length(Lines)
cat(paste0('---\ntitle: "History from R session on ', format(Sys.Date(), "%A %d %B %Y"),
'"\nauthor: "by ', getOption("BrailleR.Author"), '"\ndate: Updated on `r format(Sys.Date(), \'%A %d %B %Y\')`\n---\n\n```{r setup, include=FALSE}\nlibrary(knitr)
opts_chunk$set(comment="", fig.cap="to fix")
```\n\n'), file = file)
cat(paste0("```{r line", LineNo, "} \n", Lines, "\n``` \n\n"),
file = file, append = TRUE)
.NewFile(file = file)
return(file)
} else {
.InteractiveOnly()
return(invisible(NULL))
}
}
R2Rmd =
function(ScriptFile) {
if (file.exists(ScriptFile)) {
RmdFile = gsub(".rmd", ".Rmd", paste0(ScriptFile, "md"))
Lines = readLines(ScriptFile)
NoLines = length(Lines)
GoodLines = Lines > ""
GoodLines2 = c(FALSE, GoodLines[1:(NoLines - 1)])
ShowLines = GoodLines | GoodLines2
#if(Lines[1]=="") ShowLines[1]=FALSE
Lines[Lines == ""] = "``` \n\n```{r } "
Lines = Lines[ShowLines]
cat(paste0('---\ntitle: ""\nauthor: "', getOption("BrailleR.Author"), '"\ndate: `r format(Sys.Date(), \'%A %d %B %Y\')`\n---\n\n```{r }'),
file = RmdFile)
cat(paste0("\n", Lines, " "), file = RmdFile, append = TRUE)
cat("\n# end of input \n``` \n\n", file = RmdFile, append = TRUE)
.NewFile(file = RmdFile)
return(RmdFile)
} else {
.FileDoesNotExist()
return(invisible(NULL))
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeRmdFiles.R
|
MakeRprofile =
function(Overwrite = FALSE) {
if (!file.exists(".Rprofile")) Overwrite = TRUE
if (Overwrite) {
cat('.First=function(){\n .First.sys()\n library(BrailleR)\n}\n',
file = ".Rprofile")
.FileCreated(".Rprofile", "in the current working directory.")
.AutoLoadBrailleR()
} else {
.FileExists(file=".Rprofile")
.OverWriteNeeded()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeRprofile.R
|
# file contains MakeAllInOneSlide(), MakeSlidy(), and MakeSlideShow()
## all deprecated
MakeAllInOneSlide =
function(Folder, Style = getOption("BrailleR.SlideStyle"), file = NULL) {
if (dir.exists(Folder)) { # only continue if the folder specified exists
# find the CSS file wanted.
StyleUsed = FindCSSFile(Style)
if (file.exists(paste0("./", Folder, "/", Style))) {
StyleUsed = paste0("./", Folder, "/", Style)
}
if (!is.null(StyleUsed)) { # only continue if a css file was found
# get lists of master slides and output slide
MasterSlideSet =
list.files(path = Folder, pattern = "Rmd", full.names = TRUE)
OutRMD = paste0(file, ".Rmd")
OutMD = paste0(file, ".md")
cat("<!---
one HTML document to concatinate an entire slide show presented as a series of HTML slides.
--->\n\n",
file = OutRMD)
file.append(OutRMD, MasterSlideSet)
cat("\n\n", file = OutRMD, append = TRUE)
knit2html(OutRMD, stylesheet = StyleUsed)
# remove temporary files
file.remove(OutRMD)
file.remove(OutMD)
} # end css file condition
else {
## war ning("Cannot find the specified css file.")
}
} # end folder existence condition
else {
.FolderNotFound()
.NoActionTaken()
}
return(invisible(NULL))
}
MakeSlidy =
function(Folder, file = NULL) {
if (dir.exists(Folder)) { # only continue if the folder specified exists
# get lists of master slides and output slide
MasterSlideSet =
list.files(path = Folder, pattern = "Rmd", full.names = TRUE)
OutRMD = paste0(file, ".Rmd")
OutMD = paste0(file, ".md")
cat("<!---
Slidy presentation
--->\n\n",
file = OutRMD)
file.append(OutRMD, MasterSlideSet)
cat("\n\n", file = OutRMD, append = TRUE)
rmarkdown::render(OutRMD, output_format=slidy_presentation())
} # end folder existence condition
else {
.FolderNotFound()
.NoActionTaken()
}
return(invisible(NULL))
}
MakeSlideShow =
function(Folder, Style = getOption("BrailleR.SlideStyle"),
ContentsSlide = TRUE) {
if (dir.exists(Folder)) { # only continue if the folder specified exists
# find the CSS file wanted.
StyleUsed = FindCSSFile(Style)
if (file.exists(paste0("./", Folder, "/", Style))) {
StyleUsed = paste0("./", Folder, "/", Style)
}
if (!is.null(StyleUsed)) { # only continue if a css file was found
# get lists of master slides and output slides
MasterSlideSet =
list.files(path = Folder, pattern = "Rmd", full.names = TRUE)
SlideSet = gsub(paste0(Folder, "/"), "", MasterSlideSet)
OutSet = gsub(".Rmd", ".html", SlideSet)
# make temporary copy of slides
file.copy(from = MasterSlideSet, to = SlideSet, overwrite = TRUE)
if (ContentsSlide) {
cat("## Contents\n\n", file = "00_Contents.Rmd")
for (i in SlideSet) { # add contents link
cat("\n\n[contents](00_Contents.html)", file = i, append = TRUE)
temp = readLines(i, n = 5)
temp = temp[temp != ""]
cat(paste0("#", temp[1], "\n\n"), file = "00_Contents.Rmd",
append = TRUE)
cat(paste0("[", gsub(".Rmd", "", i), "](",
gsub(".Rmd", ".html", i), ")\n\n"),
file = "00_Contents.Rmd", append = TRUE)
}
knit2html("00_Contents.Rmd", stylesheet = StyleUsed)
file.remove("00_Contents.md")
file.remove("00_Contents.Rmd")
}
for (i in 2:length(SlideSet)) { # add back link
cat(paste0("\n\n[back](", OutSet[i - 1], ")\n"), file = SlideSet[i],
append = TRUE)
}
for (i in 1:(length(SlideSet) - 1)) { # add next link
cat(paste0(" [next](", OutSet[i + 1], ")\n"), file = SlideSet[i],
append = TRUE)
}
for (i in SlideSet) {
knit2html(i, stylesheet = StyleUsed)
# remove temporary files
file.remove(sub(".Rmd", ".md", i))
file.remove(i)
}
} # end css file condition
else {
## war ning("Cannot find the specified css file.")
}
} # end folder existence condition
else {
.FolderNotFound()
.NoActionTaken()
}
return(invisible(NULL))
}
MakeAllInOneSlide = MakeSlidy = MakeSlideShow =
function(...){
.DeprecatedFunction()
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MakeSlideShow.R
|
boxplot =
function(x, ...) {
MC <- match.call(expand.dots = TRUE)
MC[[1L]] <- quote(graphics::boxplot)
names(MC)[2] = ""
Out <- eval(MC, parent.frame())
Out$main = as.character(MC$main)
if (length(MC$horizontal) > 0) {
Out$horizontal = as.logical(MC$horizontal)
} else {
Out$horizontal = FALSE
}
# then overwrite if user has specified (even if in error)
if (length(MC$xlab) > 0) Out$xlab = as.character(MC$xlab)
if (length(MC$ylab) > 0) Out$ylab = as.character(MC$ylab)
Out$call = MC
class(Out) = "boxplot"
Out=Augment(Out)
return(invisible(Out))
}
hist = function(x, ...) {
MC <- match.call(expand.dots = TRUE)
MC[[1L]] <- quote(graphics::hist)
Out <- eval(MC, parent.frame())
if (length(MC$main) > 0) Out$main = as.character(MC$main)
if (length(MC$sub) > 0) Out$sub = as.character(MC$sub)
if (length(MC$xlab) > 0) Out$xlab = as.character(MC$xlab)
if (length(MC$ylab) > 0) Out$ylab = as.character(MC$ylab)
Out=Augment(Out)
return(invisible(Out))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/MaskedFunctions.R
|
.BlankMSG = function() {
message("")
return(invisible(NULL))
}
.Added2MyBrailleR = function(){
message("The installer file has been added to your MyBrailleR folder.")
return(invisible(NULL))
}
.AnswerQuestionsMSG = function(){
message("You will be asked to enter answers for a series of questions.Hit <enter> to use the default shown in parentheses.")
return(invisible(NULL))
}
.AuthorNameMSG = function() {
message("Enter the name you want to use for authoring content. (",
getOption("BrailleR.Author"), ")")
return(invisible(NULL))
}
.AutoLoadBrailleR = function() {
message("The BrailleR package will be automatically loaded on startup in this working directory.")
return(invisible(NULL))
}
.CanSeeWxPython = function(){
message("Python can see the necessary wx module.")
return(invisible(NULL))
}
.CanUseWriteR = function(){
message("You are ready to use WriteR.")
return(invisible(NULL))
}
.ConsultHelpPage = function() {
message("Consult the help page for guidance on using these files in Windows Explorer.")
return(invisible(NULL))
}
.DefaultSignificanceMSG = function() {
message("What is the level of significance you plan to use as your default? (",
getOption("BrailleR.SigLevel"), ")")
return(invisible(NULL))
}
.DeleteAnytime = function(){
message("You can delete it at any time, but that will not uninstall the application.")
return(invisible(NULL))
}
.Done = function(){
message("Done.")
return(invisible(NULL))
}
.FileCreated = function(file=NULL, where="in your MyBrailleR directory.") {
NewFile = .ifelse(is.null(file), "A new file", file)
message(NewFile, " has been created ", where)
return(invisible(NULL))
}
.FileUpdated = function(file=NULL, where="in your MyBrailleR directory.") {
NewFile = .ifelse(is.null(file), "The specified", file)
message(NewFile, " has been updated ", where)
return(invisible(NULL))
}
.GoAdvancedMSG = function() {
message("By going advanced, you have reduced the verbosity of text descriptions of graphs.")
return(invisible(NULL))
}
.GoBlindMSG = function() {
message("By going blind, you have turned on the automatic generation of text descriptions of graphs.")
return(invisible(NULL))
}
.GoNoviceMSG = function() {
message("By going novice, you have returned to receiving all of the automatically generated text descriptions of graphs.")
return(invisible(NULL))
}
.GoSightedMSG = function() {
message("By going sighted, you have turned off the automatic generation of text descriptions of graphs.")
return(invisible(NULL))
}
.InstallPython = function() {
message("You could use GetPython3() and GetWxPython3() to help install them.")
return(invisible(NULL))
}
.LatexOffMSG = function() {
message("You have turned the automatic generation of LaTeX tables off.")
return(invisible(NULL))
}
.LatexOnMSG = function() {
message("You have turned the automatic generation of LaTeX tables on.")
return(invisible(NULL))
}
.MoveOntoPath= function() {
message("These files need to be moved to a folder that is on your system path.")
return(invisible(NULL))
}
.NewFile = function(file=NULL) {
NewFile = .ifelse(is.null(file), "", file)
message(NewFile, " has been created in your working directory.")
return(invisible(NULL))
}
.NoActionTaken = function() {
message("No action taken.")
return(invisible(NULL))
}
.NoSeePython = function(){
message("Python cannot be seen on your system.If it is installed, then you may need to ensure your system settings are correct.")
return(invisible(NULL))
}
.NothingDoneGraph = function() {
message("Nothing done to augment this graph object.")
return(invisible(NULL))
}
.NoVIMethod = function() {
message("There is no specific method written for this type of object.")
message("You might try to use the print() function on the object or the str() command to investigate its contents.")
return(invisible(NULL))
}
.OptionLocal = function() {
message("The new setting will remain in effect next time you load the BrailleR package in this directory.")
return(invisible(NULL))
}
.OptionPermanent = function() {
message("This has overwritten the setting for all folders.")
return(invisible(NULL))
}
.OptionUpdated = function(option, to=NULL) {
message("The BrailleR.", option, " option has been updated", .ifelse(is.null(to), "", paste0("to ", to )), ".")
return(invisible(NULL))
}
.OriginalDefaults = function() {
message("You have reset all preferences to the original package defaults.")
return(invisible(NULL))
}
.PValueDigitsMSG = function() {
message("How many decimal places do you wish p values to be rounded to? (", getOption("BrailleR.PValDigits"), ")")
return(invisible(NULL))
}
.PythonVersion = function() {
VersionString = system2("python", "--version", stdout=TRUE, stderr=TRUE)
message("Your system is using ", VersionString, "")
return(invisible(NULL))
}
.QuartoVersion = function() {
VersionString = system2("quarto", "--version", stdout=TRUE, stderr=TRUE)
message("Your system is using ", VersionString, "")
return(invisible(NULL))
}
.SavedInPath = function() {
message("These details are saved in path.txt for reference.")
return(invisible(NULL))
}
.SVGAndXMLMade = function() {
message("SVG and XML files created successfully.")
return(invisible(NULL))
}
.UpdatedSettingMSG = function(What, To) {
message( "The", What, "has been changed to ", To, "and saved in your settings file.")
return(invisible(NULL))
}
.ViewOffMSG = function() {
message("You have turned the automatic opening of html pages off.")
return(invisible(NULL))
}
.ViewOnMSG = function() {
message("You have turned the automatic opening of html pages on.")
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Messages.R
|
NewFunction =
function(FunctionName, args = NULL, NArgs = 0) {
if (is.numeric(args[1])) {
NArgs = args[1]
args = NULL
}
if (is.null(args)) {
args = rep("", NArgs)
} else {
NArgs = length(args)
}
Filename = paste0(FunctionName, ".R")
cat(paste0(
"#' @rdname ", FunctionName, "\n#' @title
\n#' @aliases ",
FunctionName,
"
\n#' @description
\n#' @details
\n#' @return
\n#' @seealso
\n#' @author ",
getOption("BrailleR.Author"),
"
\n#' @references
\n#' @examples
\n#' @export ", FunctionName,
"
"), file = Filename, append = FALSE)
if (NArgs > 0) {
cat(paste("#' @param", args, "\n"), file = Filename, append = TRUE)
}
cat(paste0("\n", FunctionName, "= function(",
paste(args, collapse = ", "), "){
}
"), file = Filename,
append = TRUE)
.FileCreated(Filename, "in the current working directory.")
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/NewFunction.R
|
VI.hist =
function(...) {
args = list(...)
VI(hist(...))
if (!is.null(args$xlab)) {
cat(paste("N.B. The default text for the x axis has been replaced by: ",
args$xlab, "\n", sep = ""))
cat("\n")
}
if (!is.null(args$ylab)) {
cat(paste("N.B. The default text for the y axis has been replaced by: ",
args$ylab, "\n", sep = ""))
cat("\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/NonMethodFunctions.R
|
OneFactor =
function(Response, Factor, Data = NULL, HSD = TRUE, AlphaE = 0.05,
Filename = NULL, Folder = NULL, VI = getOption("BrailleR.VI"),
Latex = getOption("BrailleR.Latex"),
View = getOption("BrailleR.View"), Modern=TRUE) {
if (length(Response) == 1) {
if (is.character(Response)) {
ResponseName = Response
}
} else {
ResponseName = as.character(match.call()$Response)
}
if (length(Factor) == 1) {
if (is.character(Factor)) {
FactorName = Factor
}
} else {
FactorName = as.character(match.call()$Factor)
}
if (is.null(Data)) {
Data = data.frame(get(ResponseName), get(FactorName))
names(Data) = c(ResponseName, FactorName)
DataName = paste0(ResponseName, ".", FactorName)
assign(
paste0(ResponseName, ".", FactorName), Data, envir = parent.frame())
} else {
if (length(Data) == 1) {
if (is.character(Data)) {
DataName = Data
}
Data = get(DataName)
} else {
DataName = as.character(match.call()$Data)
}
if (!is.data.frame(Data)) .NotADataFrame()
}
with(
Data,
{
if (!is.numeric(get(ResponseName)))
.ResponseNotNumeric()
if (!is.factor(get(FactorName)))
.GroupNotFactor()
}) # end data checking
# create folder and filenames
if (is.null(Folder)) Folder = DataName
if (Folder != "" & !file.exists(Folder)) dir.create(Folder)
if (is.null(Filename))
Filename = paste0(.simpleCap(ResponseName), ".", .simpleCap(FactorName),
"-OneFactor.Rmd")
# start writing to the R markdown file
cat('# Analysis of the', .simpleCap(DataName), 'data, using',
.simpleCap(ResponseName), 'as the response variable and',
.simpleCap(FactorName),
'as the single grouping factor.
#### Prepared by',
getOption("BrailleR.Author"), ' \n\n', file = Filename)
cat(paste0(
'```{r setup, purl=FALSE, include=FALSE}
',
.ifelse(VI, "library(BrailleR)", ""),
.ifelse(Modern, "\nlibrary(tidyverse)\nlibrary(ggfortify)", ""),
'
knitr::opts_chunk$set(dev=c("png", "pdf", "postscript", "svg"))
knitr::opts_chunk$set(echo=FALSE, comment="", fig.path="',
Folder, '/', .simpleCap(ResponseName), '.',
.simpleCap(FactorName),
'-", fig.width=7)
```
<!--- IMPORTANT NOTE: This Rmd file does not yet import the data it uses.
You will need to add a data import command of some description into the next R chunk to use the file as a stand alone file. --->
```{r importData}
```
## Group summaries
```{r GroupSummary}
attach(',
DataName, ')
Data.Mean <- tapply(', ResponseName, ', ',
FactorName, ', mean, na.rm=TRUE)
Data.StDev <- tapply(',
ResponseName, ', ', FactorName,
', sd, na.rm=TRUE)
nNonMissing <- function(x){
length(na.omit(x)) # length() includes NAs
}
Data.n <- tapply(',
ResponseName, ', ', FactorName,
', nNonMissing)
Data.StdErr = Data.StDev/sqrt(Data.n)
detach(',
DataName,
')
DataSummary = data.frame(names(Data.Mean), Data.Mean, Data.StDev, Data.n, Data.StdErr)
colnames(DataSummary) = c("Level", "Mean", "Standard deviation", "n", "Standard error")
```
```{r PrintSummary, results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
cat("The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev)/min(Data.StDev),2)` \n\n",
file = Filename, append = TRUE)
nNonMissing <- function(x) {
length(na.omit(x)) # length() includes NAs
}
Data.n <- with(get(DataName),
tapply(get(ResponseName), get(FactorName), nNonMissing))
if (min(Data.n) > 4) {
cat(paste0('## Comparative boxplots
```{r boxplots, fig.cap="Comparative boxplots"}
',
.ifelse(VI, "VI(", ""), 'boxplot(', ResponseName, '~',
FactorName, ', data=', DataName, ', ylab=',
InQuotes(.simpleCap(ResponseName)), ', xlab=',
InQuotes(.simpleCap(FactorName)), .ifelse(VI, ")", ""),
')
``` \n\n'), file = Filename, append = TRUE)
}
else {
cat('## Comparative boxplots \n
No boxplots are included because at least one group size is too small. \n\n',
file = Filename, append = TRUE)
}
cat(paste0(
'## Comparative dotplots
```{r dotplots, fig.cap="Comparative dotplots"}
with(',
DataName, ',
', .ifelse(VI, 'VI(dotplot(', 'stripchart('),
ResponseName, '~', FactorName, ', xlab=',
InQuotes(.simpleCap(ResponseName)), ', ylab=',
InQuotes(.simpleCap(FactorName)), .ifelse(VI, ')', ''),
'))
``` \n\n'), file = Filename, append = TRUE)
cat(paste0('## One-way Analysis of Variance
```{r OneWayANOVA1}
',
.ifelse(VI, "VI(", ""), '
MyANOVA <- aov(', ResponseName, '~',
FactorName, ', data=', DataName, ')', .ifelse(VI, ")", "")),
'
summary(MyANOVA)
``` \n\n', file = Filename, append = TRUE)
cat('\n\n## Residual Analysis\n\n', file = Filename, append = TRUE)
ResidualText = .ifelse(Modern, .GetModernStyleResidualText(ModelName="MyANOVA"), .GetOldStyleResidualText(ModelName="MyANOVA"))
cat(ResidualText, file = Filename, append = TRUE)
cat(paste0(
'\n\n## Tests for homogeneity of Variance
```{r BartlettTest}
bartlett.test(',
ResponseName, '~', FactorName, ', data=', DataName,
')
```
```{r FlignerTest}
fligner.test(', ResponseName, '~',
FactorName, ', data=', DataName, ')
``` \n\n'), file = Filename,
append = TRUE)
if (HSD) {
cat(paste0(
'## Tukey Honestly Significant Difference test
```{r TukeyHSD, fig.cap="Plot of Tukey HSD"}
MyHSD <- TukeyHSD(MyANOVA, ordered=TRUE, conf.level=',
1 - AlphaE, ')
', .ifelse(VI, "VI(MyHSD) \n", ""),
'
MyHSD
plot(MyHSD)
``` \n\n'), file = Filename,
append = TRUE)
}
if (Latex) {
cat(paste0(
'## Tables for LaTeX documents
N.B. Set `Latex=FALSE` to stop creation of these tables in future
```{r DataSummaryTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', .simpleCap(ResponseName), '.',
.simpleCap(FactorName),
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
.simpleCap(ResponseName), ' by level of ',
.simpleCap(FactorName),
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="llrrrr"), include.rownames = FALSE, file = ThisTexFile)
```
```{r ANOVA-TEX, purl=FALSE}
ThisTexFile = "',
Folder, '/', .simpleCap(ResponseName), '-',
.simpleCap(FactorName),
'-ANOVA.tex"
TabCapt = "One-way ANOVA for ',
.simpleCap(ResponseName), ' with the group factor ',
.simpleCap(FactorName),
'."
print(xtable(MyANOVA, caption=TabCapt, label="',
.simpleCap(ResponseName), '-', .simpleCap(FactorName),
'-ANOVA", digits=4), file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# finish writing markdown and process the written file into html and an R script
knit2html(Filename, quiet = TRUE,
meta = list(css = FindCSSFile(getOption("BrailleR.Style"))))
file.remove(sub(".Rmd", ".md", Filename))
purl(Filename, quiet = TRUE, documentation = 0)
if (View) browseURL(sub(".Rmd", ".html", Filename))
} # end of OneFactor function
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/OneFactor.R
|
## add this back in when the VI.anova() is done
# ', .ifelse(VI, "VI(", ""), 'anova(', ModelName, .ifelse(VI,")", ""), ')
OnePredictor =
function(Response, Predictor, Data = NULL, Filename = NULL, Folder = NULL,
VI = getOption("BrailleR.VI"), Latex = getOption("BrailleR.Latex"),
View = getOption("BrailleR.View"), Modern=TRUE) {
# Need to redefine the environment for VI.lm function
VI.env <- environment(VI.lm)
environment(VI.lm) <- environment()
if (length(Response) == 1) {
if (is.character(Response)) {
ResponseName = Response
}
} else {
ResponseName = as.character(match.call()$Response)
}
if (length(Predictor) == 1) {
if (is.character(Predictor)) {
PredictorName = Predictor
}
} else {
PredictorName = as.character(match.call()$Predictor)
}
if (is.null(Data)) {
Data = data.frame(get(ResponseName), get(PredictorName))
names(Data) = c(ResponseName, PredictorName)
DataName = paste0(ResponseName, ".", PredictorName)
assign(paste0(ResponseName, ".", PredictorName), Data,
envir = parent.frame())
} else {
if (length(Data) == 1) {
if (is.character(Data)) {
DataName = Data
}
Data = get(DataName)
} else {
DataName = as.character(match.call()$Data)
}
if (!is.data.frame(Data)) .NotADataFrame()
}
if(VI){
VIOpenText = "VI("
VICloseText = ")"
}
else {
VIOpenText = ""
VICloseText = ""
}
if(Latex){
LatexOpenText = "VI("
LatexCloseText = ")"
}
else {
LatexOpenText = ""
LatexCloseText = ""
}
with(Data, {
if (!is.numeric(get(ResponseName)))
.ResponseNotNumeric()
if (!is.numeric(get(PredictorName)))
.PredictorNotNumeric()
}) # end data checking
# create folder and filenames
if (is.null(Folder)) Folder = DataName
if (Folder != "" & !file.exists(Folder)) dir.create(Folder)
if (is.null(Filename)) {
Filename = paste0(.simpleCap(ResponseName), ".",
.simpleCap(PredictorName), "-OnePredictor.Rmd")
}
ModelName = paste0(ResponseName, ".", PredictorName, ".lm")
# start writing to the R markdown file
cat('# Analysis of the', .simpleCap(DataName), 'data, using',
.simpleCap(ResponseName), 'as the response variable and',
.simpleCap(PredictorName),
'as the single predictor.
#### Prepared by ',
getOption("BrailleR.Author"), ' \n\n', file = Filename)
cat(paste0(
'```{r setup2, purl=FALSE, include=FALSE}
',
.ifelse(VI, "library(BrailleR)", ""),
.ifelse(Modern, "\nlibrary(tidyverse)\nlibrary(ggfortify)", ""),
'
library(knitr)
opts_chunk$set(dev=c("png", "pdf", "postscript", "svg"))
opts_chunk$set(echo=FALSE, comment="", fig.path="',
Folder, '/', .simpleCap(ResponseName), '.',
.simpleCap(PredictorName),
'-", fig.width=7)
```
<!--- IMPORTANT NOTE: This Rmd file does not yet import the data it uses.
You will need to add a data import command of some description into the next R chunk to use the file as a stand alone file. --->
```{r importData}
```
## Variable summaries
The response variable is ',
.simpleCap(ResponseName), ' and the predictor variable is ',
.simpleCap(PredictorName), '.
```{r VariableSummary}
attach(',
DataName, ')
SummaryResponse <- summary(na.omit(', ResponseName,
'))
SummaryPredictor <- summary(na.omit(', PredictorName,
'))
SummaryTable <- cbind(', ResponseName, '=SummaryResponse,',
PredictorName,
'=SummaryPredictor)
row.names(SummaryTable) <- c("Minimum","Lower Quartile", "Median","Mean","Upper Quartile","Maximum")
Sds <- c(sd(',
ResponseName, ', na.rm=T),sd(', PredictorName,
', na.rm=T))
Nas <- c(sum(is.na(', ResponseName, ')), sum(is.na(',
PredictorName,
')))
SummaryTable <- rbind(SummaryTable,"Standard Deviation"=Sds,"Missing Values"=Nas)
detach(',
DataName,
')
```
```{r PrintSummary, results="asis", purl=FALSE}
kable(t(SummaryTable), row.names=T, align=rep("c",8))
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
}
cat('## Scatter Plot\n\n', file = Filename, append = TRUE)
ScatterText = .ifelse(Modern, .GetModernStyleScatterText(ResponseName=ResponseName, PredictorName=PredictorName, DataName=DataName),
.GetOldStyleScatterText(ResponseName=ResponseName, PredictorName=PredictorName, DataName=DataName))
cat(ScatterText, file = Filename, append = TRUE)
cat(paste0('## Linear regression
```{r ', ModelName,
'}
', ModelName,
' <- lm(', ResponseName, '~', PredictorName, ', data=', DataName,
')
', .ifelse(VI, paste("VI(", ModelName, ")"), ""), '
',
.ifelse(VI, paste0("VI(summary(", ModelName, "))"), ""),
'
summary(', ModelName,
')
```\n\n'),
file = Filename, append = TRUE)
FittedText = .ifelse(Modern, .GetModernStyleFittedText(ResponseName=ResponseName, PredictorName=PredictorName, DataName=DataName, ModelName=ModelName),
.GetOldStyleFittedText(ResponseName=ResponseName, PredictorName=PredictorName, DataName=DataName, ModelName=ModelName))
cat(FittedText, file = Filename, append = TRUE)
ResidualText = .ifelse(Modern, .GetModernStyleResidualText(ModelName=ModelName), .GetOldStyleResidualText(ModelName=ModelName))
cat(ResidualText, file = Filename, append = TRUE)
if (VI) {
cat(paste0(
'A separate html page showing the residual analysis and model validity checking for ',
ModelName, ' is at [', ModelName, '.Validity.html](', ModelName,
'.Validity.html) \n\n'), file = Filename, append = TRUE)
}
cat(paste0('### One-way Analysis of Variance
```{r ANOVA', ModelName, '}
anova(',
ModelName, ')
``` \n\n'), file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r VariableSummaryTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', .simpleCap(ResponseName), '.',
.simpleCap(PredictorName),
'-VariableSummary.tex"
TabCapt = "Summary statistics for variables ',
.simpleCap(ResponseName), ' and ', .simpleCap(PredictorName),
'."
print(xtable(t(SummaryTable), caption=TabCapt, label="',
.simpleCap(ResponseName),
'-VariableSummary", digits=4, align="lrrrrrrrr"), include.rownames = FALSE, file = ThisTexFile)
```
```{r SimpleLinMod-TEX, purl=FALSE}
ThisTexFile = "', Folder,
'/', .simpleCap(ResponseName), '-', .simpleCap(PredictorName),
'-lm.tex"
TabCapt = "Linear regression model for ',
.simpleCap(ResponseName), ' with the single Predictor ',
.simpleCap(PredictorName), '."
print(xtable(', ModelName,
', caption=TabCapt, label="', ResponseName, '-', PredictorName,
'-lm", digits=4), file = ThisTexFile)
```
```{r ANOVA-TEX, purl=FALSE}
ThisTexFile = "',
Folder, '/', ResponseName, '-', PredictorName,
'-anova.tex"
TabCapt = "Analysis of variance for the linear regression model having ',
ResponseName, ' as the response and the Predictor ',
PredictorName, '."
print(xtable(anova(', ModelName,
'), caption=TabCapt, label="', ResponseName, '-', PredictorName,
'-lm", digits=4), file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# finish writing markdown and process the written file into html and an R script
knit2html(Filename, quiet = TRUE,
meta = list(css = FindCSSFile(getOption("BrailleR.Style"))))
file.remove(sub(".Rmd", ".md", Filename))
purl(Filename, quiet = TRUE, documentation = 0)
if (View) browseURL(sub(".Rmd", ".html", Filename))
environment(VI.lm) <- VI.env
} # end of OnePredictor function
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/OnePredictor.R
|
# functions for setting the package options as easily as possible. Most do not have arguments.
# these ones do have arguments
ResetDefaults =
function(Local = interactive()) {
if (interactive()) {
DefSettings = system.file("BrailleROptions", package = "BrailleR")
PrefSettings =
file.path(getOption("BrailleR.Folder"), "BrailleROptions")
file.copy(DefSettings, PrefSettings, overwrite = TRUE)
.OriginalDefaults()
if (Local) file.remove("BrailleROptions")
devtools::reload("BrailleR")
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
ChooseEmbosser =
function(
Embosser = "none", Permanent = interactive(), Local = interactive()) {
if (is.character(Embosser)) {
options(BrailleR.Embosser = Embosser)
.OptionUpdated("Embosser", Embosser)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.Embosser = Embosser
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.Embosser = Embosser
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.ExpectingText()
}
return(invisible(NULL))
}
ChooseSlideStyle =
function(css = "JGSlides.css", Permanent = interactive(),
Local = interactive()) {
if (is.character(css)) {
options(BrailleR.SlideStyle = css)
if (system.file("css", css, package = "BrailleR") == "") {
warning(
"The file", css,
"is not in the css folder of the BrailleR package.\nPlease put it there before re-issuing this command.\n")
} else {
.OptionUpdated("SlideStyle", css)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.SlideStyle = css
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.SlideStyle = css
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
}
} else {
.ExpectingText()
}
return(invisible(NULL))
}
ChooseStyle =
function(css = "BrailleR.css", Permanent = interactive(),
Local = interactive()) {
if (is.character(css)) {
options(BrailleR.Style = css)
if (system.file("css", css, package = "BrailleR") == "") {
warning(
"The file", css,
"is not in the css folder of the BrailleR package.\nPlease put it there before re-issuing this command.\n")
} else {
.OptionUpdated("Style", css)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.Style = css
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.Style = css
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
}
} else {
.ExpectingText()
}
return(invisible(NULL))
}
SetAuthor =
function(
name = "BrailleR", Permanent = interactive(), Local = interactive()) {
if (is.character(name)) {
options(BrailleR.Author = name)
.OptionUpdated("Author", name)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.Author = name
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.Author = name
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.ExpectingText()
}
return(invisible(NULL))
}
SetBRLPointSize =
function(pt, Permanent = FALSE, Local = interactive()) {
if ((10 < pt) & (pt < 40)) {
options(BrailleR.BRLPointSize = pt)
.OptionUpdated("BRLPointSize (for the braille font)", paste0(pt, " inches"))
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.BRLPointSize = pt
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.BRLPointSize = pt
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning("The point size must be between 10 and 40 .")
}
return(invisible(NULL))
}
SetLanguage =
function(
Language = "en_us", Permanent = interactive(), Local = interactive()) {
if (is.character(Language)) {
options(BrailleR.Language = Language)
.OptionUpdated("Language", Language)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.Language = Language
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.Language = Language
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.ExpectingText()
}
return(invisible(NULL))
}
SetMakeUpper =
function(Upper, Permanent = interactive(), Local = interactive()) {
Upper = as.logical(Upper)
if (is.logical(Upper)) {
options(BrailleR.MakeUpper = Upper)
.UpdatedSettingMSG(What="BrailleR.MakeUpper option for capitalising the initial letter of variable names", To=Upper)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.MakeUpper = Upper
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.MakeUpper = Upper
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning()
}
return(invisible(NULL))
}
SetPaperHeight =
function(Inches, Permanent = FALSE, Local = interactive()) {
if ((5 < Inches) & (Inches < 14)) {
options(BrailleR.PaperHeight = Inches)
.UpdatedSettingMSG(What = "BrailleR.PaperHeight option for the height of the embossed images", To=paste(Inches, "inches"))
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.PaperHeight = Inches
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.PaperHeight = Inches
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning("The height must be between 5 and 14 inches.")
}
return(invisible(NULL))
}
SetPaperWidth =
function(Inches, Permanent = FALSE, Local = interactive()) {
if ((5 < Inches) & (Inches < 14)) {
options(BrailleR.PaperWidth = Inches)
.UpdatedSettingMSG(What="BrailleR.PaperWidth option for the width of the embossed images", To=paste(Inches, "inches"))
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.PaperWidth = Inches
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.PaperWidth = Inches
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning("The width must be between 5 and 14 inches.")
}
return(invisible(NULL))
}
SetPValDigits =
function(digits, Permanent = interactive(), Local = interactive()) {
digits = as.integer(digits)
if (digits > 1) {
options(BrailleR.PValDigits = digits)
.UpdatedSettingMSG(What="BrailleR.PValDigits option for the number of decimal places to display for p values", To=digits)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.PValDigits = digits
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.PValDigits = digits
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning("The number of digits must be an integer greater than one")
}
return(invisible(NULL))
}
SetSigLevel =
function(alpha, Permanent = interactive(), Local = interactive()) {
if ((0 < alpha) & (alpha < 1)) {
options(BrailleR.SigLevel = alpha)
.UpdatedSettingMSG("BrailleR.SigLevel option for the level of alpha",To=alpha)
if (Permanent) {
Prefs = paste0(getOption("BrailleR.Folder"), "BrailleROptions")
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
OpSet$BrailleR.SigLevel = alpha
write.dcf(OpSet, file = Prefs)
.OptionPermanent()
}
if (Local) {
Prefs = "BrailleROptions"
if (file.exists(Prefs)) {
OpSet = as.data.frame(read.dcf(Prefs, all = TRUE))
}
OpSet$BrailleR.SigLevel = alpha
write.dcf(OpSet, file = Prefs)
.OptionLocal()
}
} else {
.NoChangeWarning("The level of alpha must be between 0 and 1.")
}
return(invisible(NULL))
}
# functions below this point have no arguments. (yet)
GoSighted =
function() {
options(BrailleR.VI = FALSE)
.GoSightedMSG()
return(invisible(NULL))
}
GoBlind =
function() {
options(BrailleR.VI = TRUE)
.GoBlindMSG()
return(invisible(NULL))
}
GoAdvanced =
function() {
options(BrailleR.Advanced = TRUE)
.GoAdvancedMSG()
return(invisible(NULL))
}
GoNovice =
function() {
options(BrailleR.Advanced = FALSE)
.GoNoviceMSG()
return(invisible(NULL))
}
ViewOn = function() {
options(BrailleR.View = TRUE)
.ViewOnMSG()
return(invisible(NULL))
}
ViewOff =
function() {
options(BrailleR.View = FALSE)
.ViewOffMSG()
return(invisible(NULL))
}
LatexOn =
function() {
options(BrailleR.Latex = TRUE)
.LatexOnMSG()
return(invisible(NULL))
}
LatexOff =
function() {
options(BrailleR.Latex = FALSE)
.LatexOffMSG()
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Options.R
|
PandocAll = function(intype="docx", outtype="html"){
FileList=list.files(pattern=paste0(".",intype))
for(i in FileList){
Outfile = sub(paste0(".", intype), paste0(".", outtype), i)
if(file.mtime(i) > file.mtime(Outfile)| !file.exists(Outfile)) {
shell(paste0('pandoc -s "', i, '" -o "', Outfile, '"'))
.FileUpdated(file=Outfile, where="in your current working directory.")
}
}
return(invisible(TRUE))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/PandocAll.R
|
# @rdname Embossers
# @title Prepare BrailleR settings for specific braille embossers
# @aliases Premier100
# @description Convenience functions for setting package options based on experimentation using specific embossers.
# @details These functions are only relevant for owners of the specified embossers. Ownership of these models means the user has access to fonts that are licenced to the user.
#
# The Premier 100 embosser uses standard 11 by 11.5 inch fanfold braille paper. Printing in landscape or portrait is possible.
# @return Nothing. The functions are only used to set package options.
# @seealso \code{\link{ChooseEmbosser}}
# @author A. Jonathan R. Godfrey.
# @examples
# Premier100() # Specify use of the Premier 100 embosser.
# ChooseEmbosser() # reset to default: using no embosser.
# @export Premier100
Premier100 =
function() {
ChooseEmbosser("Premier100")
SetPaperWidth(10, TRUE)
SetPaperHeight(10, TRUE)
SetBRLPointSize(29, TRUE)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Premier100.R
|
# Getting started with the WriteR application
# only for Windows users at present.
## preparing for deprecation
## substituted with temporarily unavailable while testing the impact of removal
PrepareWriteR =
function(Author = getOption("BrailleR.Author")) {
if (interactive()) {
if (.Platform$OS.type == "windows") {
} else {
.WindowsOnly()
}
} else {
.InteractiveOnly()
}
return(invisible(NULL))
}
PrepareWriteR =
function(Author = getOption("BrailleR.Author")) {
.TempUnavailable()
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/PrepareWriteR.R
|
ProcessAllRmd = function(dir =".", method = "render"){
if (dir.exists(dir)) {
FileSet = list.files(dir, pattern="\\.Rmd$", full.names=TRUE)
}
else {.MissingFolder()}
.ProcessAll(dir = dir, method = method, FileSet, Extension=".Rmd")
return(invisible(NULL))
}
ProcessAllMd = function(dir ="."){
if (dir.exists(dir)) {
FileSet = list.files(dir, pattern="\\.md$", full.names=TRUE)
}
else {.MissingFolder()}
.ProcessAll(dir = dir, FileSet = FileSet, Extension=".md")
return(invisible(NULL))
}
.ProcessAll = function(dir =".", method = "render", FileSet, Extension=".Rmd") {
for(i in FileSet){
Outfile = sub(Extension, ".html", i)
if(file.mtime(i) > file.mtime(Outfile)| !file.exists(Outfile)) {
RemoveBOM(i)
if(method=="render"){
rmarkdown::render(i, output_format = "all")
}
else if(method=="knit2html"){
knitr::knit2html(i)
}
else{.MissingMethod()}
}
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/ProcessAll.R
|
# add commands to launch QuartoWriter
# add commands to create Qmd batch files
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Quarto.R
|
txtOut =
function(Filename = NULL) {
if (is.null(Filename)) {
message(
"Please enter a filename and press <enter>. \nPressing <enter> alone will generate a default filename \nbased on the current date and time.\n")
Filename = scan(, what = character(0), quiet = TRUE)
FullFilename = paste0(Filename[1], ".txt")
CommandSet = paste0(Filename[1], ".R")
} else {
FullFilename = paste(sub(".txt", "", Filename), "txt", sep = ".")
CommandSet = paste(sub(".txt", "", Filename), "R", sep = ".")
}
if (is.na(Filename[1])) {
Now = date()
Year = substr(Now, 21, 24)
Month = substr(Now, 5, 7)
Day = substr(Now, 9, 10)
Hour = substr(Now, 12, 13)
Minute = substr(Now, 15, 16)
FullFilename =
paste0("Term", Year, Month, Day, "-", Hour, Minute, ".txt")
CommandSet = paste0("Hist", Year, Month, Day, "-", Hour, Minute, ".R")
}
txtStart(file = FullFilename, cmdfile = CommandSet)
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/R2txtExtraJG.R
|
.R2txt.vars <- new.env()
R2txt <- function(cmd, res, s, vis) {
if (.R2txt.vars$first) {
.R2txt.vars$first <- FALSE
if (.R2txt.vars$res) {
sink()
close(.R2txt.vars$outcon)
.R2txt.vars$outcon <- textConnection(NULL, open = 'w')
sink(.R2txt.vars$outcon, split = TRUE)
}
} else {
if (.R2txt.vars$cmd) {
cmdline <- deparse(cmd)
cmdline <- gsub(
' ', paste("\n", .R2txt.vars$continue, sep = ''), cmdline)
cmdline <- gsub(
'}', paste("\n", .R2txt.vars$continue, "}", sep = ''), cmdline)
cat(.R2txt.vars$prompt, cmdline, "\n", sep = '', file = .R2txt.vars$con)
}
if (.R2txt.vars$cmdfile) {
cmdline <- deparse(cmd)
cmdline <- gsub(' ', "\n ", cmdline)
cmdline <- gsub('}', "\n}", cmdline)
cat(cmdline, "\n", file = .R2txt.vars$con2)
}
if (.R2txt.vars$res) {
tmp <- textConnectionValue(.R2txt.vars$outcon)
if (length(tmp)) {
cat(tmp, sep = '\n', file = .R2txt.vars$con)
sink()
close(.R2txt.vars$outcon)
.R2txt.vars$outcon <- textConnection(NULL, open = 'w')
sink(.R2txt.vars$outcon, split = TRUE)
}
}
}
TRUE
}
txtStart <- function(file, commands = TRUE, results = TRUE, append = FALSE,
cmdfile, visible.only = TRUE) {
tmp <- TRUE
if (is.character(file)) {
if (append) {
con <- file(file, open = 'a')
} else {
con <- file(file, open = 'w')
}
tmp <- FALSE
} else if (any(class(file) == 'connection')) {
con <- file
} else {
.NotAProperFileName()
}
if (tmp && isOpen(con)) {
.R2txt.vars$closecon <- FALSE
} else {
.R2txt.vars$closecon <- TRUE
if (tmp) {
if (append) {
open(con, open = 'a')
} else {
open(con, open = 'w')
}
}
}
.R2txt.vars$vis <- visible.only
.R2txt.vars$cmd <- commands
.R2txt.vars$res <- results
.R2txt.vars$con <- con
.R2txt.vars$first <- TRUE
if (results) {
.R2txt.vars$outcon <- textConnection(NULL, open = 'w')
sink(.R2txt.vars$outcon, split = TRUE)
}
if (!missing(cmdfile)) {
tmp <- TRUE
if (is.character(cmdfile)) {
con2 <- file(cmdfile, open = 'w')
tmp <- FALSE
} else if (any(class(cmdfile) == 'connection')) {
con2 <- cmdfile
}
if (tmp && isOpen(con2)) {
.R2txt.vars$closecon2 <- FALSE
} else {
.R2txt.vars$closecon2 <- TRUE
if (tmp) {
open(con2, open = 'w')
}
}
.R2txt.vars$con2 <- con2
.R2txt.vars$cmdfile <- TRUE
} else {
.R2txt.vars$cmdfile <- FALSE
}
.R2txt.vars$prompt <- unlist(options('prompt'))
.R2txt.vars$continue <- unlist(options('continue'))
options(prompt = paste('txt', .R2txt.vars$prompt, sep = ''),
continue = paste('txt', .R2txt.vars$continue, sep = ''))
message('Output being copied to text file,\nuse txtStop() to end.\n')
addTaskCallback(R2txt, name = 'r2txt')
invisible(NULL)
}
txtStop <- function() {
removeTaskCallback('r2txt')
if (.R2txt.vars$closecon) {
close(.R2txt.vars$con)
}
if (.R2txt.vars$cmdfile && .R2txt.vars$closecon2) {
close(.R2txt.vars$con2)
}
options(prompt = .R2txt.vars$prompt, continue = .R2txt.vars$continue)
if (.R2txt.vars$res) {
sink()
close(.R2txt.vars$outcon)
}
evalq(rm(list = ls()), envir = .R2txt.vars)
invisible(NULL)
}
txtComment <- function(txt, cmdtxt) {
.R2txt.vars$first <- TRUE
if (!missing(txt)) {
cat("\n", txt, "\n\n", file = .R2txt.vars$con)
}
if (!missing(cmdtxt)) {
cat("# ", cmdtxt, "\n", file = .R2txt.vars$con2)
}
}
txtSkip <- function(expr) {
.R2txt.vars$first <- TRUE
expr
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/R2txtJG.R
|
RemoveBOM = function(file){
FileLines = readLines(file)
Line1 = FileLines[1]
if(nchar(Line1)==6 & nchar(strsplit(Line1,"---")) ==3){
FileLines[1] = "---"
writeLines(FileLines, con=file)
.Done()
return(invisible(TRUE))
}
return(invisible(TRUE))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/RemoveBOM.R
|
Require = function(pkg){
pkg = as.character(substitute(pkg))
if(!suppressPackageStartupMessages(base::require(pkg, character.only=TRUE, warn.conflicts=FALSE))){
utils::chooseCRANmirror(ind=1)
utils::install.packages(pkg)
}
suppressPackageStartupMessages(base::require(pkg, character.only=TRUE, warn.conflicts=FALSE))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Require.R
|
#' Rewrite a SVG so that it can be properly explored with diagcess via the XML.
#' @rdname .RewriteSVG
#' The Rewrite SVG is a wrapper around the .RewriteSVGGeom function. It will loop through each
#' of the layers and do the necessary changes.
#'
#' @param x The graph object that the svg comes from
#' @param file The file of the SVG
#' @return NULL
#'
.RewriteSVG <- function(x, file, ...) {
svgDoc <- XML::xmlParseDoc(file)
# Loop through each layer and write the geom.
seq_along(x$layers) |>
lapply(function(layerIndex, graphObject, file, svg) {
geomGTagID <- .GetGeomID(graphObject, layerIndex)
# If the geomGTagID is empty then this geom is not supported.
if (is.null(geomGTagID)) {
NULL
}
geomGTag <- XML::getNodeSet(
svg,
paste0('//*[@id="', geomGTagID, '"]')
)[[1]]
.RewriteSVGGeom(graphObject, x$layer[[layerIndex]]$geom, geomGTagID, geomGTag, layerIndex, ...)
}, graphObject = x, file = file, svg = svgDoc)
XML::saveXML(svgDoc, file = file)
return(invisible())
}
#' @rdname .RewriteSVG
#'
#' The internal workhorse of the RewriteSVG function. These functions have all the specific
#' things that need to be done with the SVG to make it properly accessible.
#' Most of these functions have something has to line up with the AddXML internal functions.
#'
#' @param geomGTagID Id of the geomGTag
#' @param geomGTag This is the g tag with which all of this layers geom tags are inside
#' @param ... Any other variables needed by the function.
#'
.RewriteSVGGeom <- function(x, type, geomGTagID, geomGTag, ...) {
UseMethod(".RewriteSVGGeom", type)
}
.RewriteSVGGeom.default <- function(x, type, geomGTagID, geomGTag, ...) {
# Nothing is to be done by default
}
.RewriteSVGGeom.GeomLine <- function(x, type, geomGTagID, geomGTag, layer = 1, ...) {
struct <- .VIstruct.ggplot(x)[["panels"]][[1]][["panellayers"]][[layer]]
# Need to figure out how many lines there are
numLines <- struct[["lines"]] |>
length()
for (lineNum in 1:numLines) {
# Will grab the correct polyline as there will be a text and polyline for each line.
# The poly line gets deleted at end of this loop
# So the next polyine will always be + 1 the line number
if (.IsGeomLineDisjoint(struct$lines[[lineNum]]$scaledata)) {
regex <- paste0(.CreateID(geomGTagID, lineNum), "[a-z]")
polylinesToBeSplit <- XML::xmlChildren(geomGTag) |>
Filter(function(polyline) {
numMatches <- XML::xmlGetAttr(polyline, "id") |>
grep(regex, x = _) |>
length()
# Only if there is just one match
numMatches == 1
}, x = _)
newSegmentIDs <- polylinesToBeSplit |>
lapply(XML::xmlGetAttr, name = "id")
} else {
polylinesToBeSplit <- XML::xmlChildren(geomGTag)[[lineNum + 1]] |>
list()
newSegmentIDs <- .CreateID(geomGTagID, lineNum)
}
polylinesToBeSplit |>
mapply(function(line, i, segmentIDs) {
# Get the g tag for the line for the segments to go into
segmentParentGTag <- XML::newXMLNode("g",
parent = geomGTag,
attrs = list(id = segmentIDs)
)
XML::addChildren(geomGTag, segmentParentGTag)
# Split the line into smaller polylines
.RewriteSVG_SplitPoly(segmentParentGTag,
line,
id = segmentIDs
)
}, line = _, i = seq_along(polylinesToBeSplit), segmentIDs = newSegmentIDs)
}
}
.RewriteSVGGeom.GeomPoint <- function(x, type, geomGTagID, geomGTag, layer = 1, ...) {
pointNodes <- XML::xmlChildren(geomGTag)
structLayer <- .VIstruct.ggplot(x)[["panels"]][[1]][["panellayers"]][[layer]][["scaledata"]]
numPoints <- structLayer$x |> length()
orderOfIDs <- data.frame(x = structLayer$x, id = 1:numPoints) |>
dplyr::arrange(x) |>
select(id) |>
unlist()
pointGroups <- .SplitData(orderOfIDs)
# Only summarized the points if there are atelast 5 summarized secionts
if (numPoints > 5) {
# For each section go through get all of the use tags that should be in
# The section and move them there
for (sectionNum in 1:length(pointGroups)) {
# Create new section tag
newSectionGTag <- XML::newXMLNode("g",
parent = geomGTag,
attrs = list(id = paste(
geomGTagID,
letters[sectionNum],
sep = "."
))
)
pointNodes[pointGroups[[sectionNum]] * 2] |>
XML::addChildren(newSectionGTag, kids = _)
}
}
}
.RewriteSVGGeom.GeomSmooth <- function(x, type, geomGTagID, geomGTag, layer = 1, ...) {
ribbonAndLine <- XML::xmlChildren(geomGTag)
## Checking to see if it has a SE ribbon around the fitted line.
if (length(ribbonAndLine) == 3) {
hasCI <- FALSE
} else {
hasCI <- TRUE
## Split up the CI polygon into 5 polygons
ribbonGTag <- ribbonAndLine[[2]]
polygonGTag <- XML::xmlChildren(ribbonGTag)[[2]]
polygonGTagID <- XML::xmlGetAttr(polygonGTag, "id")
polygonTag <- XML::xmlChildren(polygonGTag)$polygon
# Update the stroke so that when it is changed colour by Diagcess on selection
# it will actually be highlighted
XML::`xmlAttrs<-`(polygonTag, value = c(`stroke-opacity` = 0.4, `stroke-width` = 0.4))
.RewriteSVG_SplitPoly(polygonGTag, polygonTag, id = .CreateID(layer, "smoother_ci"), type = "polygon")
## Move polygon to base geomGTag
XML::addChildren(geomGTag, polygonGTag)
XML::removeChildren(geomGTag, ribbonGTag)
}
## Split up the line into subparts
polylineGTag <- ribbonAndLine[[ifelse(hasCI, 4, 2)]]
polylineGTagID <- XML::xmlGetAttr(polylineGTag, "id")
polylineTag <- XML::xmlChildren(polylineGTag)$polyline
.RewriteSVG_SplitPoly(polylineGTag, polylineTag, id = .CreateID(layer, "smoother_line"))
## Take the 2 g tag with 5 polygon/polyline tags inside each of them.
## I want to zip them together so that I have 5 g tags with a polyline and polygon in each of them.
if (hasCI) {
# There are always two text elements at the start of the list. These ought
# to be removed
polygons <- XML::xmlChildren(polygonGTag)[3:7]
polylines <- XML::xmlChildren(polylineGTag)[3:7]
mapply(
function(index, polygon, polyline, parentGTag, IDBase) {
# New node as child of the Geom g tag
XML::newXMLNode("g",
polygon, polyline,
attrs = list(id = paste(IDBase, letters[index], sep = ".")),
parent = parentGTag
)
},
1:length(polygons), polygons, polylines,
MoreArgs = list(parentGTag = geomGTag, IDBase = geomGTagID)
)
# Remove the old polygon and polyline
XML::removeChildren(geomGTag, polylineGTag, polygonGTag)
}
}
#' @rdname .RewriteSVG
#'
#' This is used to split both polylines and polygons. It will behave slightly differently depending on the parameter.
#' However by default it will split a polyline.
#'
#' Splitting of the points is doen with the .SplitPolyPoint functions.
#'
#' @param parentGTag This is the parent g tag which the new polylines will be children of
#' @param id The id of the new polyline. The id of these new polylines will be the argument with a letter added to end.
#' @param originalPoly original poly that you wish to split up.
#' @param type Type of the poly it is currently only support for polygon and polyline
#'
#' @return Returns nothing
#'
.RewriteSVG_SplitPoly <- function(parentGTag, originalPoly, id = "", type = "polyline") {
## Copy attributes from the original segment
polyAttr <- XML::xmlAttrs(originalPoly)
polyAttr <- polyAttr[!(names(polyAttr) %in% c("id", "points"))]
polyAttr <- split(polyAttr, names(polyAttr))
## Get the line points
points <- originalPoly |>
XML::xmlGetAttr("points") |>
strsplit(" ") |>
unlist()
# Split the points up based on the type of poly it is
nSections <- ifelse(length(points) > 5, 5, length(points))
pointsSplit <- .SplitPolyPoints(points, structure(type, class = type), nSections)
## For each segment add in a new poly with all the correct attributes
seq_along(pointsSplit) |>
lapply(function(i) {
args <- polyAttr
args$id <- paste(id, letters[i], sep = ".")
if (type == "polyline") args$`fill-opacity` <- "0"
args$points <- paste(pointsSplit[[i]], collapse = " ")
newPoly <- XML::newXMLNode(type, parent = parentGTag, attrs = args)
XML::addChildren(parentGTag, newPoly)
})
## Remove old line
XML::removeNodes(originalPoly)
return(invisible())
}
#' @rdname .RewriteSVG
#'
#' These functions will take a vector of points and split them into a certain number of sections.
#'
#' @param points A vector of points to be split into
#' @param polyType The poly type that the points come
#' @param nSections This is the number of resultant sections
#'
#' @return A list of vectors of points.
.SplitPolyPoints <- function(points, polyType, nSections) {
UseMethod(".SplitPolyPoints", polyType)
}
.SplitPolyPoints.polyline <- function(points, polyType, nSections) {
.SplitData(points, overlapping = TRUE)
}
.SplitPolyPoints.polygon <- function(points, polyType, nSections) {
# Polygon points start and work there way round the outside
# I will split this into top and bottom
pointsTopAndBottom <-
# Split the data into top and bottom
split(
points,
cut(seq_along(points),
2,
labels = FALSE,
include.lowest = TRUE
)
) |>
# Split each top and bottom section into sections
lapply(function(points) {
split(
points,
cut(seq_along(points),
nSections,
labels = FALSE,
include.lowest = TRUE
)
)
}) |>
# Go through the top and bottom and add one point from the next seciton
# This is so there will be a continous polygon
lapply(function(pointsCollection) {
pointsCollection |>
seq_along() |>
lapply(function(i) {
if (i != length(pointsCollection)) {
c(pointsCollection[[i]], pointsCollection[[i + 1]][1])
} else {
pointsCollection[[i]]
}
})
})
# As the points go aroudn the permiter the top needs to be reversed so that
# it starts at the lower end.
pointsTopAndBottom[[2]] <- rev(pointsTopAndBottom[[2]])
# Combine the top and bottom sections so that you just have nsection number
# of sections with top and bottom coordinates
mapply(c,
pointsTopAndBottom[[1]],
pointsTopAndBottom[[2]],
SIMPLIFY = FALSE
)
}
.SplitPolyPoints.default <- function(points, polyType, nSections) {
warning(paste("Sorry type '", class(polyType), "' is not supported yet"))
points
}
# vs Currently we hardcode the attributes. Should simply be copied.
# Old functions only held for backwards support with base R
.SplitPolyline <- function(points, root, start = 0, child = 1) {
children <- XML::getNodeSet(root, "//*[@points]")
polyline <- children[[child]]
attr <- XML::xmlGetAttr(polyline, "points")
coordinates <- strsplit(attr, " ")[[1]]
count <- 1
## result <- list()
for (i in 1:length(points)) {
node <- XML::newXMLNode("polyline", parent = root)
end <- count + points[i]
segment <- coordinates[count:end]
XML::addAttributes(
node,
id = paste("graphics-plot-1-lines-1.1.1", intToUtf8(utf8ToInt("a") + (i - 1)), sep = ""),
points = paste(segment[!is.na(segment)], collapse = " "),
"stroke-dasharray" = "none",
stroke = "rgb(0,0,0)",
"stroke-width" = "1",
"stroke-linecap" = "round",
"stroke-miterlimit" = "10",
"stroke-linejoin" = "round",
"stroke-opacity" = "1",
fill = "none"
)
XML::addChildren(root, node, at = i + (child - 1))
count <- end
}
XML::removeChildren(root, polyline)
return(invisible(NULL))
}
.RewriteSVG.tsplot <- function(x, file) {
svgDoc <- XML::xmlParseDoc(file) ## "Temperature.svg"
nodes <- XML::getNodeSet(
svgDoc,
'//*[@id="graphics-plot-1-lines-1.1"]'
)
if (length(nodes) == 0) {
return(invisible("Something went wrong!"))
}
.SplitPolyline(x$GroupSummaries$N, nodes[[1]])
XML::saveXML(svgDoc, file = file)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/RewriteSVG.R
|
Rnw2Rmd = function(file){
FindReplace(file, "<<>>=", "```{r}")
FindReplace(file, "<<", "```{r ")
FindReplace(file, "@", "```")
FindReplace(file, ">>=", "}")
FindReplace(file, "\\Sexpr{", "`{r ")
FindReplace(file, "results=hide", 'results="hide"')
FindReplace(file, "\\title{", "# ")
FindReplace(file, "\\author{", "### ")
FindReplace(file, "\\section{", "## ")
FindReplace(file, "\\subsection{", "### ")
FindReplace(file, "\\maketitle", "")
FindReplace(file, "\\begin{document}", "")
FindReplace(file, "\\ ", " ")
FindReplace(file, "\\end{document}", "")
FindReplace(file, "\\begin{equation}", "\n$$")
FindReplace(file, "\\end{equation}", "$$\n")
FindReplace(file, "\\today", "")
FindReplace(file, "\\date{}", "")
FindReplace(file, "\\cite{", "@")
# clean out excessive blank lines from the end.
Txt = readLines(file)
NoLines=length(Txt)
while(all(Txt[(NoLines-1):NoLines] == "")) {NoLines=NoLines-1}
writeLines(Txt[1:NoLines], con=file)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Rnw2Rmd.R
|
# this file is only for the SVGThis method and associated utility functions.
# SVGThis.default() needs interactive session but specific methods need not be
# this from Paul via maps example
## chekc it is not already incorporated into new version of gridSVG.
.addInfo <- function(name, title, desc) {
grid::grid.set(
name,
grid::gTree(
children = grid::gList(
elementGrob("title", children = grid::gList(textNodeGrob(title))),
elementGrob("desc", children = grid::gList(textNodeGrob(desc))),
grid::grid.get(name)
), name = name
),
redraw = FALSE
)
}
# next is partly from Paul via maps example, with additions from Jonathan
.MakeTigerReady <-
function(svgfile) { # for alterations needed on all SVG files
if (file.exists(svgfile)) {
cat("\n", file = svgfile, append = TRUE) # otherwise problems
# on readLines() below
temp <- readLines(con = svgfile)
writeLines(gsub("ISO8859-1", "ASCII", temp), con = svgfile)
} else {
.FileDoesNotExist(svgfile)
}
return(invisible(NULL))
}
# method is mostly Jonathan's use of Paul/Simon's work
SVGThis <- function(x, file = "test.svg", ...) {
UseMethod("SVGThis")
}
SVGThis.default <-
function(x, file = "test.svg", ...) {
if (is.null(x)) { # must be running interactively
if (dev.cur() > 1) { # there must also be an open graphics/grid device
if (length(grid::grid.ls(print = FALSE)$name) == 0) { # if not grid
# already, then
# convert
gridGraphics::grid.echo()
}
# then export to SVG
gridSVG::grid.export(name = file)
.MakeTigerReady(svgfile = file)
# no specific processing to be done in this function.
} # end open device condition
else { # no current device
.NoGraphicsDevice("to convert to SVG.")
}
} # end interactive condition
else { # not interactive session
warning(
"The default SVGThis() method only works for objects of specific classes.\nThe object supplied does not yet have a method written for it.\n"
)
}
return(invisible(NULL))
}
SVGThis.boxplot <-
function(x, file = "test.svg", ...) {
# really should check that the boxplot wasn't plotted already before...
# but simpler to just do the plotting ourselves and close the device later
x # ensure we create a boxplot on a new graphics device
gridGraphics::grid.echo() # boxplot() currently uses graphics package
gridSVG::grid.export(name = file)
dev.off() # remove our graph window
.MakeTigerReady(svgfile = file)
return(invisible(NULL))
}
SVGThis.dotplot <-
function(x, file = "test.svg", ...) {
# really should check that the dotplot wasn't plotted already before...
# but simpler to just do the plotting ourselves and close the device later
x # ensure we create a dotplot on a new graphics device
gridGraphics::grid.echo() # dotplot() currently uses graphics package
gridSVG::grid.export(name = file)
dev.off() # remove our graph window
.MakeTigerReady(svgfile = file)
return(invisible(NULL))
}
SVGThis.eulerr <-
function(x, file = "test.svg", ...) {
x <- Augment(x)
X <- stats::coef(x)[, 1L]
Y <- stats::coef(x)[, 2L]
R <- stats::coef(x)[, 3L]
Labels <- rownames(x$coefficients)
TextX <- x$TextPositions$x
TextY <- x$TextPositions$y
pushViewport(dataViewport(c(X - R, X + R), c(Y - R, Y + R)))
grid.circle(X, Y, R, default.units = "native", name = "VennCircles")
grid.text(Labels, TextX, TextY, default.units = "native", name = "VennLabels")
gridSVG::grid.export(name = file)
dev.off()
.MakeTigerReady(svgfile = file)
return(invisible(NULL))
}
# if createDevice is TRUE (the default) SVGThis will create its own
# (non-displaying) graphics device and destroy it when complete
# if FALSE it will use the currently active device
SVGThis.ggplot <-
function(x, file = "test.svg", createDevice = TRUE, ...) {
if (length(x$data$x) > 10000) {
warning("You are trying to make a svg from a plot with lots of data it might take quite some time.")
}
if (createDevice) {
pdf(NULL)
}
print(x)
gridSVG::grid.export(name = file)
# Rewrite the SVG to that it works with the AddXML
.RewriteSVG(x, file)
# Delete the display device
if (createDevice) {
dev.off()
}
.MakeTigerReady(svgfile = file)
return(invisible(NULL))
}
SVGThis.histogram <-
function(x, file = "test.svg", ...) {
# really should check that the histogram wasn't plotted already before...
# but simpler to just do the plotting ourselves and close the device later
x # ensure we create a histogram on a new graphics device
gridGraphics::grid.echo() # hist() currently uses graphics package
# use gridSVG ideas in here
gridSVG::grid.garnish(
"graphics-plot-1-bottom-axis-line-1",
title = "the x axis"
)
gridSVG::grid.garnish(
"graphics-plot-1-left-axis-line-1",
title = "the y axis"
)
# these titles are included in the <g> tag not a <title> tag
.addInfo("graphics-plot-1-bottom-axis-line-1",
title = "the x axis",
desc = "need something much smarter in here"
)
.addInfo("graphics-plot-1-left-axis-line-1",
title = "the y axis",
desc = "need something much smarter in here"
)
# .SVGThisBase(x)
# add class-specific content to svg file from here onwards
# short descriptions should be automatic, such as axis labels or marks
# long descriptions need to be constructed, such as describe all axis marks together
# find some way to embed the object from which the graph was created
gridSVG::grid.export(name = file)
dev.off() # remove our graph window
.MakeTigerReady(svgfile = file)
return(invisible(NULL))
}
.SVGThisBase <- function(x) {
# use gridSVG ideas in here
gridSVG::grid.garnish(
"graphics-plot-1-bottom-axis-line-1",
title = "the x axis"
)
gridSVG::grid.garnish(
"graphics-plot-1-left-axis-line-1",
title = "the y axis"
)
# these titles are included in the <g> tag not a <title> tag
.addInfo("graphics-plot-1-bottom-axis-line-1",
title = "the x axis",
desc = "need something much smarter in here"
)
.addInfo("graphics-plot-1-left-axis-line-1",
title = "the y axis",
desc = "need something much smarter in here"
)
}
SVGThis.scatterplot <- function(x, file = "test.svg", ...) {
x$x <- x$data$x
x$y <- x$data$y
x$data <- NULL
suppressWarnings(do.call(plot, x)) # ensure we create a plot on a new graphics device
gridGraphics::grid.echo() # plot() uses graphics package
gridSVG::grid.export(name = file)
dev.off() # remove our graph window
.MakeTigerReady(svgfile = file)
.FileCreated(file)
return(invisible(NULL))
}
SVGThis.tsplot <- function(x, file = "test.svg", ...) {
suppressWarnings(do.call(plot, x)) # ensure we create a plot on a new graphics device
gridGraphics::grid.echo() # plot() uses graphics package
gridSVG::grid.export(name = file)
dev.off() # remove our graph window
.MakeTigerReady(svgfile = file)
.FileCreated(file)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/SVGThis.R
|
ScatterPlot = function(.data, x, y=NULL, base=FALSE, ...){
MC <- match.call(expand.dots = TRUE)
if(base){
Out = list()
Out$data = .CleanData4TwoWayPlot(x, y)
Out$ExtraArgs = .GrabExtraArgs(MC)
Out$ExtraArgs$xlab = MC$xlab= .ifelse(is.null(MC$xlab), as.character(MC$x), MC$xlab)
Out$ExtraArgs$ylab = MC$ylab= .ifelse(is.null(MC$ylab), as.character(MC$y), MC$ylab)
Out = .checkTextLabels(MC, Out)
MC[[1L]] <- quote(graphics::plot)
MC$x <- Out$data$x
MC$y <- Out$data$y
Out$graph <- eval(MC, envir=parent.frame())
Out$par = par()
class(Out) = "scatterplot"
Out=Augment(Out)
return(invisible(Out))
}
else{ ## do it in ggplot2
Out=ggplot(.data, aes(x=x, y=y)) + geom_point()
return(Out)
}
}
FittedLinePlot = function(.data, x, y, line.col=2, base=FALSE, ...){
MC <- match.call(expand.dots = TRUE)
if(base){
Out = list()
Out$data = .CleanData4TwoWayPlot(x, y)
Out$fittedline = list(coef = coef(lm(y~x, data=Out$data)),
col = line.col)
Out$ExtraArgs = .GrabExtraArgs(MC)
Out$ExtraArgs$xlab = MC$xlab = .ifelse(is.null(MC$xlab), as.character(MC$x), MC$xlab)
Out$ExtraArgs$ylab = MC$ylab= .ifelse(is.null(MC$ylab), as.character(MC$y), MC$ylab)
Out = .checkTextLabels(MC, Out)
MC$x <- Out$data$x
MC$y <- Out$data$y
MC$line.col=NULL
Out$graph <- do.call(graphics::plot, as.list(MC[-1]))
Out$par = par()
class(Out) = c("fittedlineplot", "scatterplot")
Out=Augment(Out)
do.call(abline, Out$fittedline)
return(invisible(Out))
}
else{ ## do it in ggplot2
Out=ggplot(.data, aes(x=x, y=y)) + geom_point() + geom_smooth(method="lm", col=line.col)
return(Out)
}
}
plot.fittedlineplot = function(x, ...){
x$x= x$data$x
x$y = x$data$y
Pars=x$ExtraArgs
if(any(class(x) == "fittedlineplot")) fitline = x$fittedline
x = .RemoveExtraGraphPars(x)
suppressWarnings(do.call(plot, c(x, Pars)))
if(any(class(x) == "fittedlineplot")) do.call(abline, fitline)
return(invisible(NULL))
}
plot.scatterplot = print.fittedlineplot = print.scatterplot = plot.fittedlineplot
.RemoveExtraGraphPars = function(x){
ToRemoveBrailleRBits = c("xTicks", "yTicks", "par", "GroupSummaries", "Continuous", "coef", "data", "fittedline", "main", "sub", "xlab", "ylab", "ExtraArgs", "line.col")
ToRemoveBasePar = c("cin", "cra", "csi", "cxy", "din", "page")
ToRemove = c(ToRemoveBasePar, ToRemoveBrailleRBits)
x2 = x[setdiff(names(x), ToRemove)]
class(x2) = class(x)
return(invisible(x2))
}
.GrabExtraArgs = function(x){
ToRemove = c("", "x", "y", "main", "xlab", "ylab", "sub", "line.col")
ExtraArgs = (as.list(x))[setdiff(names(x), ToRemove)]
return(invisible(ExtraArgs))
}
.CleanData4TwoWayPlot = function(x, y){
Ord = order(x,y)
return(invisible(na.omit(data.frame(x=x[Ord], y=y[Ord]))))
}
.checkTextLabels = function(MC, Out){
if (length(MC$main) > 0) Out$ExtraArgs$main = as.character(MC$main) else {Out$ExtraArgs$main = ""}
if (length(MC$sub) > 0) Out$ExtraArgs$sub = as.character(MC$sub)
if (length(MC$xlab) > 0) Out$ExtraArgs$xlab = as.character(MC$xlab)
if (length(MC$ylab) > 0) Out$ExtraArgs$ylab = as.character(MC$ylab)
return(invisible(Out))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/ScatterPlot.R
|
.DefaultPath = function(){
defaultPath = "~/MyBrailleR/"
defaultPath <- normalizePath(defaultPath, mustWork = FALSE)
return(defaultPath)
}
.CheckMyBrailleR = function(){
return(dir.exists(.DefaultPath()))
}
.MyBrailleRName = function(){
Out=NULL
if(.CheckMyBrailleR()) {Out = .DefaultPath()}
else{ .NoBrailleRFolder()}
return(Out)
}
SetupBrailleR =
function() {
defaultPath = .DefaultPath()
Folder = NULL
if (dir.exists(defaultPath)) {
Folder = normalizePath(defaultPath)
.MoveBrailleRFiles(Folder)
} else if (interactive()) {
prompt <-
"The BrailleR package needs to create a directory that will hold your files.\n
It is convenient to use one in your home directory, because \nit remains after restarting R.\n\n"
prompt <- c(
prompt,
sprintf("Do you wish to create the '%s' directory?\n", defaultPath))
message(prompt)
UserPref =
menu(list(paste("Yes: create", defaultPath, "now"),
"No,not this time"),
title = "Do you want to create the (almost) permanent folder?")
if (UserPref == 1) {
dir.create(defaultPath)
cat("This folder is for the BrailleR package to be used with the R statistical software application.\nIt was created on",
format(Sys.Date(), "%A %d %B %Y"), "\nusing version",
as.character(utils::packageVersion("BrailleR")), "of BrailleR.\n",
file = file.path(defaultPath, "Readme.txt"))
message(
"Using the permanent folder for this session and every session from now onwards.\nYou can delete the folder at any time.")
Folder = normalizePath(defaultPath)
.MoveBrailleRFiles(Folder)
} else {
message(
"N.B. You will be asked again next time you load the BrailleR package.")
}
}
return(invisible(Folder))
}
.MoveBrailleRFiles =
function(Folder) {
Folder <- normalizePath(Folder, mustWork = FALSE)
# move various options and settings files here, use overwrite=FALSE
BrailleRSettings =
system.file("MyBrailleR/BrailleROptions", package = "BrailleR")
file.copy(BrailleRSettings, Folder, overwrite = FALSE)
WriteRSettings =
system.file("MyBrailleR/WriteROptions", package = "BrailleR")
file.copy(
WriteRSettings, file.path(Folder, "WriteROptions"), overwrite = FALSE)
if (!dir.exists(file.path(Folder, "css"))) {
dir.create(file.path(Folder, "css"))
}
CSSFolder = file.path(system.file(package = "BrailleR"), "MyBrailleR/css")
CSSFiles = list.files(path = CSSFolder, pattern = "css")
file.copy(file.path(CSSFolder, CSSFiles),
file.path(Folder, "css", CSSFiles), overwrite = FALSE)
AutoSpell =
system.file("MyBrailleR/AutoSpellList.csv", package = "BrailleR")
file.copy(
AutoSpell, file.path(Folder, "AutoSpellList.csv"), overwrite = FALSE)
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/SetupBrailleR.R
|
# do we need this given spelling package now exists??
SpellCheck =
function(file) {
if (interactive()) {
for (ThisFile in file) {
cat(paste0(ThisFile, ": "))
if (file.exists(ThisFile)) {
file.copy(ThisFile, paste0(ThisFile, ".bak"), overwrite = FALSE)
cat("\n", file = ThisFile, append = TRUE) # otherwise problems
# on readLines() below
OldText <- readLines(con = ThisFile)
Mistakes = SpellCheckFiles(file = ThisFile)
for (i in names(Mistakes[[1]])) {
Lines = gsub(",", ", ", Mistakes[[1]][i])
LineNos = as.numeric(unlist(strsplit(Lines, ", ")))
UserPref = 6
while (UserPref > 4) {
UserPref =
menu(
list(
"Ignore this word",
"add this word to the global list of words to ignore",
"add this word to the list of words to ignore when checking this file",
"change it to...",
paste0("read the word '", i, "' in context")),
title = paste0(
"\n", i, " appears to be misspelled on ",
ifelse(length(LineNos) > 1, "lines", "line"), Lines))
if (UserPref == "5") {
cat(paste0(OldText[LineNos], "\n"))
}
} # end of the while loop
if (UserPref == "2") {
cat(paste0(i, "\n"), file = paste0(getOption("BrailleR.Folder"),
"words.ignore.txt"),
append = TRUE)
}
if (UserPref == "3") {
cat(paste0(i, "\n"), file = paste0(ThisFile, ".ignore.txt"),
append = TRUE)
}
if (UserPref == "4") {
cat("Enter replacement text: ")
Replace = readLines(n = 1)
OldText = gsub(i, Replace, OldText)
}
} # end of misspelled words loop
NoLines = length(OldText)
if (NoLines > 2) {
if (all(OldText[c(NoLines - 1, NoLines)] == "\n")) {
NoLines = NoLines - 1
}
}
writeLines(OldText[1:NoLines], con = ThisFile)
.Done()
} # end ThisFile exists condition
else {
.FileDoesNotExist(file)
}
} # end for loop for files
} # end interactive ondition
else {
.InteractiveOnly()
}
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/SpellCheck.R
|
## need to fix this to revert to spelling package
SpellCheckFiles =
function(file = ".", ignore = character(), local.ignore = TRUE,
global.ignore = TRUE) {
ignore <- c(hunspell::en_stats, ignore)
if (global.ignore) {
globalIgnoreFile =
paste0(getOption("BrailleR.Folder"), "words.ignore.txt")
if (file.exists(globalIgnoreFile)) {
ignore = c(ignore, read.table(globalIgnoreFile,
colClasses = "character")[, 1])
}
}
if (dir.exists(file)) {
filenames = list.files(file)
checkFiles <- normalizePath(paste0(file, "/", filenames))
if (file.exists(as.character(local.ignore))) {
ignore =
c(ignore, read.table(local.ignore, colClasses = "character")[, 1])
}
} else {
filenames = checkFiles <- file
localIgnoreFile = paste0(filenames, ".ignore.txt")
if (file.exists(localIgnoreFile)) {
ignore = c(ignore,
read.table(localIgnoreFile, colClasses = "character")[, 1])
}
}
# a little hack because Hadley doesn't want to export spell_check_file from the devtools package
NS = getNamespace("devtools")
spell_check_file = get("spell_check_file", NS)
checkLines = list()
checkLines <- lapply(
checkFiles, spell_check_file, ignore = ignore, dict="en_us")
names(checkLines) = filenames
class(checkLines) = c("wordlist", "data.frame")
return(checkLines)
}
print.wordlist =
function(x, ...) {
for (i in 1:length(x)) {
cat(paste0("File: ", names(x)[i], "\n"))
cat(paste0(names(x[[i]]), " ", gsub(",", " ", x[[i]]), "\n"))
}
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/SpellCheckFiles.R
|
# still need to insert factor name in error message; look for which
.BlankStop = function() {
stop("\n")
return(invisible(NULL))
}
.FactorNotFactor = function(which=NULL) {
stop("The factor is not stored as a factor.\nTry using as.factor() on a copy of the data.frame.")
return(invisible(NULL))
}
.GroupNotFactor = function() {
stop("The group variable is not a factor.\nTry using as.factor() on a copy of the data.frame.")
return(invisible(NULL))
}
.MissingFolder = function() {
stop("Specified folder does not exist.\n")
return(invisible(NULL))
}
.MissingMethod = function() {
stop("Specified method is not yet available.\n")
return(invisible(NULL))
}
.NoBrailleRFolder= function() {
stop("No permanent MyBrailleR folder was found.\n Use `SetupBrailleR()` to fix this problem.")
return(invisible(NULL))
}
.NoResponse = function() {
stop("You must specify either the Response or the ResponseName.")
return(invisible(NULL))
}
.NotADataFrame = function() {
stop("The named dataset is not a data.frame.")
return(invisible(NULL))
}
.NotAProperFileName = function() {
stop('file must be a character string or connection')
return(invisible(NULL))
}
.NotViewable = function() {
stop("The named data is not a data.frame, matrix, or vector so cannot be viewed.")
return(invisible(NULL))
}
.NoYNeeds2X = function() {
stop("If y is not supplied, x must have two numeric columns")
return(invisible(NULL))
}
.PredictorNotNumeric = function() {
stop("The predictor variable is not numeric.")
return(invisible(NULL))
}
.ResponseNotNumeric = function() {
stop("The response variable is not numeric.")
return(invisible(NULL))
}
.ResponseNotAVector = function() {
stop("Input response is not a vector.")
return(invisible(NULL))
}
.XOrYNotNumeric = function(which="y") {
stop("The x or y variable is not numeric.")
return(invisible(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Stop.R
|
TimeSeriesPlot = function(.data, x, time=NULL, base=FALSE, ...){
Out = list()
MC = match.call(expand.dots = TRUE)
if(base){
Out = list(x=as.ts(x))
MC$ylab= ifelse(is.null(MC$ylab), as.character(MC$x), MC$ylab)
MC[[1L]] <- quote(graphics::plot)
MC$x <- Out$x
Out$graph <- eval(MC, envir=parent.frame())
Out$par = par()
class(Out) = "tsplot"
if (length(MC$main) > 0) Out$main = as.character(MC$main) else {Out$main = ""}
if (length(MC$sub) > 0) Out$sub = as.character(MC$sub)
if (length(MC$xlab) > 0) Out$xlab = as.character(MC$xlab) else {Out$xlab = "Time"}
if (length(MC$ylab) > 0) Out$ylab = as.character(MC$ylab)
Out=Augment(Out)
}
else{ ## do it in ggplot2
MC$ylab = ifelse(is.null(MC$ylab), tail(strsplit(as.character(MC$x), "$"),n=1), MC$ylab)
if (length(MC$sub) > 0) Out$sub = as.character(MC$sub)
if (length(MC$xlab) > 0) Out$xlab = as.character(MC$xlab) else {Out$xlab = "Time"}
if (length(MC$ylab) > 0) Out$ylab = as.character(MC$ylab)
if (length(MC$main) > 0) Out$main = as.character(MC$main)
#Special care has to be taken if it is a dataframe
if (is.ts(.data)) {
#Sort out data frame
.data = data.frame(Y=as.matrix(.data), date=time(.data))
time = .data$date
x = .data$Y
#Get correct ylab
Out$ylab = ifelse(is.null(MC$ylab[[1]]), deparse(MC$.data), MC$ylab)
} else if (!is.data.frame(.data)) {
x = .data
.data = data.frame(x=x)
}
if (is.null(time)) time = 1:length(x)
Out = ggplot(.data, aes(y=x, x=time)) +
geom_line() +
ylab(Out$ylab) + xlab(Out$xlab) +
labs(title=Out$main, subtitle=Out$sub)
}
return(invisible(Out))
}
plot.tsplot = function(x, ...){
x = .RemoveExtraGraphPars(x) # see ScatterPlot.R for this function
suppressWarnings(do.call(plot, x))
return(invisible(NULL))
}
print.tsplot = plot.tsplot
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/TSPlot.R
|
.BoxplotText = function(fivenum, outliers=NULL, horizontal=FALSE){
Outs=length(outliers)
TextOuts = ifelse(Outs==0, "no", as.character(Outs))
ShortText = paste("Min", fivenum[1], "Lower quartile", fivenum[2], "Median", fivenum[3], "Upper quartile", fivenum[4], "Max", fivenum[5], "with", TextOuts, ifelse(Outs==1, "outlier.", "outliers."))
Text1 = Text2 = Text3 = Text4 = Text5 = Text6 = ""
if (Outs>0) {
Text1 = paste(ifelse(Outs==1, "An outlier is", "Outliers are"), 'marked at:', outliers)
} else{
Text1 = "no outliers"
}
Text2 = paste('The whiskers extend to', fivenum[1], 'and', fivenum[5],
'from the ends of the box, \nwhich are at', fivenum[2], 'and',
fivenum[4], '\n')
BoxLength = fivenum[4] - fivenum[2]
Text3 = paste('The median,', fivenum[3], 'is',
round(100 * (fivenum[3] - fivenum[2]) / BoxLength, 0),
'% from the', ifelse(horizontal, 'left', 'lower'),
'end of the box to the', ifelse(horizontal, 'right', 'upper'),
'end.\n')
Text4 = paste('The', ifelse(horizontal, 'right', 'upper'), 'whisker is',
round((fivenum[5] -
fivenum[4]) / (fivenum[2] - fivenum[1]), 2),
'times the length of the', ifelse(horizontal, 'left', 'lower'),
'whisker.\n')
LongText = c(Text1, Text2, Text3, Text4)
return(invisible(list(Short=ShortText, Long=LongText)))
}
.GetAxisTicks =
function(x) {
A = x[1]
B = x[2]
Ticks = x[3]
paste(paste0(seq(A, B - (B - A)/Ticks, (B - A) / Ticks), ",", collapse = " "),
"and", B, collapse = " ")
}
.ScatterPlotText = function(x, MedianX=x$GroupSummaries$MedianX, MedianY=x$GroupSummaries$MedianY, MeanX=x$GroupSummaries$MeanX, MeanY=x$GroupSummaries$MeanY, MinX=x$GroupSummaries$MinX, MinY=x$GroupSummaries$MinY, MaxX=x$GroupSummaries$MaxX, MaxY=x$GroupSummaries$MaxY, SDX=x$GroupSummaries$SDX, SDY=x$GroupSummaries$SDY, CorXY=x$GroupSummaries$CorXY, N=x$GroupSummaries$N){
ShortText = paste("Around X=", MedianX, "there are", N, "y values with median =", MedianY, "over the range", MinY, "to", MaxY)
LongText = paste("X=", MedianX, "has y values with median =", MedianY, "over the range", MinY, "to", MaxY, "; the values have a correlation of", CorXY)
return(invisible(list(Short=ShortText, Long=LongText)))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/TextStrings.R
|
## Last Edited: 30/08/16
ThreeFactors =
function(Response, Factor1, Factor2, Factor3, Data = NULL,
Filename = NULL, Folder = NULL, VI = getOption("BrailleR.VI"),
Latex = getOption("BrailleR.Latex"),
View = getOption("BrailleR.View"), Modern=TRUE) {
# Check inputs are right form
if (length(Response) == 1) {
if (is.character(Response)) {
ResponseName = Response
}
} else {
ResponseName = as.character(match.call()$Response)
}
if (length(Factor1) == 1) {
if (is.character(Factor1)) {
Factor1Name = Factor1
}
} else {
Factor1Name = as.character(match.call()$Factor1)
}
if (length(Factor2) == 1) {
if (is.character(Factor2)) {
Factor2Name = Factor2
}
} else {
Factor2Name = as.character(match.call()$Factor2)
}
if (length(Factor3) == 1) {
if (is.character(Factor3)) {
Factor3Name = Factor3
}
} else {
Factor3Name = as.character(match.call()$Factor3)
}
if (is.null(Data)) {
Data = data.frame(get(ResponseName), get(Factor1Name), get(Factor2Name), get(Factor3Name))
names(Data) = c(ResponseName, Factor1Name, Factor2Name, Factor3Name)
DataName = paste0(ResponseName, ".And3Factors")
assign(DataName, Data,
envir = parent.frame())
} else {
if (length(Data) == 1) {
if (is.character(Data)) {
DataName = Data
}
Data = get(DataName)
} else {
DataName = as.character(match.call()$Data)
}
if (!is.data.frame(Data)) .NotADataFrame()
}
with(
Data,
{
if (!is.numeric(get(ResponseName)))
.ResponseNotNumeric()
if (!is.vector(get(ResponseName)))
.ResponseNotAVector()
if (!is.factor(get(Factor1Name)))
.FactorNotFactor(which="first")
if (!is.factor(get(Factor2Name)))
.FactorNotFactor(which="second")
if (!is.factor(get(Factor3Name)))
.FactorNotFactor(which="third")
}) # end data checking
# create folder and filenames
if (is.null(Folder)) Folder = DataName
if (Folder != "" & !file.exists(Folder)) dir.create(Folder)
if (is.null(Filename))
Filename =
paste0(DataName, ".Rmd")
# start writing to the R markdown file for all three factors
cat(paste0('# Analysis of the ', DataName, ' data, using ', ResponseName,
' as the response variable and the variables ', Factor1Name,
', ', Factor2Name,
', and ', Factor3Name,
' as factors.
#### Prepared by ',
getOption("BrailleR.Author"), ' \n\n'), file = Filename)
cat(paste0(
'```{r setup, include=FALSE}
',
.ifelse(VI, "library(BrailleR)", ""),
.ifelse(Modern, "\nlibrary(tidyverse)\nlibrary(ggfortify)", ""),
'
knitr::opts_chunk$set(dev=c("png", "pdf", "postscript", "svg"))
knitr::opts_chunk$set(echo=FALSE, comment="", fig.path="',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor2Name,
'-", fig.width=7)
```
<!--- IMPORTANT NOTE: This Rmd file does not yet import the data it uses.
You will need to add a data import command of some description into the next R chunk to use the file as a stand alone file. --->
```{r importData}
```
## Group summaries
```{r NewFunction} \n',
paste(readLines(system.file("Templates/nNonMissing.R", package="BrailleR")), collapse="\n"),
'\n```
```{r All3GroupSummary}
Data.Mean <- aggregate(', ResponseName, ', list(',
Factor1Name, ', ', Factor2Name, ', ', Factor3Name,
'), mean, na.rm=TRUE)
colnames(Data.Mean) = c("', Factor1Name,
'","', Factor2Name, '","', Factor3Name, '","Mean")
Data.StDev <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name, ', ', Factor3Name,
'), sd, na.rm=TRUE)
Data.n <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name,', ', Factor3Name,
'), nNonMissing)
Data.StdErr = Data.StDev[,4]/sqrt(Data.n[,4])
DataSummary = cbind(Data.Mean, Data.StDev[,4], Data.n[,4], Data.StdErr)
colnames(DataSummary) = c("',
Factor1Name, ' Level", "', Factor2Name, ' Level", "', Factor3Name,
' Level", "Mean", "Standard deviation", "n", "Standard error")
```
The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev[,4])/min(Data.StDev[,4]),2)`
```{r PrintSummary, results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r DataSummaryTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor2Name,'.', Factor3Name,
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
ResponseName, ' by level of ', Factor1Name, ', ', Factor2Name, ' and ',
Factor3Name,
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="lllrrrrr"), include.rownames = FALSE, file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# additional testing
cat('```{r DTMeans, message=FALSE}\n', file=Filename, append=TRUE)
cat(UseTemplate("DTGroupSummary.R",
c("DataName", "ResponseName", "FactorSet"),
c(DataName, ResponseName, paste0("list(", Factor1Name, ",", Factor2Name, ",", Factor3Name, ")") )), file=Filename, append=TRUE)
cat('```
```{r kableDTMeans, perl=FALSE}
kable(DataSummary)
```\n\n', file=Filename, append=TRUE)
# start writing to the R markdown file for pairs F1&F2
cat(paste0('### Group summaries, averaging over ', Factor3Name,'
```{r GroupSummary_', Factor1Name, '_', Factor2Name,'}
Data.Mean <- aggregate(', ResponseName, ', list(',
Factor1Name, ', ', Factor2Name,
'), mean, na.rm=TRUE)
colnames(Data.Mean) = c("', Factor1Name,
'","', Factor2Name, '", "Mean")
Data.StDev <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name,
'), sd, na.rm=TRUE)
Data.n <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name,
'), nNonMissing)
Data.StdErr = Data.StDev[,3]/sqrt(Data.n[,3])
DataSummary = cbind(Data.Mean, Data.StDev[,3], Data.n[,3], Data.StdErr)
colnames(DataSummary) = c("',
Factor1Name, ' Level", "', Factor2Name,
' Level", "Mean", "Standard deviation", "n", "Standard error")
```
The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev[,3])/min(Data.StDev[,3]),2)`
```{r PrintSummary_', Factor1Name, '_', Factor2Name,', results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r DataSummaryTex_', Factor1Name, '_', Factor2Name,', purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor2Name,
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
ResponseName, ' by level of ', Factor1Name, ' and ',
Factor2Name,
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="llrrrrr"), include.rownames = FALSE, file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# start writing to the R markdown file for pairs F1&F3
cat(paste0('### Group summaries, averaging over ', Factor2Name,'
```{r GroupSummary_', Factor1Name, '_', Factor3Name,'}
Data.Mean <- aggregate(', ResponseName, ', list(',
Factor1Name, ', ', Factor3Name,
'), mean, na.rm=TRUE)
colnames(Data.Mean) = c("', Factor1Name,
'","', Factor3Name, '", "Mean")
Data.StDev <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor3Name,
'), sd, na.rm=TRUE)
Data.n <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor3Name,
'), nNonMissing)
Data.StdErr = Data.StDev[,3]/sqrt(Data.n[,3])
DataSummary = cbind(Data.Mean, Data.StDev[,3], Data.n[,3], Data.StdErr)
colnames(DataSummary) = c("',
Factor1Name, ' Level", "', Factor3Name,
' Level", "Mean", "Standard deviation", "n", "Standard error")
```
The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev[,3])/min(Data.StDev[,3]),2)`
```{r PrintSummary_', Factor1Name, '_', Factor3Name,', results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r DataSummaryTex_', Factor1Name, '_', Factor3Name,', purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor3Name,
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
ResponseName, ' by level of ', Factor1Name, ' and ',
Factor3Name,
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="llrrrrr"), include.rownames = FALSE, file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# start writing to the R markdown file for pairs F2&F3
cat(paste0('### Group summaries, averaging over ', Factor1Name,'
```{r GroupSummary_', Factor2Name, '_', Factor3Name,'}
Data.Mean <- aggregate(', ResponseName, ', list(',
Factor2Name, ', ', Factor3Name,
'), mean, na.rm=TRUE)
colnames(Data.Mean) = c("', Factor2Name,
'","', Factor3Name, '", "Mean")
Data.StDev <- aggregate(',
ResponseName, ', list(', Factor2Name, ', ', Factor3Name,
'), sd, na.rm=TRUE)
Data.n <- aggregate(',
ResponseName, ', list(', Factor2Name, ', ', Factor3Name,
'), nNonMissing)
Data.StdErr = Data.StDev[,3]/sqrt(Data.n[,3])
DataSummary = cbind(Data.Mean, Data.StDev[,3], Data.n[,3], Data.StdErr)
colnames(DataSummary) = c("',
Factor2Name, ' Level", "', Factor3Name,
' Level", "Mean", "Standard deviation", "n", "Standard error")
```
The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev[,3])/min(Data.StDev[,3]),2)`
```{r PrintSummary_', Factor2Name, '_', Factor3Name,', results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r DataSummaryTex_', Factor2Name, '_', Factor3Name,', purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '.', Factor2Name, '.', Factor3Name,
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
ResponseName, ' by level of ', Factor2Name, ' and ',
Factor3Name,
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="llrrrrr"), include.rownames = FALSE, file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
######## Fit the anova model
cat(paste0(
'## Three-way Analysis of Variance
```{r ThreeWayANOVA}
MyANOVA <- aov(',
ResponseName, '~', Factor1Name, '*', Factor2Name, '*',
Factor3Name, ', data=', DataName, ')
',
.ifelse(VI, "VI(MyANOVA)", ""),
'
summary(MyANOVA)
``` \n\n'),
file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r ANOVA-TEX, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '-', Factor1Name, '-', Factor2Name,
'-ANOVA.tex"
TabCapt = "Two-way ANOVA for ',
.simpleCap(ResponseName), ' with the group factors ',
.simpleCap(Factor1Name), ' and ', .simpleCap(Factor2Name),
'."
print(xtable(MyANOVA, caption=TabCapt, label="',
ResponseName, '-', Factor1Name,
'-ANOVA", digits=4), file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
# finish writing markdown and process the written file into html and an R script
knit2html(Filename, quiet = TRUE, envir=globalenv(),
meta = list(css = FindCSSFile(getOption("BrailleR.Style"))))
file.remove(sub(".Rmd", ".md", Filename))
purl(Filename, quiet = TRUE, documentation = 0)
if (View) browseURL(sub(".Rmd", ".html", Filename))
} # end of ThreeFactors function
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/ThreeFactors.R
|
## Last Edited: 7/12/22
TwoFactors =
function(Response, Factor1, Factor2, Inter = FALSE, HSD = TRUE,
AlphaE = getOption("BrailleR.SigLevel"), Data = NULL,
Filename = NULL, Folder = NULL, VI = getOption("BrailleR.VI"),
Latex = getOption("BrailleR.Latex"),
View = getOption("BrailleR.View"), Modern=TRUE) {
# Check inputs are right form
if (length(Response) == 1) {
if (is.character(Response)) {
ResponseName = Response
}
} else {
ResponseName = as.character(match.call()$Response)
}
if (length(Factor1) == 1) {
if (is.character(Factor1)) {
Factor1Name = Factor1
}
} else {
Factor1Name = as.character(match.call()$Factor1)
}
if (length(Factor2) == 1) {
if (is.character(Factor2)) {
Factor2Name = Factor2
}
} else {
Factor2Name = as.character(match.call()$Factor2)
}
if (is.null(Data)) {
Data = data.frame(get(ResponseName), get(Factor1Name), get(Factor2Name))
names(Data) = c(ResponseName, Factor1Name, Factor2Name)
DataName = paste0(ResponseName, ".", Factor1Name)
assign(paste0(ResponseName, ".", Factor1Name, ".", Factor2Name), Data,
envir = parent.frame())
} else {
if (length(Data) == 1) {
if (is.character(Data)) {
DataName = Data
}
Data = get(DataName)
} else {
DataName = as.character(match.call()$Data)
}
if (!is.data.frame(Data)) .NotADataFrame()
}
with(Data, {
if (!is.numeric(get(ResponseName)))
.ResponseNotNumeric()
if (!is.vector(get(ResponseName)))
.ResponseNotAVector()
if (!is.factor(get(Factor1Name)))
.FactorNotFactor(which="first")
if (!is.factor(get(Factor2Name)))
.FactorNotFactor(which="second")
}) # end data checking
if(VI){
VIOpenText = "VI("
VICloseText = ")"
}
else {
VIOpenText = ""
VICloseText = ""
}
if(Latex){
LatexOpenText = "VI("
LatexCloseText = ")"
}
else {
LatexOpenText = ""
LatexCloseText = ""
}
# create folder and filenames
if (is.null(Folder)) Folder = DataName
if (Folder != "" & !file.exists(Folder)) dir.create(Folder)
if (is.null(Filename)){
Filename =
paste0(ResponseName, '.', Factor1Name, '.', Factor2Name,
'-TwoFactors', .ifelse(Inter, "WithInt", "NoInt"), '.Rmd')
}
# start writing to the R markdown file
cat(paste0('# Analysis of the ', DataName, ' data, using ', ResponseName,
' as the response variable and the variables ', Factor1Name,
.ifelse(Inter, ", ", " and "), Factor2Name,
.ifelse(Inter, ", and their interaction", ""),
' as factors.
#### Prepared by ',
getOption("BrailleR.Author"), ' \n\n'), file = Filename)
cat(paste0(
'```{r setup, purl=FALSE, include=FALSE}
',
.ifelse(VI, "library(BrailleR)", ""),
.ifelse(Modern, "\nlibrary(tidyverse)\nlibrary(ggfortify)", ""),
'
knitr::opts_chunk$set(dev=c("png", "pdf", "postscript", "svg"))
knitr::opts_chunk$set(echo=FALSE, comment="", fig.path="',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor2Name,
'-", fig.width=7)
```
<!--- IMPORTANT NOTE: This Rmd file does not yet import the data it uses.
You will need to add a data import command of some description into the next R chunk to use the file as a stand alone file. --->
```{r importData}
```
## Group summaries
```{r GroupSummary}
attach(',
DataName, ')
Data.Mean <- aggregate(', ResponseName, ', list(',
Factor1Name, ', ', Factor2Name,
'), mean, na.rm=TRUE)
colnames(Data.Mean) = c("', Factor1Name,
'","', Factor2Name, '", "Mean")
Data.StDev <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name,
'), sd, na.rm=TRUE)
nNonMissing <- function(x){
length(na.omit(x)) # length() includes NAs
}
Data.n <- aggregate(',
ResponseName, ', list(', Factor1Name, ', ', Factor2Name,
'), nNonMissing)
Data.StdErr = Data.StDev[,3]/sqrt(Data.n[,3])
detach(',
DataName,
')
DataSummary = cbind(Data.Mean, Data.StDev[,3], Data.n[,3], Data.StdErr)
colnames(DataSummary) = c("',
Factor1Name, ' Level", "', Factor2Name,
' Level", "Mean", "Standard deviation", "n", "Standard error")
```
The ratio of the largest group standard deviation to the smallest is `r round(max(Data.StDev[,3])/min(Data.StDev[,3]),2)`
```{r PrintSummary, results="asis", purl=FALSE}
kable(as.matrix(DataSummary), row.names=FALSE)
``` \n\n'),
file = Filename, append = TRUE)
######## Fit the anova model
cat(paste0(
'## Two-way Analysis of Variance
```{r TwoWayANOVA}
MyANOVA <- aov(',
ResponseName, '~', Factor1Name, .ifelse(Inter, "*", "+"),
Factor2Name, ', data=', DataName, ')
',
.ifelse(VI, "VI(MyANOVA)", ""),
'
summary(MyANOVA)
if(length(unique(Data.n[,3]))!=1){
MyANOVA2 <- aov(',
ResponseName, '~', Factor2Name, .ifelse(Inter, "*", "+"),
Factor1Name, ', data=', DataName, ')
',
.ifelse(VI, "VI(MyANOVA2)", ""), '
summary(MyANOVA2)
}
``` \n\n'),
file = Filename, append = TRUE)
cat('\n\n## Residual Analysis\n\n', file = Filename, append = TRUE)
ResidualText = .ifelse(Modern, .GetModernStyleResidualText(ModelName="MyANOVA"), .GetOldStyleResidualText(ModelName="MyANOVA"))
cat(ResidualText, file = Filename, append = TRUE)
cat('\n\n## Tests for homogeneity of Variance \n\n', file = Filename, append = TRUE)
if (Inter) {
cat(paste0('```{r BartlettTest}
bartlett.test(',
ResponseName, '~interaction(', Factor1Name, ',', Factor2Name,
'), data=', DataName,
')
```
```{r FlignerTest}
fligner.test(', ResponseName,
'~interaction(', Factor1Name, ',', Factor2Name, '), data=',
DataName, ')
``` \n\n'), file = Filename, append = TRUE)
} else {
cat(paste0('```{r BartlettTest}
bartlett.test(',
ResponseName, '~', Factor1Name, ', data=', DataName,
')
bartlett.test(', ResponseName, '~', Factor2Name, ', data=',
DataName, ')
```
```{r FlignerTest}
fligner.test(',
ResponseName, '~', Factor1Name, ', data=', DataName,
')
fligner.test(', ResponseName, '~', Factor2Name, ', data=',
DataName, ')
``` \n\n'), file = Filename, append = TRUE)
}
# Tukey HSD output and plots
if (HSD) {
cat(paste0(
'## Tukey Honestly Significant Difference test
```{r TukeyHSD, fig.cap="Plot of Tukey HSD"}
MyHSD <- TukeyHSD(MyANOVA, ordered=TRUE, conf.level=',
1 - AlphaE, ')
', .ifelse(VI, 'VI(MyHSD)', ""),
'
MyHSD
plot( MyHSD )
``` \n\n'), file = Filename,
append = TRUE)
}
if (Latex) {
cat(paste0(
'```{r DataSummaryTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, '/', ResponseName, '.', Factor1Name, '.', Factor2Name,
'-GroupSummary.tex"
TabCapt = "Summary statistics for ',
ResponseName, ' by level of ', Factor1Name, ' and ',
Factor2Name,
'"
print(xtable(DataSummary, caption=TabCapt, label="',
ResponseName,
'GroupSummary", digits=4, align="llrrrrr"), include.rownames = FALSE, file = ThisTexFile)
```
```{r ANOVA-TEX, purl=FALSE}
ThisTexFile = "',
Folder, '/', ResponseName, '-', Factor1Name, '-', Factor2Name,
.ifelse(Inter, "WithInt", "NoInt"),
'-ANOVA.tex"
TabCapt = "Two-way ANOVA for ',
.simpleCap(ResponseName), ' with the group factors ',
.simpleCap(Factor1Name), ' and ', .simpleCap(Factor2Name),
.ifelse(Inter, ", as well as their interaction",
" without their interaction"),
'.
print(xtable(MyANOVA, caption=TabCapt, label="',
ResponseName, '-', Factor1Name,
'-ANOVA", digits=4), file = ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
} # end LaTeX table creation
# finish writing markdown and process the written file into html and an R script
knit2html(Filename, quiet = TRUE,
meta = list(css = FindCSSFile(getOption("BrailleR.Style"))))
file.remove(sub(".Rmd", ".md", Filename))
purl(Filename, quiet = TRUE, documentation = 0)
if (View) browseURL(sub(".Rmd", ".html", Filename))
} # end of TwoFactors function
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/TwoFactors.R
|
UniDesc =
function(
Response = NULL, ResponseName = as.character(match.call()$Response),
Basic = TRUE, Graphs = TRUE, Normality = TRUE, Tests = TRUE,
Title = NULL, Filename = NULL, Folder = ResponseName, Process = TRUE,
VI = getOption("BrailleR.VI"), Latex = getOption("BrailleR.Latex"),
View = getOption("BrailleR.View"),
PValDigits = getOption("BrailleR.PValDigits")) {
if (is.null(Response)) {
if (length(ResponseName) == 0)
.NoResponse()
Response = get(ResponseName)
}
if(VI){
VIOpenText = "VI("
VICloseText = ")"
}
else {
VIOpenText = ""
VICloseText = ""
}
if(Latex){
LatexOpenText = "VI("
LatexCloseText = ")"
}
else {
LatexOpenText = ""
LatexCloseText = ""
}
# to ensure consistent and predictable appearance
StartChunk =
function(ChunkName, ThisFile = Filename) {
cat('\n```{r', ChunkName, '} \n', file = ThisFile, append = TRUE)
}
CloseChunk = function(ThisFile = Filename) {
cat('\n``` \n\n', file = ThisFile, append = TRUE)
}
GraphHead = function(GraphName, AltTag, ThisFile = Filename) {
cat(paste0('\n```{r ', GraphName, ', fig.cap="', AltTag,
'", fig.height=5} \n'), file = ThisFile,
append = TRUE)
}
GraphHeadSq =
function(GraphName, AltTag, ThisFile = Filename) {
cat(paste0('\n```{r ', GraphName, ', fig.cap="', AltTag,
'", fig.height=7} \n'), file = ThisFile, append = TRUE)
}
GraphHeadWide = function(GraphName, AltTag, ThisFile = Filename) {
cat(paste0('\n```{r ', GraphName, ', fig.cap="', AltTag,
'", fig.height=3.5} \n'), file = ThisFile,
append = TRUE)
}
# to avoid errors for missing folders
if (Graphs || Latex) {
if (Folder != "." && !file.exists(Folder)) dir.create(Folder)
}
# make sure there is a filename to write the markdown to.
if (is.null(Filename)) {
Filename = paste0(.simpleCap(ResponseName), "-UniDesc.Rmd")
}
# Start writing mark down here.
if (is.null(Title)) {
Title = paste0('Univariate analysis for ', .simpleCap(ResponseName))
}
cat('#', Title, '
#### Prepared by', getOption("BrailleR.Author"),
' \n\n', file = Filename)
cat(paste0(
'```{r setup, purl=FALSE, include=FALSE}
library(BrailleR)
opts_chunk$set(dev=c("png", "pdf", "postscript", "svg"))
opts_chunk$set(comment="", echo=FALSE, fig.path="',
Folder, '/', .simpleCap(ResponseName),
'-", fig.width=7)
```
<!--- IMPORTANT NOTE: This Rmd file does not yet import the data it uses.
You will need to add a data import command of some description into the next R chunk to use the file as a stand alone file. --->
```{r importData}
```\n\n'), file = Filename, append = TRUE)
if (Basic) {
cat(paste0(
'## Basic summary measures
```{r BasicSummaries}
',
ResponseName,
'.count = length(',
ResponseName,
')
',
ResponseName,
'.unique = length(unique(',
ResponseName,
'))
',
ResponseName,
'.Nobs = sum(!is.na(',
ResponseName,
'))
',
ResponseName,
'.Nmiss = sum(is.na(',
ResponseName,
'))
',
ResponseName,
'.mean = mean(',
ResponseName,
', na.rm = TRUE)
',
ResponseName,
'.tmean5 = mean(',
ResponseName,
', trim =0.025, na.rm = TRUE)
',
ResponseName,
'.tmean10 = mean(',
ResponseName,
', trim =0.05, na.rm = TRUE)
',
ResponseName,
'.IQR = IQR(',
ResponseName,
', na.rm = TRUE)
',
ResponseName,
'.sd = sd(',
ResponseName,
', na.rm = TRUE)
',
ResponseName,
'.var = var(',
ResponseName,
', na.rm = TRUE)
',
ResponseName,
'.skew = moments::skewness(',
ResponseName,
', na.rm = TRUE)
',
ResponseName,
'.kurt = moments::kurtosis(',
ResponseName,
', na.rm = TRUE)
```
### Counts
`r ',
ResponseName,
'.count` values in all, made up of
`r ',
ResponseName,
'.unique` unique values,
`r ',
ResponseName,
'.Nobs` observed, and
`r ',
ResponseName,
'.Nmiss` missing values. \n\n
### Measures of location
Data | all | 5% trimmed | 10% trimmed
----- | ------ | ----- | ------
Mean | `r ',
ResponseName,
'.mean` | `r ',
ResponseName,
'.tmean5` | `r ',
ResponseName,
'.tmean10`
### Quantiles
```{r Quantiles1}
Quantiles=quantile(',
ResponseName,
', na.rm=TRUE)
QList=c("Minimum", "Lower Quartile", "Median", "Upper Quartile", "Maximum")
Results=data.frame(Quantile=QList, Value=Quantiles[1:5])
```
```{r QuantilesPrint, eval=FALSE}
Results
```
```{r QuantilesKable, results="asis", purl=FALSE}
kable(Results, digits=4)
```
### Measures of spread
Measure | IQR | Standard deviation | Variance
-------- | ------ | -------- | ------
Value | `r ',
ResponseName,
'.IQR` | `r ',
ResponseName,
'.sd` | `r ',
ResponseName,
'.var` \n\n'), file = Filename, append = TRUE)
if (!Tests) {
cat(paste0(
'### Other moments
Moment | Skewness | Kurtosis
-------- | ------ | ------
Value | `r ',
ResponseName, '.skew` | `r ', ResponseName, '.kurt` \n\n'),
file = Filename, append = TRUE)
}
}
if (Graphs) {
cat("\n## Basic univariate graphs \n### Histogram \n",
file = Filename, append = TRUE)
GraphHead("Hist", "The histogram")
cat(paste0(VIOpenText, 'hist(', ResponseName, ', xlab="',
ResponseName, '", main="Histogram of ',
.simpleCap(ResponseName), '")', VICloseText),
file = Filename, append = TRUE)
CloseChunk()
cat("\n### Boxplot \n", file = Filename, append = TRUE)
GraphHeadWide("Boxplot", "The boxplot")
cat(paste0(VIOpenText, 'boxplot(', ResponseName,
', horizontal=TRUE, main = "Boxplot of ',
.simpleCap(ResponseName), '")', VICloseText),
file = Filename, append = TRUE)
CloseChunk()
#cat("\n### Density plot \n", file=Filename, append=TRUE)
#GraphHead("Density")
#cat(paste0('density(', ResponseName, ', na.rm=TRUE, main = "Density plot for ', .simpleCap(ResponseName), '")'), file=Filename, a#ppend=TRUE)
#CloseChunk()
#MyDensity=plot(density(x, xlab=ResponseName)
#cat(paste0("The title put on this density plot was: Density plot of",ResponseName,"\n"))
#cat(paste0("The x-axis for this density plot was given the label:",ResponseName,"\n"))
#VI(MyDensity)
} # end of basic graphs section
if (Normality) {
cat(paste0(
'\n## Assessing normality
### Formal tests for normality
```{r NormalityTests}
library(nortest)
Results = matrix(0, nrow=6, ncol=2)
dimnames(Results) = list(c("Shapiro-Wilk", "Anderson-Darling", "Cramer-von Mises",
"Lilliefors (Kolmogorov-Smirnov)", "Pearson chi-square", "Shapiro-Francia"), c("Statistic", "P Value"))
SW =shapiro.test(',
ResponseName,
')
Results[1,] = c(SW$statistic, SW$p.value)
AD = ad.test(',
ResponseName,
')
Results[2,] = c(AD$statistic, AD$p.value)
CV = cvm.test(',
ResponseName,
')
Results[3,] = c(CV$statistic, CV$p.value)
LI = lillie.test(',
ResponseName,
')
Results[4,] = c(LI$statistic, LI$p.value)
PE = pearson.test(',
ResponseName,
')
Results[5,] = c(PE$statistic, PE$p.value)
SF = sf.test(',
ResponseName,
')
Results[6,] = c(SF$statistic, SF$p.value)
```
```{r NormalityTestsPrint, eval=FALSE}
Results
```
```{r NormalityTestsKable, results="asis", purl=FALSE}
kable(Results, digits=c(4,',
PValDigits, '))
``` \n'), file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r NormalityTestsTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, "/", ResponseName,
'-Normality.tex"
TabCapt= "Tests for normality: Variable is ',
ResponseName,
'."
print(xtable(Results, caption=TabCapt, label=\"',
ResponseName,
'Normality", digits=4, align="lrr"), file=ThisTexFile)
``` \n'),
file = Filename, append = TRUE)
}
} # end of normality test statistics section
if (Graphs) {
cat("\n### Normality plot \n", file = Filename, append = TRUE)
GraphHeadSq("NormPlot", "The normality plot")
cat(paste0('qqnorm(', ResponseName, ', main = "Normality Plot for ',
.simpleCap(ResponseName), '")\nqqline(', ResponseName, ')'),
file = Filename, append = TRUE)
CloseChunk()
} # end of normality plot section
if (Tests) {
cat(paste0(
'\n## Formal tests of moments
```{r MomentsTests}
library(moments)
Results = matrix(0, nrow=2, ncol=3)
dimnames(Results)= list(c( "D\'Agostino skewness", "Anscombe-Glynn kurtosis"),
c("Statistic","Z", "P Value"))
AG = moments::agostino.test(',
ResponseName, ')
AN = moments::anscombe.test(', ResponseName,
')
Results[1,] = c(AG$statistic, AG$p.value)
Results[2,] = c(AN$statistic, AN$p.value)
```
```{r MomentsTestsPrint, eval=FALSE}
Results
```
```{r MomentsTests2, results="asis", purl=FALSE}
kable(Results, digits=c(4,3,',
PValDigits, '))
``` \n\n'), file = Filename, append = TRUE)
if (Latex) {
cat(paste0(
'```{r MomentsTestsTex, purl=FALSE}
library(xtable)
ThisTexFile = "',
Folder, "/", ResponseName,
'-Moments.tex"
TabCapt= "Tests on moments: Variable is',
ResponseName,
'"
print(xtable(Results, caption=TabCapt, label=\"',
ResponseName,
'Moments", digits=4, align="lrrr"), file=ThisTexFile)
``` \n\n'),
file = Filename, append = TRUE)
}
} # end of formal tests of normality via moments section
if (Process) {
# finish writing markdown and process the written file into html and an R script
knit2html(Filename, quiet = TRUE,
meta = list(css = FindCSSFile(getOption("BrailleR.Style"))))
file.remove(sub(".Rmd", ".md", Filename))
purl(Filename, quiet = TRUE)
if (View) browseURL(sub(".Rmd", ".html", Filename))
} # end of processing chunk
} # end of UniDesc function definition
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/UniDesc.R
|
# NB xlab() and ylab() are functions in the ggplot2 package;
# the original BrailleR implementation was inconsistent with ggplot2 so the function names were chantged to camel case.
Main = XLab = YLab = function(graph, label=NULL){
arg = as.character(match.call()[[1]])
Obj = tolower(as.character(match.call()[["graph"]]))
if(any(class(graph)=="Augmented")){
if(is.null(label)){
Out = .GetGraphText(graph, arg)
return(Out)
} else {
Out = .UpdateGraph(graph, label, arg)
assign(Obj, Out, parent.frame())
return(invisible(Out))
}
}
}
update.scatterplot = update.tsplot = update.fittedlineplot = UpdateGraph = function(object, ...){
MC <- match.call(expand.dots = TRUE)
ParSet = (as.list(MC))[-c(1,2)]
Obj = as.character(match.call()[["object"]])
Out = object
# now sift ExtraArgs from ParSet and update them
# now sift pars from ParSet and update them
assign(Obj, Out, parent.frame())
return(invisible(Out))
}
.UpdateGraph = function(graph, label, arg){
graph$"ExtraArgs"[[arg]] = label
if(any(class(graph)=="ggplot")){
arg = .ggplotLabelNames[arg]
graph$labels[[arg]] = label
}
print(graph) # is actually plot() except for histograms
return(invisible(graph))
}
.GetGraphText = function(graph, arg){
return(invisible(graph$"ExtraArgs"[[arg]]))
}
.ggplotLabelNames = c(main="title", sub="subtitle", xlab="x", ylab="y")
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/UpdateGraph.R
|
UseTemplateList = function(newfile, fileList, find=NULL, replace=NULL){
for(Template in fileList){
cat(UseTemplate(Template, find=find, replace=replace), file=newfile, append=TRUE)
}
return(invisible(TRUE))
}
UseTemplate = function(file, find=NULL, replace=NULL){
TXT = readLines(system.file(paste0("Templates/", file), package="BrailleR"))
if(!is.null(replace)){
for(i in 1:length(replace)){
TXT = gsub(find[i], replace[i], TXT)
}
}
return(paste0(TXT, collapse="\n"))
}
.UseTemplate = function(templateFile, NewFile=NULL, Changes=list()){
TXT = readLines(system.file(paste0("Templates/", templateFile), package="BrailleR"))
OutText = whisker.render(template=TXT, data=Changes)
if(!is.null(NewFile)){
cat(OutText, file=NewFile)
.NewFile(NewFile)
}
return(OutText)
}
.ChooseTemplate = function(){
if (interactive()) {
Templates = read.csv(system.file("Templates/templates.csv", package="BrailleR"))
Types = as.character(unique(Templates$Type))
UserPrefType = menu(Types,
title = "Which type of template do you want?")
Subset = Templates[Templates$Type == Types[UserPrefType], ]
UserPrefFile = menu(Subset$Template,
title = "Which template do you want?")
file = Subset$Template[UserPrefFile]
message(paste("The", file, "uses the following terms that must be replaced:", Subset$Changes[UserPrefFile], "\nIt will ", Subset$Description[UserPrefFile]))
} else {
.InteractiveOnly()
file=NULL
}
return(file)
}
.BuildRmdFile = function(TemplateList = c("simpleYAMLHeader.Rmd", "StandardSetupChunk.Rmd", "GetLibs.Rmd", "GetData.Rmd"),
Changes = list(), Outfile = "test.Rmd"){
for(Template in TemplateList){
cat(.UseTemplate(Template, Changes=Changes), "\n\n\n", file=Outfile, append=TRUE)
}
.NewFile(Outfile)
message("N.B. it will not be processed untill all {{.}} elements have been replaced with meaningful text.")
return(invisible(TRUE))
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/UseTemplate.R
|
### This file is for internal functions used by VI.ggplot
### These functions access the objects created by ggplot and ggplot_build,
### and may be sensitive to changes in those structure in later ggplot versions.
## All of these functions take as parameters:
## x = the object created by ggplot
## xbuild = the object resulting from ggplot_build(x)
# Some also take a panel or layer index
## Annotations
.getGGTitle = function(x, xbuild) {
if (is.null(x$labels$title)) {
text = NULL
} else {
text = x$labels$title
}
return(invisible(text))
}
.getGGSubtitle = function(x, xbuild) {
if (is.null(x$labels$subtitle)) {
text = NULL
} else {
text = x$labels$subtitle
}
return(invisible(text))
}
.getGGCaption = function(x, xbuild) {
if (is.null(x$labels$caption)) {
text = NULL
} else {
text = x$labels$caption
}
return(invisible(text))
}
.getGGAxisLab = function(x, xbuild, axis) {
if (!.isGGCoordFlipped(x)) {
# Make sure it has axis ticks for it to have a axis
if (is.null(.getGGTicks(x, xbuild, axis = axis)))
return(NULL)
else
return(x$labels[[axis]])
} else {
# Return the opposite of the axis because the coord are flipped
if (axis == 'y') {
return(x$labels$x)
} else {
return(x$labels$y)
}
}
}
.getGGTicks = function(x, xbuild, layer, axis) {
if (.getGGCoord(x, xbuild) == "CoordPolar") {
if (.isGGAxisTheta(x,axis)) {
labs = xbuild$layout$panel_params[[1]]$theta.labels
} else {
labs = xbuild$layout$panel_params[[1]]$r.labels
}
} else {
labs = xbuild$layout$panel_params[[1]][[axis]]$get_labels()
}
if (all(labs[!is.na(labs)] != '')) {
return(labs[!is.na(labs)])
} else {
return(NULL)
}
}
# Guides
.getGGGuideLabels = function(x, xbuild) {
labels = x$labels
# Note: checking against char string "NA" is correct - label is set that way.
labels = labels[which(names(labels) %in%
c("colour", "fill", "size", "shape", "alpha", "radius", "linetype") & labels != "NA")]
return(labels)
}
.getGGGuides = function(x, xbuild) {
return(xbuild$plot$guides)
}
# Coordinates
.getGGCoord = function(x, xbuild) {
coords = class(x$coordinates)
if (sum("CoordFlip" %in% coords) > 0) return("CoordFlip")
if (sum("CoordPolar" %in% coords) > 0) return("CoordPolar")
if (sum("CoordCartesian" %in% coords) > 0) return("CoordCartesian")
return('unknown')
}
#Bar Orientation
# It is done by looking at the the flipped_aes in the build object
.findBarOrientation = function(x, xbuild, layeri) {
layer = xbuild$data[[layeri]]
#Vertical bars
if (sum(layer$flipped_aes == T) == 0) {
return("vertical")
#Horizontal bars
} else if (sum(layer$flipped_aes == T) == length(layer$count)) {
return("horizontal")
} else {
return("(error with orientation)")
}
}
#Get number of bars in a geom_bar
.getNumOfBars = function(data, flipped_aes) {
#Vertical bars
if (flipped_aes == "vertical") {
min = data$xmin
max = data$xmax
#Horizontal bars
} else {
min = data$ymin
max = data$ymax
}
widths = vector()
for (i in 1:length(min)) {
widths[length(widths)+1] = paste(toString(min[i]), " to ", toString(max[i]))
}
length(unique(widths))
}
## Scales
.getGGScaleFree = function(x, xbuild) {
free = x$facet$params$free
if (is.null(free))
return(FALSE)
else
return (free$x | free$y)
}
.getGGScale = function(x, xbuild, aes) {
scalelist = xbuild$plot$scales$scales
scale = which(sapply(scalelist, function(x) aes %in% x$aesthetics))
if (any(scale))
return(scalelist[[scale]])
else
return(NULL)
}
.getGGTransInverse = function(x, xbuild, var) {
scalelist = x$scales$scales
scale = which(sapply(scalelist, function(x) var %in% x$aesthetics))
if (is.null(scale) || is.null(scale$trans))
return(NULL)
else
return(scale$trans$inverse)
}
# Small helper function for .getGGPanelScale
.findScale = function(x, var, panel) {
panelIndex = min(panel, length(x))
var %in% x[[panelIndex]]$aesthetics
}
.getGGPanelScale = function(x, xbuild, var, panel) {
## Need to find the scale that matches the var we're translating
## Depending on scalefree and layout, we might have separate scales
## for each panel or just one
if (packageVersion("ggplot2") < "3.0.0") {
scales = xbuild$layout$panel_scales
} else {
scales = list(xbuild$layout$panel_scales_x,
xbuild$layout$panel_scales_y)
}
findscale = which(sapply(scales, .findScale, var, panel))
if (length(findscale) == 1) {
panelIndex = min(panel, length(scales[[findscale]]))
return(scales[[findscale]][[panelIndex]])
} else {
## Something went wrong -- no matching scale, or more than one
return(NULL)
}
}
## Facets
# Getting facet row and col names from a different place than the
# rest of the panel info. Does it matter?
.getGGFacetRows = function(x, xbuild) {
if (length(x$facet$params$rows) > 0)
return(names(x$facet$params$rows))
else
return(NULL)
}
.getGGFacetCols = function(x, xbuild) {
if (length(x$facet$params$cols) > 0)
return(names(x$facet$params$cols))
else if (length(x$facet$params$facets) > 0) # If nothing on left side of tilde in facet formula
return(names(x$facet$params$facets)) # then it's stored like this (??)
else
return(NULL)
}
# This returns a data frame with fields PANEL, ROW, COL, plus one column
# for each faceted variable, plus SCALE_X and SCALE_Y
# e.g. for facets=cut~color the data frame contains:
# PANEL, ROW, COL, cut, color, SCALE_X, SCALE_Y
# The name of this item is panel_layout in ggplot 2.2.1 but looks like
# it's going to be just layout in the next ggplot version
.getGGFacetLayout = function(x, xbuild) {
if ("panel_layout" %in% names(xbuild$layout))
return(xbuild$layout$panel_layout)
else
return(xbuild$layout$layout)
}
## Layers
.getGGLayerCount = function(x, xbuild) {
count=length(xbuild$plot$layers)
}
.getGGLayerType = function(x, xbuild, layer) {
plotClass = class(xbuild$plot$layers[[layer]]$geom)[1]
}
# Report on non-default aesthetics set on this layer
.getGGLayerAes = function(x, xbuild, layer) {
layeraes = list()
params = xbuild$plot$layers[[layer]]$aes_params
params = params[which(!(names(params) %in% c("x", "y")))] # Exclude x, y
values = .convertAes(as.data.frame(params, stringsAsFactors=FALSE))
for (i in seq_along(params))
layeraes[[i]] = list(aes=names(params)[i], mapping=values[,i])
return(layeraes)
}
# Find those aesthetics that are varying within this layer
# (e.g not all points in a scatterplot have the same colour)
.findVaryingAesthetics = function(x, xbuild, layer) {
aeslist = c("colour", "fill", "linetype", "alpha", "size", "weight", "shape")
data = xbuild$data[[layer]]
names = names(data)
data = data[names[names %in% aeslist]]
data = data[sapply(data, function(col) { length(unique(col)) > 1 })]
return(names(data))
}
# Layer position
.getGGLayerPosition = function(x, xbuild, layer) {
pos = switch (class(x$layers[[layer]]$position)[1],
PositionDodge = "dodge",
PositionFill = "fill",
PositionIdentity = "identity",
PositionJitter = "jitter",
PositionJitterdodge = "jitterdodge",
PositionNudge = "nudge",
PositionStack = "stack",
class(x$layers[[layer]]$position)[1]
)
return(pos)
}
# Plot data
# Layer-specific mapping overrides the higher level one
# Mapping is an expression to be evaluated in the x$data environment
# Will return null if there is no mapping (e.g. for y with stat_bin)
.getGGMapping = function(x, xbuild, layer, aes) {
m = xbuild$plot$layers[[layer]]$mapping
if (!is.null(m) & !is.null(m[[aes]]))
return(m[[aes]])
m=xbuild$plot$layers[[layer]]$aes_params[[aes]]
if (!is.null(m))
return(m)
if (xbuild$plot$layers[[layer]]$inherit.aes)
return(xbuild$plot$mapping[[aes]])
else
return(NULL)
}
.getGGPlotData = function(x, xbuild, layer, panel) {
# This returns a data frame -- useable by MakeAccessible, but will need to change
# if it's going to be used by VI via the whisker template
fulldata = xbuild$data[[layer]]
return(fulldata[fulldata$PANEL == panel,])
}
# Get the original data values for variable var in the given layer
# NOT CURRENTLY IN USE
# Dangerous since the original data may have changed or no longer be present in the env
# Also note that the returned data won't necessarily align to the plot data -- e.g. if
# facets are present or a stat other than identity is in play
.getGGRawValues = function(x, xbuild, layer, var) {
map = .getGGMapping(x, xbuild, layer, var)
if (inherits(x$layers[[layer]]$data, "waiver"))
return(eval(map,x$data))
else
return(eval(map,x$layers[[layer]]$data))
}
# Smooth layer details
.getGGSmoothParams = function(x, xbuild, layer) {
return(xbuild$plot$layers[[layer]]$stat_params)
}
.getGGSmoothMethod = function(x, xbuild, layer) {
Out = xbuild$plot$layers[[layer]]$stat_params$method
if(is.null(Out)) Out = c("lowess")
return(Out)
}
.getGGSmoothSEflag = function(x, xbuild, layer) {
return(xbuild$plot$layers[[layer]]$stat_params$se)
}
.getGGSmoothLevel = function(x, xbuild, layer) {
Out = xbuild$plot$layers[[layer]]$stat_params$level
if(is.null(Out)) Out = 0.95
return(Out)
}
.isGuideHidden = function(x, xbuild, aes) {
# Need to look through all layers to figure out whether this aesthetic is involved, and
# if so, has show.legend been specified?
someLayerShows = FALSE
for (layer in xbuild$plot$layers) {
mapped = aes %in% names(layer$mapping) ||
(layer$inherit.aes && aes %in% names(xbuild$plot$mapping))
if (mapped && (is.na(layer$show.legend) || layer$show.legend)) {
someLayerShows = TRUE
}
}
if (!someLayerShows)
return(TRUE)
scale = .getGGScale(x, xbuild, aes)
if (!is.null(scale) && !is.null(scale$guide) && scale$guide %in% c("none",FALSE))
return(TRUE)
guides = xbuild$plot$guides
if (!is.null(guides) && !is.null(guides[[aes]]) && guides[[aes]] %in% c("none",FALSE))
return(TRUE)
legend.position = xbuild$plot$theme$legend.position
if (!is.null(legend.position) && legend.position == "none")
return(TRUE)
return(FALSE)
}
#Helper list for finding whether words start with vowels to give them an/a accordingly
.giveAnOrA =function(wordChosen){
vowels = c("a", "e", "i", "o", "u")
AnA = .ifelse(is.element(substr(wordChosen, 1,1), vowels), "an", "a")
return(AnA)
}
#Get the area which is filled in by the ymin and ymax found in the layer.
#Useful for geomRibbon and geomSmooth
.getGGShadedArea = function(x, xbuild, layer, useX = TRUE) {
data = xbuild$data[[layer]]
#Width of the shaded area
if (useX) {
width = data$ymax - data$ymin
axis_values = sort(data$x)
} else {
width = data$xmax - data$xmin
axis_values = sort(data$y)
}
#Get the length of each shaded area
#I believe they might be constant
distances = rep(0, length(axis_values))
for (i in 1:(length(axis_values)-1)) {
distances[i] = axis_values[i+1]-axis_values[i]
}
#Length of x and y axis
xaxis = xbuild$layout$panel_scales_x[[1]]$range$range
yaxis = xbuild$layout$panel_scales_y[[1]]$range$range
#Calculate area approximations
shadedArea = sum(abs(distances) * abs(width))
totalArea = (xaxis[2] - xaxis[1]) * (yaxis[2] - yaxis[1])
#Get percentage
areaProportion = shadedArea / totalArea
areaPercentageStr = (areaProportion*100) |>
signif(2) |>
toString() |>
paste("%", sep="")
return(areaPercentageStr)
}
#Get the number of points that can be individually seen
#This will help for users to tell how much overlap there really is
.getGGVisiblePoints = function(cleandata) {
# This model is hardcoded in to keep it simple.
# It was achieved by getting a whole bunch of data by manually plotting
# points and working out how many distinct points will fit in a fig dimmensions
# for a given point size.
# The model was run on this data was "number ~ figDim * log(size)- 1"
getNumber = function(figDim, size) 18.8451775594414 * figDim + -0.670862804568509 * log(size) + -5.94685845490627 * log(size) * figDim
size = dev.size()
axes = c('x', 'y')
#Get grid for points to be put into
roundedPoints = list()
for (axis in axes) {
data = cleandata[axis]
range = max(data) - min(data)
avgPointSize = mean(cleandata$size)
figDim = size[which(axes == axis)]
#print(avgPointSize)
numberOfPoints = getNumber(figDim, avgPointSize)
#print(numberOfPoints)
cellWidth = range / numberOfPoints
roundedPoints[axis] = cellWidth * round(data/cellWidth)
}
#Return proportion of indiviual points
numberOfVisiblePoints = data.frame(roundedPoints) |> distinct() |> nrow()
numberOfPoints = length(roundedPoints$x)
(numberOfVisiblePoints / numberOfPoints)
}
#####################################################################
##-----------------Coordinate system helper functions--------------##
#####################################################################
##########################
## Flipped coordinates
##########################
## Gets whether the plot is CoordFlip or not
.isGGCoordFlipped = function(x) {
return(.getGGCoord(x) == "CoordFlip")
}
##########################
## Polar coordinates
##########################
## Tests if the plot is GGCoordFlipped
.isGGCoordPolar = function(x) {
return(.getGGCoord(x) == "CoordPolar")
}
## Tests if the given axis is the theta axis
.isGGAxisTheta = function(x, axis) {
x$coordinates$theta == axis
}
|
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/VIInternals.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.