content
stringlengths
0
14.9M
filename
stringlengths
44
136
### Internal functions for base R plots .getGraphName = function(graph, titlePreamble = "With the title:", noTitleMessage="With no title") { if (length(graph$main) > 0) { if (nchar(gsub(" ", "",graph$main, fixed=T)) != 0) { paste(titlePreamble,graph$main) } else { noTitleMessage } } else if (nchar(graph$ExtraArgs$main) > 0) { paste(titlePreamble,graph$ExtraArgs$main) } else { noTitleMessage } } ###VI methods VI = function(x, Describe=FALSE, ...) { UseMethod("VI") } print.VI = function(x, ...){ cat(x, sep="\n") return(invisible(x)) } VI.default = function(x, Describe=FALSE, ...) { .NoVIMethod() print(x) } VI.boxplot = function(x, Describe=FALSE, ...) { x=Augment(x) cat(paste0( 'This graph has ', x$Boxplots, ' printed ', x$VertHorz, '\n', .getGraphName(x), '\n', .ifelse(length(x$ExtraArgs$xlab) > 0, InQuotes(x$ExtraArgs$xlab), 'No label'), ' appears on the x-axis.\n', .ifelse(length(x$ExtraArgs$ylab) > 0, paste0('"', x$ExtraArgs$ylab, '"'), 'No label'), ' appears on the y-axis.\n')) if (x$horizontal) { cat("Tick marks for the x-axis are at:", .GetAxisTicks(x$par$xaxp), "\n") } else { cat("Tick marks for the y-axis are at:", .GetAxisTicks(x$par$yaxp), "\n") } for (i in 1:x$NBox) { cat(x$VarGroupUpp, x$names[i], 'has', x$n[i], 'values.\n') if (any(x$group == i)) { cat('An outlier is marked at:', x$out[which(x$group == i)], '\n') } else { cat('There are no outliers marked for this', x$VarGroup, '\n') } cat('The whiskers extend to', x$stats[1, i], 'and', x$stats[5, i], 'from the ends of the box, \nwhich are at', x$stats[2, i], 'and', x$stats[4, i], '\n') BoxLength = x$stats[4, i] - x$stats[2, i] cat('The median,', x$stats[3, i], 'is', round(100 * (x$stats[3, i] - x$stats[2, i]) / BoxLength, 0), '% from the', .ifelse(x$horizontal, 'left', 'lower'), 'end of the box to the', .ifelse(x$horizontal, 'right', 'upper'), 'end.\n') cat('The', .ifelse(x$horizontal, 'right', 'upper'), 'whisker is', round((x$stats[5, i] - x$stats[4, i]) / (x$stats[2, i] - x$stats[1, i]), 2), 'times the length of the', .ifelse(x$horizontal, 'left', 'lower'), 'whisker.\n') } cat('\n') } VI.data.frame = function(x, Describe=FALSE, ...) { ThisDF = x cat("\nThe summary of each variable is\n") with(ThisDF, { for (i in names(ThisDF)) { cat(paste(i, ": ", sep = "")) Wanted = summary(get(i)) cat(paste(names(Wanted), Wanted, " ")) cat("\n") } }) # closure of the with command cat("\n") } VI.dotplot = function(x, Describe=FALSE, ...) { MinVal = min(unlist(x$vals)) MaxVal = max(unlist(x$vals)) Bins = getOption("BrailleR.DotplotBins") Cuts = seq(MinVal, MaxVal, (MaxVal - MinVal) / Bins) # now do the description bit cat(paste0('This graph has ', x$dotplots, ' printed ', x$VertHorz, '\n', .getGraphName(x), '\n')) if (!is.null(x$ExtraArgs$dlab) | !is.null(x$ExtraArgs$glab)) { .OldCodeWarning(Old="dlab or glab arguments", New = "xlab and ylab ") } else { cat(paste0(ifelse(length(x$ExtraArgs$xlab) > 0, InQuotes(x$ExtraArgs$xlab), 'No label'), ' appears on the x-axis.\n', .ifelse(length(x$ExtraArgs$ylab) > 0, paste0('"', x$ExtraArgs$ylab, '"'), 'No label'), ' appears on the y-axis.\n')) } if (x$vertical) { cat("Tick marks for the y-axis are at:", .GetAxisTicks(x$par$yaxp), "\n") } else { cat("Tick marks for the x-axis are at:", .GetAxisTicks(x$par$xaxp), "\n") } cat(paste("the data that range from", MinVal, "to", MaxVal, "has been broken into", Bins, "bins.\nThe counts are:\n")) for (i in 1:x$NPlot) { cat(paste0(names(x$vals)[i], ": ")) cat(graphics::hist(x$vals[[i]], breaks = Cuts, plot = FALSE)$counts, "\n") } return(invisible(NULL)) } VI.histogram = function(x, Describe=FALSE, ...) { cat(paste0('This is a histogram, with the title: ', .getGraphName(x, titlePreamble = "with the title:", noTitleMessage = "with no title"), '\n', .ifelse(length(x$ExtraArgs$xlab) > 0, InQuotes(x$ExtraArgs$xlab), InQuotes(x$xname)), ' is marked on the x-axis.\n')) cat("Tick marks for the x-axis are at:", .GetAxisTicks(x$par$xaxp), "\n") cat('There are a total of', sum(x$counts), 'elements for this variable.\n') cat("Tick marks for the y-axis are at:", .GetAxisTicks(x$par$yaxp), "\n") NoBins = length(x$breaks) - 1 if (x$equidist) { cat('It has', NoBins, 'bins with equal widths, starting at', x$breaks[1], 'and ending at', x$breaks[NoBins + 1], '.\n') cat('The mids and counts for the bins are:') cat(paste0("\nmid = ", x$mids, " count = ", x$counts)) } else { cat('The', NoBins, 'bins have unequal bin sizes.\n') cat('The intervals and densities for the bins are:') cat(paste("\nFor the bin from ", x$breaks[1:NoBins], " to ", x$breaks[-1], "the density is ", x$density, sep = "")) } cat("\n") } VI.htest = function (x, Describe=FALSE, digits = getOption("digits"), ...) { cat("\n") cat(strwrap(x$method ), sep = "\n") if (!is.null(x$statistic)) cat(paste("\n", names(x$statistic), "=", format(x$statistic, digits = max(1L, digits - 2L)))) if (!is.null(x$parameter)) cat(paste("\n", names(x$parameter), "=", format(x$parameter, digits = max(1L, digits - 2L)))) if (!is.null(x$p.value)) { fp <- format.pval(x$p.value, digits = max(1L, digits - 3L)) cat(paste("\n", "p-value", if (substr(fp, 1L, 1L) == "<") fp else paste("=", fp))) } if (!is.null(x$conf.int)) { cat("\n\n") cat(format(100 * attr(x$conf.int, "conf.level")), " percent confidence interval:\n", " ", paste(format(x$conf.int[1:2], digits = digits), collapse = " "), sep = "") } cat("\n\n") invisible(x) } VI.list = function(x, Describe=FALSE, ...) { cat("No VI method has yet been written for this type of object so it has been printed for you in its entirety.\n") print(x) } VI.lm = function(x, Describe=FALSE, ...) { ModelName <- match.call(expand.dots = FALSE)$x FolderName = paste0(ModelName, ".Validity") RmdName = paste0(FolderName, ".Rmd") TitleName = paste0( 'Checking validity for the model "', ModelName, '" by way of standardised residuals, leverages, and Cook\'s distances ```{r GetVars, echo=FALSE} Residuals=rstudent(', ModelName, ') Fits= fitted(', ModelName, ') Leverages= hatvalues(', ModelName, ') Cooks= cooks.distance(', ModelName, ') ``` ') Residuals = rstudent(x) UniDesc( Residuals, Title = TitleName, Filename = RmdName, Folder = FolderName, Process = FALSE, VI = TRUE, Latex = FALSE, View = FALSE) cat(paste0( '## Regression diagnostic plots ### Standardised residuals ```{r Fits, fig.cap="Standardised residuals plotted against fitted values"} plot(Fits, Residuals) WhereXY(Fits, Residuals, yDist="normal") ``` ```{r Order, fig.cap="Standardised residuals plotted against order"} plot(Residuals) WhereXY(1:length(Residuals), Residuals, yDist="normal") ``` ```{r Lag1Resids, fig.cap="standardised residuals plotted against lagged residuals"} n = length(Residuals) plot(Residuals[-n], Residuals[-1], ylab= paste("Residuals 2 to", n), xlab=paste("Residuals 1 to",(n-1))) WhereXY(Residuals[-n], Residuals[-1], xDist="normal") ``` The lag 1 autocorrelation of the standardised residuals is `r cor(Residuals[-n], Residuals[-1])`. ### Influence ```{r Leverages, fig.cap="Standardised residuals plotted against leverages"} plot(Leverages, Residuals) WhereXY(Leverages, Residuals, yDist="normal") ``` `r sum(Leverages>2*mean(Leverages))` points have excessive leverage. `r sum(Cooks>1)` points have Cook\'s distances greater than one. ### Outliers and influential observations ```{r ListInfObs} InflObs = data.frame(', ModelName, '$model, Fit=Fits, St.residual=Residuals, Leverage=Leverages, Cooks.distance=Cooks)[abs(Residuals)>2 | Cooks > 1 | Leverages > 2*mean(Leverages) , ] ``` ```{r ListInfObsLatex, purl=FALSE} library(xtable) print(xtable(InflObs, caption="Listing of suspected outliers and influential observations.", label="InflObs', ModelName, '", digits=4), file = "', FolderName, '/Influential.tex") ``` ```{r ListInfObsKabled, results="asis", purl=FALSE} kable(InflObs) ``` \n\n'), file = RmdName, append = TRUE) # stop writing markdown and process the written file into html and an R script knit2html(RmdName, quiet = TRUE, stylesheet = FindCSSFile(getOption("BrailleR.Style"))) file.remove(sub(".Rmd", ".md", RmdName)) purl(RmdName, quiet = TRUE) if (getOption("BrailleR.View")) browseURL(sub(".Rmd", ".html", RmdName)) # do the clean up #rm(list=c("Residuals", "Fits", "Leverages", "Cooks"), envir=.GlobalEnv) return(invisible(TRUE)) } VI.matrix = function(x, Describe=FALSE, ...) { VI(as.data.frame.matrix(x), Describe=Describe, ...) } VI.qcc = function (x, ...) { TypeText = paste("This control chart is a", x$type, "chart.") SubgroupSizesConst = diff(range(x$sizes))==0 PointText = paste("Data for", length(x$statistics), "subgroups of", .ifelse(SubgroupSizesConst, "equal", "varying"), "size are marked.") CenterText = .ifelse(length(x$center)==1, paste0("The center line is marked at ", signif(x$center,4), "."), "There is more than one center line.") CLText = .ifelse(length(x$limits)==2, paste0("The LCL is at ", signif(x$limits[,1], 4), " and the UCL is at ", signif(x$limits[,2],4), "."), "There are more than one set of control limits.") NoBL = length(x$violations$beyond.limits) BLText = paste("There", .ifelse(NoBL==1, "is", "are"), .ifelse(NoBL==0, "no", NoBL), .ifelse(NoBL==1, "point", "points"), "that breach the control limits.") NoVR = length(x$violations$violating.runs) VRText = paste0("There ", .ifelse(NoVR==1, "is", "are"), " ", .ifelse(NoVR==0, "no", NoVR), " violating run", .ifelse(NoVR==1, "", "s"), ".") Out = c(TypeText, PointText, CenterText, CLText, BLText, VRText) class(Out) = "VI" return(Out) } VI.tsplot = function(x, Describe=FALSE, ...) { x }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/VIMethod1_JG.R
VI.aov <- function(x, Describe=FALSE, ...) # Last Edited: 18/02/15 { GroupL <- interaction(x$model[, -1], sep = ":") FNames = attr(x$terms, 'term.labels') for (Factor in FNames) { cat("\nThe p value for", Factor, "is", round(anova(x)[which(FNames == Factor), 5], 4)) } cat("\n\nThe ratios of the group standard deviations to the overall standard deviation \n", "(groups ordered by increasing mean) are:\n", round(tapply(x$residuals, GroupL, sd) / sqrt(sum(x$residuals ^ 2) / x$df.residual), 2)) cat("\n \n") return(invisible(NULL)) } VI.summary.lm <- function(x, Describe=FALSE, ...) { CoeTable <- x$coe # Gives us the table # Check if intercept has been fitted if (row.names(CoeTable)[1] == "(Intercept)") { IsInter = 1 } else { IsInter = 0 } # Determine the significance of each model term SigPValues <- numeric(nrow(CoeTable) - IsInter) for (Term in 1:length(SigPValues)) { if (CoeTable[Term + IsInter, 4] <= 0.01) { SigPValues[Term] = 0.01 } else if (CoeTable[Term + IsInter, 4] <= 0.05) { SigPValues[Term] = 0.05 } else if (CoeTable[Term + IsInter, 4] <= 0.1) { SigPValues[Term] = 0.1 } } # For each significant term, make statement about it. for (SigLevel in c(0.01, 0.05, 0.1)) { SigTerms <- which(SigPValues == SigLevel) if (length(SigTerms) != 0) { cat('The', .ifelse(length(SigTerms) == 1, " term which is ", " terms which are;"), 'significant to ', SigLevel * 100, .ifelse(length(SigTerms) == 1, "% is", "% are"), '\n', sep = "") for (Term in 1:length(SigTerms)) { Index = SigTerms[Term] + IsInter cat(row.names(CoeTable)[Index], 'with an estimate of', CoeTable[Index, 1], 'and P-Value of', CoeTable[Index, 4], '\n') } cat('\n') } } # State which terms are not significant to 10%. NonSigTerms <- which(SigPValues == 0) if (length(NonSigTerms) != 0) { if (length(NonSigTerms) == 1) { cat('The term', row.names(CoeTable)[NonSigTerms + IsInter], 'is not significant to 10%.') } else { NoOfTerms <- length(NonSigTerms) cat('The terms', paste(row.names(CoeTable)[NonSigTerms[1:(NoOfTerms - 1)] + IsInter], collapse = ", "), 'and', row.names(CoeTable)[NonSigTerms[NoOfTerms] + IsInter], 'are not significant to 10%.') } } } VI.TukeyHSD <- function(x, Describe=FALSE, ...) # Last Edited: 25/02/15 { CI <- attr(x, 'conf.level') for (Comparison in 1:length(x)) { CTable = x[[names(x)[Comparison]]] SignPValues = (CTable[, 4] <= (1 - CI)) if (any(SignPValues == TRUE)) { cat("For term ", names(x)[Comparison], " the comparisons which are significant at ", (1 - CI) * 100, "% are:\n", sep = "") for (DRow in 1:length(SignPValues)) { if (SignPValues[DRow] == TRUE) { SComp = strsplit(rownames(CTable)[DRow], "-")[[1]] cat(SComp[1], "and", SComp[2], "with a difference of", round(CTable[DRow, 1], 2), "and P-value of", round(CTable[DRow, 4], 4), "\n") } } } else { cat("For term ", names(x)[Comparison], " there are no comparisons significant at ", (1 - CI) * 100, "%\n", sep = "") } cat("\n") } return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/VIMethod2_TB.R
## Textify performs whisker rendering ## First parameter is a list of objects. ## Second parameter is the name of a template file. ## Each object is rendered using the template of the same name ## found within the template file. Partial templates can also ## be present in the template file and will be used if needed. .VItextify <- function(x, template = system.file("whisker/VIdefault.txt", package = "BrailleR")) { temp <- read.csv(template, header = FALSE, as.is = TRUE) templates <- as.list(gsub("\n", "", temp[, 2])) names(templates) <- temp[, 1] result <- list() for (i in 1:length(x)) { if (is.null(x[[i]])) { result[[i]] <- character(0) } else { render <- whisker::whisker.render(templates[names(x[i])], x[[i]], partials = templates) result[[i]] <- as.vector(strsplit(render, "<br>", fixed = TRUE)[[1]]) } } names(result) <- names(x) return(result) } # This function adds flags to the VIstruct object that are only # required because of the limitations of mustache templating, as well # as implementing the threshold for printing by setting "largecount" flags. # Mustache can't check a field's value, only whether it's present or not. # So flags are either set to true or not included at all .VIpreprocess <- function(x, threshold = 10) { if (is.null(x)) { return(NULL) } # Deal with coords supportedNonCartesian <- c("CoordPolar") if (x$coord %in% supportedNonCartesian) { x$noncartesian <- TRUE } x[[x$coord]] <- TRUE x <- append(x, x$coordInformation) # Add all coord information if (x$npanels == 1) { x$singlepanel <- TRUE } if (x$nlayers == 1) { x$singlelayer <- TRUE } if (length(x$panelrows) == 0) { x$singlerow <- TRUE } if (length(x$panelcols) == 0) { x$singlecol <- TRUE } if (length(x$panelrows) > 0 && length(x$panelcols) > 0) { x$panelgrid <- TRUE } if (length(x$xaxis) == 1) { x$xaxis <- NULL } if (length(x$yaxis) == 1) { x$yaxis <- NULL } # If samescale then axis labels are at top level if (!is.null(x$xaxis$xticklabels)) { x$xaxis$xtickitems <- .listifyVars(list(label = x$xaxis$xticklabels)) } if (!is.null(x$yaxis$yticklabels)) { x$yaxis$ytickitems <- .listifyVars(list(label = x$yaxis$yticklabels)) } for (legendi in 1:length(x$legends)) { if (!is.null(x$legends[[legendi]]$scalelevels)) { x$legends[[legendi]]$scalelevelitems <- .listifyVars(list( level = x$legends[[legendi]]$scalelevels, map = x$legends[[legendi]]$scalemaps )) } } for (paneli in 1:x$npanels) { # Othewise they're within the panels if (!is.null(x$panels[[paneli]]$xticklabels)) { x$panels[[paneli]]$xtickitems <- .listifyVars(list(label = x$panels[[paneli]]$xticklabels)) } if (!is.null(x$panels[[paneli]]$yticklabels)) { x$panels[[paneli]]$ytickitems <- .listifyVars(list(label = x$panels[[paneli]]$yticklabels)) } for (layeri in 1:x$nlayers) { layer <- x$panels[[paneli]]$panellayers[[layeri]] typeflag <- paste0("type", layer$type) layer[[typeflag]] <- TRUE n <- layer$n if (!is.null(n)) { if (n > 1) { layer$s <- TRUE } if (n > threshold) { layer$largecount <- TRUE } else { if (layer$type == "line") { # Lines are special, items are within groups for (i in 1:length(layer$lines)) { layer$lines[[i]]$linenum <- i npoints <- nrow(layer$lines[[i]]$scaledata) layer$lines[[i]]$npoints <- npoints if (npoints > threshold) { layer$lines[[i]]$largecount <- TRUE } else { layer$lines[[i]]$items <- .listifyVars(layer$lines[[i]]$scaledata) } } } else { layer$items <- .listifyVars(layer$scaledata) } } } x$panels[[paneli]]$panellayers[[layeri]] <- layer } } return(x) } # This function will convert vectors into lists for mustache # Takes a named list of vectors, result is a list of lists # Also adds item numbers and separator # e.g. converts list(x=c(1,2),y=c(3,4)) into # list(list(itemnum=1,x=1,y=3,sep=" and "),list(itemnum=2,x=2,y=4,sep="")) # This code isn't efficient, but hopefully we aren't printing a huge number of points .listifyVars <- function(varlist) { itemlist <- list() for (i in seq_along(varlist[[1]])) { # Assumes all varlists are the same length item <- list() for (j in seq_along(varlist)) { item$itemnum <- i var <- varlist[[j]] name <- names(varlist)[j] item[[name]] <- .cleanPrint(var[i]) } len <- length(varlist[[1]]) # Separator, to allow whisker template to create and-separated lists if (i == len) { item[["sep"]] <- "" } else if (i == len - 1) { item[["sep"]] <- " and " } else { item[["sep"]] <- ", " } itemlist[[i]] <- item } return(itemlist) } # For now, limit all values printed to 2 decimal places. Should do something smarter -- what does # ggplot itself do? .cleanPrint <- function(x) { if (is.numeric(x)) { return(round(x, 2)) } else { return(x) } } ### Print function for the object created by VI.ggplot ### Prints the text component of the object print.VIgraph <- function(x, ...) { cat(x$text, sep = "\n") invisible(x) } # Small helper function - builds list excluding items that are null or length 0 .VIlist <- function(...) { l <- list(...) if (length(l[(lapply(l, length) > 0)]) == 0) { return(NULL) } else { return(l[(lapply(l, length) > 0)]) } } sort.VIgraph <- function(x, decreasing = FALSE, by = "x", ...) { if (!by %in% c("x", "y")) { message('Valid by parameters are "x" or "y".') return(x) # Return unchanged } VIgg <- x$VIgg for (i in 1:VIgg$npanels) { for (j in 1:VIgg$nlayers) { if (VIgg$panels[[i]]$panellayers[[j]]$type != "point") { message("Sorting is only supported on plots of type 'point'") return(x) # Return unchanged } df <- VIgg$panel[[i]]$panellayers[[j]]$scaledata VIgg$panels[[i]]$panellayers[[j]] <- within(VIgg$panels[[i]]$panellayers[[j]], { sortorder <- order(if (by == "x") scaledata$x else scaledata$y, decreasing = decreasing) scaledata <- scaledata[sortorder, ] }) } } text <- .VItextify(list(VIgg = .VIpreprocess(VIgg, x$threshold)), x$template)[[1]] VIgraph <- list(VIgg = VIgg, text = text, threshold = x$threshold, template = x$template) class(VIgraph) <- "VIgraph" return(VIgraph) } grep <- function(pattern, x, ...) { ## Dispatch on 'x' rather than 'pattern' !!! UseMethod("grep", x) } grep.default <- function(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE, ...) { base::grep(pattern, x, ignore.case, perl, value, fixed, useBytes, invert) } # Returns the VIgraph object with the text trimmed down to only those rows # containing the specified pattern. Passes extra parameters on to grepl. # Note that only the text portion of the VIgraph is modified; the complete # VIgg structure is still included grep.VIgraph <- function(pattern, x, ...) { x$text <- grep(pattern, x$text, value = TRUE, ...) x } gsub <- function(pattern, replacement, x, ...) { ## Dispatch on 'x' rather than 'pattern' !!! UseMethod("gsub", x) } gsub.default <- function(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE, ...) { base::gsub( pattern, replacement, x, ignore.case, perl, fixed, useBytes ) } gsub.VIgraph <- function(pattern, replacement, x, ...) { x$text <- gsub(pattern, replacement, x$text, ...) x } # threshold specifies how many points, lines, etc will be explicitly listed. # Greater numbers will be summarised (e.g. "is a set of 32 horizontal lines" vs # "is a set of 3 horizontal lines at 5, 7.5, 10") VI.ggplot <- function(x, Describe = FALSE, threshold = 10, template = system.file("whisker/VIdefault.txt", package = "BrailleR"), ...) { VIstruct <- .VIstruct.ggplot(x) text <- .VItextify(list(VIgg = .VIpreprocess(VIstruct, threshold)), template)[[1]] VIgraph <- list(VIgg = VIstruct, text = text, threshold = threshold, template = template) class(VIgraph) <- "VIgraph" return(VIgraph) } # Builds the VIgg structure describing the graph .VIstruct.ggplot <- function(x) { xbuild <- suppressMessages(ggplot_build(x)) # If this is a plot we really can't deal with, say so now supportedClasses <- c("CoordCartesian", "CoordPolar", "CoordFlip") if (!sum(.getGGCoord(x, xbuild) %in% supportedClasses) > 0) { message("VI cannot process this ggplot objects coordinates") return(NULL) } # Deal with quirks of different coordinate system coord <- .getGGCoord(x, xbuild) coordInformation <- list() if (coord == "CoordPolar") { PolarTheta <- x$coordinates$theta PolarR <- x$coordinates$r coordInformation <- .VIlist(PolarTheta = PolarTheta, PolarR = PolarR) } title <- .getGGTitle(x, xbuild) subtitle <- .getGGSubtitle(x, xbuild) caption <- .getGGCaption(x, xbuild) annotations <- .VIlist(title = title, subtitle = subtitle, caption = caption) xlabel <- .getGGAxisLab(x, xbuild, "x") ylabel <- .getGGAxisLab(x, xbuild, "y") if (!.getGGScaleFree(x, xbuild)) { # Can talk about axis ticks at top level unless scale_free samescale <- TRUE xticklabels <- .getGGTicks(x, xbuild, 1, "x") yticklabels <- .getGGTicks(x, xbuild, 1, "y") } else { samescale <- NULL xticklabels <- NULL yticklabels <- NULL } xaxis <- .VIlist(xlabel = xlabel, xticklabels = xticklabels, samescale = samescale) yaxis <- .VIlist(ylabel = ylabel, yticklabels = yticklabels, samescale = samescale) legends <- .buildLegends(x, xbuild) panels <- .buildPanels(x, xbuild) panelrows <- as.list(.getGGFacetRows(x, xbuild)) panelcols <- as.list(.getGGFacetCols(x, xbuild)) layerCount <- .getGGLayerCount(x, xbuild) VIstruct <- .VIlist( annotations = annotations, xaxis = xaxis, yaxis = yaxis, legends = legends, panels = panels, npanels = length(panels), nlayers = layerCount, panelrows = panelrows, panelcols = panelcols, coord = coord, coordInformation = coordInformation, type = "ggplot" ) class(VIstruct) <- "VIstruct" return(VIstruct) } .buildLegends <- function(x, xbuild) { legends <- list() labels <- .getGGGuideLabels(x, xbuild) names <- names(labels) guides <- .getGGGuides(x, xbuild) for (i in seq_along(labels)) { name <- names[i] mapping <- labels[[i]] scale <- .getGGScale(x, xbuild, name) ## From ggplot2 3.0.0 can have x$labels without any corresponding ## xbuild$plot$scales if (is.null(scale)) { break } scalediscrete <- if ("ScaleDiscrete" %in% class(scale)) TRUE hidden <- if (.isGuideHidden(x, xbuild, name)) TRUE maplevels <- data.frame(col1 = scale$map(scale$range$range), stringsAsFactors = FALSE) colnames(maplevels) <- name maplevels <- .convertAes(maplevels) maplevels <- maplevels[[name]] if (!is.null(scalediscrete)) { scalenlevels <- length(scale$range$range) scalelevels <- scale$range$range scalemaps <- maplevels legend <- .VIlist( aes = name, mapping = unname(mapping), scalediscrete = scalediscrete, scalenlevels = scalenlevels, scalelevels = scalelevels, scalemaps = scalemaps, hidden = hidden ) } else { scalefrom <- scale$range$range[1] scaleto <- scale$range$range[2] scalemapfrom <- maplevels[1] scalemapto <- maplevels[2] legend <- .VIlist( aes = name, mapping = unname(mapping), scalediscrete = scalediscrete, scalefrom = scalefrom, scaleto = scaleto, scalemapfrom = scalemapfrom, scalemapto = scalemapto, hidden = hidden ) } legends[[i]] <- legend } return(legends) } .buildPanels <- function(x, xbuild) { f <- .getGGFacetLayout(x, xbuild) panels <- list() names <- colnames(f) panelvars <- names[which(!names %in% c("PANEL", "ROW", "COL", "SCALE_X", "SCALE_Y"))] for (i in seq_along(f$PANEL)) { panel <- list() panel[["panelnum"]] <- as.character(f$PANEL[i]) panel[["row"]] <- f$ROW[i] panel[["col"]] <- f$COL[i] scalefree <- .getGGScaleFree(x, xbuild) panel[["samescale"]] <- if (!scalefree) TRUE # Might want to move this into pre-processing step if (scalefree) { panel[["xticklabels"]] <- .getGGTicks(x, xbuild, 1, "x") panel[["yticklabels"]] <- .getGGTicks(x, xbuild, 1, "y") panel[["xlabel"]] <- .getGGAxisLab(x, xbuild, "x") # Won't actually change over the panels panel[["ylabel"]] <- .getGGAxisLab(x, xbuild, "y") # But we still want to mention them } vars <- list() for (j in seq_along(panelvars)) { vars[[j]] <- list(varname = as.character(panelvars[j]), value = as.character(f[[i, panelvars[j]]])) } panel[["vars"]] <- vars panel[["panellayers"]] <- .buildLayers(x, xbuild, i) panels[[i]] <- panel } return(panels) } .buildLayers <- function(x, xbuild, panel) { layerCount <- .getGGLayerCount(x, xbuild) layers <- list() for (layeri in 1:layerCount) { layeraes <- .getGGLayerAes(x, xbuild, layeri) layer <- .VIlist(layernum = layeri, layeraes = layeraes) layer$data <- .getGGPlotData(x, xbuild, layeri, panel) if (length(layer$data$group) > 0 && max(layer$data$group) > 0) { # ungrouped data have group = -1 ngroups <- length(unique(layer$data$group)) } else { ngroups <- 1 } layerClass <- .getGGLayerType(x, xbuild, layeri) # HLINE if (layerClass == "GeomHline") { layer$type <- "hline" # Discard lines that go outside the bounds of the plot, # as they won't be displayed cleandata <- layer$data[!is.na(layer$data$yintercept), ] layer$n <- nrow(cleandata) map <- .mapDataValues(x, xbuild, list("yintercept"), panel, list(yintercept = cleandata$yintercept)) if (!is.null(map$badTransform)) { layer$badtransform <- TRUE layer$transform <- map$badTransform } layer$scaledata <- map$value # Also report on any aesthetic variables that vary across the layer layer <- .addAesVars(x, xbuild, cleandata, layeri, layer, panel) # POINT } else if (layerClass == "GeomPoint") { layer$type <- "point" # Mark as hidden points that go outside the bounds of the plot, # as they won't be displayed cleandata <- layer$data[!is.na(layer$data$x) & !is.na(layer$data$y), ] layer$n <- nrow(cleandata) map <- .mapDataValues( x, xbuild, list("x", "y"), panel, list(x = cleandata$x, y = cleandata$y) ) if (!is.null(map$badTransform)) { layer$badtransform <- TRUE layer$transform <- map$badTransform } layer$scaledata <- map$value # Get visible points. # Current model is only effective for median sizes less than 18. if (median(cleandata$size) < 18) { layer$visibleproportion <- (.getGGVisiblePoints(cleandata) * 100) |> signif(digits = 2) |> paste0("%") } # Check to see if the shape parameter has been set. if (is.null(cleandata$aes_params[["shape"]])) { # Make sure there is only one shape for all points # We know this is the default from the previous conditional if (length(unique(xbuild$data[[layeri]]$shape)) == 1) { layer$defaultShape <- .convertAes(data.frame(shape = xbuild$data[[layeri]]$shape[1]))$shape[1] } } # Also report on any aesthetic variables that vary across the layer layer <- .addAesVars(x, xbuild, cleandata, layeri, layer, panel) # BAR } else if (layerClass == "GeomBar" | layerClass == "GeomCol") { layer$type <- "bar" # Discard bars that go outside the bounds of the plot, # as they won't be displayed cleandata <- layer$data[!is.na(layer$data$xmin) & !is.na(layer$data$xmax), ] # Recount rows # Whether the bar is vertical or horizontal layer$orientation <- .findBarOrientation(x, xbuild, layeri) # Count how many bars are seen visually this is different # to the number of actual bars as bars may be stacked on top of each other layer$numberOfBars <- .getNumOfBars(cleandata, layer$orientation) layer$n <- nrow(cleandata) # If bar width varies then we should report xmin and xmax instead if (layer$orientation == "vertical") { width <- cleandata$xmax - cleandata$xmin valueList <- list(loc = cleandata$x, min = cleandata$ymin, max = cleandata$ymax) } else { width <- cleandata$ymax - cleandata$ymin valueList <- list(loc = cleandata$y, min = cleandata$xmin, max = cleandata$xmax) } map <- .mapDataValues( x, xbuild, list("loc", "min", "max"), panel, valueList ) if (!is.null(map$badTransform)) { layer$badtransform <- TRUE layer$transform <- map$badTransform } layer$scaledata <- map$value # Print out information of width of bar if they vary if (max(width) - min(width) > .0001) { # allow for small rounding error if (layer$orientation == "vertical") { layer$scaledata <- cbind(layer$scaledata, widthmin = cleandata$xmin, widthmin = cleandata$xmax) } else { layer$scaledata <- cbind(layer$scaledata, widthmin = cleandata$ymin, widthmin = cleandata$ymax) } layer$varyingWidths <- T } else { layer$varyingWidths <- F } # Also report on any aesthetic variables that vary across the layer layer <- .addAesVars(x, xbuild, cleandata, layeri, layer, panel) # LINE } else if (layerClass == "GeomLine") { layer$type <- "line" # Lines are funny - each item in the data is a point # The number of actual lines depends on the group parameter layer$n <- ngroups # Y values of NA or past ylims create broken lines if (any(is.na(layer$data$y))) { layer$broken <- TRUE } # X values of NA or past xlims should just not be reported on # as they won't be displayed but the line will still be continuous cleandata <- layer$data[!is.na(layer$data$x), ] layer <- .addLineAesLabels(x, xbuild, layeri, layer, panel) # Each group is a line which has its own information including its own scaledata layer$lines <- list() for (groupi in unique(cleandata$group)) { line <- list() groupdata <- cleandata[cleandata$group == groupi, ] groupx <- groupdata$x groupy <- groupdata$y map <- .mapDataValues(x, xbuild, list("x", "y"), panel, list(x = groupx, y = groupy)) if (!is.null(map$badTransform)) { layer$badtransform <- TRUE layer$transform <- map$badTransform } # Lines have a separate scaledata for each group line$scaledata <- map$value line <- .addLineAesVars(x, xbuild, line, layeri, groupdata, panel) layer$lines[[length(layer$lines) + 1]] <- line } # BOXPLOT } else if (layerClass == "GeomBoxplot") { ## Could add information about the varying widths layer$type <- "box" cleandata <- layer$data # No need for cleaning since this data is already aggregated layer$n <- nrow(layer$data) # Deal with them either being horizontal or vertical flipped <- sum(cleandata$flipped_aes) == length(cleandata$flipped_aes) if (flipped) { map <- .mapDataValues( x, xbuild, list("loc", "min", "lower", "middle", "upper", "max"), panel, list( loc = cleandata$y, min = cleandata$xmin, lower = cleandata$xlower, middle = cleandata$xmiddle, upper = cleandata$xupper, max = cleandata$xmax ) ) } else { map <- .mapDataValues( x, xbuild, list("loc", "min", "lower", "middle", "upper", "max"), panel, list( loc = cleandata$x, min = cleandata$ymin, lower = cleandata$lower, middle = cleandata$middle, upper = cleandata$upper, max = cleandata$ymax ) ) } layer$flipped <- flipped if (!is.null(map$badTransform)) { layer$badtransform <- TRUE layer$transform <- map$badTransform } layer$scaledata <- map$value nOutliers <- sapply(cleandata$outliers, length) layer$scaledata[["nooutliers"]] <- nOutliers == 0 # Outlier code made nicer with help from josliber on code review # https://codereview.stackexchange.com/questions/281708/calculate-number-of-max-and-min-outliers-from-data-frame/281730#281730 middle <- if (flipped) cleandata$xmiddle else cleandata$middle layer$scaledata[["minoutliers"]] <- mapply(function(x, y) sum(x < y), cleandata$outliers, middle) layer$scaledata[["maxoutliers"]] <- mapply(function(x, y) sum(x > y), cleandata$outliers, middle) # Also report on any aesthetic variables that vary across the layer layer <- .addAesVars(x, xbuild, cleandata, layeri, layer, panel) # SMOOTH } else if (layerClass == "GeomSmooth") { layer$type <- "smooth" layer$method <- .getGGSmoothMethod(x, xbuild, layeri) layer$ci <- .getGGSmoothSEflag(x, xbuild, layeri) # adding confidence level as a percentage deci <- toString(.getGGSmoothLevel(x, xbuild, layeri) * 100) layer$level <- paste(deci, "%", sep = "") if (layer$ci) { layer$shadedarea <- .getGGShadedArea(x, xbuild, layeri) } # RIBBON } else if (layerClass == "GeomRibbon" | layerClass == "GeomArea") { layer$type <- "ribbon" data <- xbuild$data[[layeri]] # Width of the ribbon yMin <- data$ymin yMax <- data$ymax # Length of the ribbon xMin <- data$xmin xMax <- data$xmax # actual data x_data <- data$x y_data <- data$y # Removing the leading and trailing 0 if (layerClass == "GeomArea") { yMin <- yMin[2:(length(yMin) - 1)] yMax <- yMax[2:(length(yMax) - 1)] xMin <- xMin[2:(length(xMin) - 1)] xMax <- xMax[2:(length(xMax) - 1)] x_data <- x_data[2:(length(x_data) - 1)] y_data <- y_data[2:(length(y_data) - 1)] } widthIntervals <- seq(from = 1, to = length(y_data), length.out = 5) # Bound on the x or y axis if (is.null(yMin) && is.null(yMax) && !is.null(xMin) && !is.null(xMax)) { ybounds <- FALSE layer$bound <- "x" } else { ybounds <- TRUE layer$bound <- "y" } # Get the width of the ribbon if (ybounds) { width <- yMax - yMin } else { width <- xMax - xMin } # constant or nonconstant width if (length(unique(width)) != 1) { layer$nonconstantribbonwidth <- T width <- width[widthIntervals] |> signif() } else { width <- width[1] } layer$ribbonwidth <- .listifyVars(list(value = width)) # Centre if (ybounds) { centres <- (yMax + yMin)[widthIntervals] |> lapply(function(.x) signif((.x / 2))) } else { centres <- (xMax + xMin)[widthIntervals] |> lapply(function(.x) signif((.x / 2))) } if (length(unique(centres)) == 1) { # Centre is constant layer$constantcentre <- T centres <- centres[1] } layer$centre <- .listifyVars(list(value = unlist(centres))) # Shaded area if (ybounds) { layer$shadedarea <- .getGGShadedArea(x, xbuild, layeri) } else { layer$shadedarea <- .getGGShadedArea(x, xbuild, layeri, useX = F) } # expand_limits } else if (layerClass == "GeomBlank") { # As only one method uses geom blank at the moment it will be treated like # expand limits layer$type <- "expand_limits" data <- xbuild$data[[layeri]] # Deal with situations of failed transformations. In these cases it wont affect # the grpah so just removing the bound. bounds <- list(x = data$x, y = data$y) |> lapply(function(bounds) { unlist(lapply(bounds, function(bound) { if (!is.null(bound) && !is.na(bound)) { bound } else { NULL } })) }) # Helper function to calculate the increase getIncrease <- function(max, min, dataRange) { if (max < dataRange[2]) max <- dataRange[2] if (min > dataRange[1]) min <- dataRange[1] dataSize <- (dataRange[2] - dataRange[1]) if (dataSize == 0) { increase <- (max - min) / 0.1 # It is divided by zero because if there is no width then the graph will # be very narrow. From my testing it is about 0.1. But the emphasis here # is that any limit will probably make the graph very much larger. } else { increase <- (max - min) / (dataRange[2] - dataRange[1]) } return(increase) } # Get plots max and mins on both axis xRange <- NULL yRange <- NULL # To get the min max of the plot it will go through all layers looking # in any of the potential locations below yLocations <- c("y", "ymin", "ymax", "yintercept") xLocations <- c("x", "xmin", "xmax", "xintercept") for (layerNum in 1:layerCount) { if (layerNum == layeri) break currentLayer <- xbuild$data[[layerNum]] # x min for (loc in xLocations) { if (!is.null(currentLayer[[loc]])) { xRange[1] <- min(min(currentLayer[[loc]]), xRange[1], na.rm = T) } } # x max for (loc in xLocations) { if (!is.null(currentLayer[[loc]])) { xRange[2] <- max(max(currentLayer[[loc]]), xRange[2], na.rm = T) } } # y min for (loc in yLocations) { if (!is.null(currentLayer[[loc]])) { yRange[1] <- min(min(currentLayer[[loc]]), yRange[1], na.rm = T) } } # y max for (loc in yLocations) { if (!is.null(currentLayer[[loc]])) { yRange[2] <- max(max(currentLayer[[loc]]), yRange[2], na.rm = T) } } } dataRange <- list(x = xRange, y = yRange) # Get the increase for each axis axises <- c("x", "y") increase <- list() for (axis in axises) { bound <- bounds[[axis]] if (!is.null(bound) && !is.null(dataRange[[axis]])) { increase[axis] <- getIncrease(max(bound), min(bound), dataRange[[axis]]) } } # Setup ready for moustache template if (!is.null(increase[["x"]]) && increase[["x"]] > 1) { if (increase[["x"]] < 1.01) { # Format really small changes differently layer$xIncrease <- sprintf("%0.1f%%", (increase[["x"]] - 1) * 100) } else { layer$xIncrease <- sprintf("%0.0f%%", (increase[["x"]] - 1) * 100) } } if (!is.null(increase[["y"]]) && increase[["y"]] > 1) { if (increase[["y"]] < 1.01) { layer$yIncrease <- sprintf("%0.1f%%", (increase[["y"]] - 1) * 100) } else { layer$yIncrease <- sprintf("%0.0f%%", (increase[["y"]] - 1) * 100) } } # Unknown } else { layer$type <- "unknown" # Name the unknown type and give it a/an accordingly className <- tolower(gsub("^.*?Geom", "", layerClass)) layer$assign <- className layer$anA <- .giveAnOrA(className) } ## Positioning layerPos <- .getGGLayerPosition(x, xbuild, layeri) if (is.null(layerPos)) { layer$hasPos <- FALSE } else { if (layerPos == "dodge") { layer$position <- "adjacent, as sorted by" } else if (layerPos == "fill") { if (layerClass == "GeomBar") { layer$position <- "stacked and shown as propotions of" layer$hasPos <- TRUE } } else if (layerPos == "identity") { if (layerClass == "GeomBar") { layer$position <- "stacked, as sorted by" layer$hasPos <- TRUE } } else if (layerPos == "stack") { layer$position <- "stacked, as sorted by" layer$hasPos <- TRUE } else if (layerPos == "jitter") { layer$position <- "offset by added random noise, and sorted by" layer$hasPos <- TRUE } else if (layerPos == "jitterdodge") { layer$position <- "offset along the x axis to avoid overlapping points, and sorted by" layer$hasPos <- TRUE } else if (layerPos == "nudge") { if (layerClass == "GeomText") { "adjusted text placement for tidier graph" layer$hasPos <- TRUE } } } # End of Layer Position checks layer$mapping2 <- .getGGGuideLabels(x, xbuild) if (length(layer$mapping2) == 0) { layer$hasPos <- FALSE } layers[[layeri]] <- layer } ## END OF THE LAYER FOR LOOP return(layers) } .mapAesDataValues <- function(x, xbuild, layer, varlist, valuelist) { transformed <- list() for (var in varlist) { value <- valuelist[[var]] scale <- .getGGScale(x, xbuild, var) if (is.null(scale)) { # No scale found next } else if (("ScaleDiscrete" %in% class(scale))) { # Try to map back to levels match <- match(value, scale$palette.cache) transformed[[var]] <- scale$range$range[match] } else { # Continuous scale - We can't currently map these next } } return(transformed) } # Converts positional data values back to their original scales -- converting factor # variables back to their levels, and undoisng transforms .mapDataValues <- function(x, xbuild, varlist, panel, valuelist) { badTransform <- NULL transformed <- list() for (var in varlist) { value <- valuelist[[var]] scale <- .getGGPanelScale(x, xbuild, var, panel) if (is.null(scale)) { # No scale - just return the stored value r <- value } else if (("ScaleDiscrete" %in% class(scale))) { # Try to map back to levels map <- scale$range$range if (is.null(map)) { r <- value } else { mapping <- as.character(map[value]) if (length(mapping) != length(value)) { # Can happen with jittered data r <- value } # Something's gone wrong - bail else { r <- mapping } } } else { # Continuous scale - try to undo any transform if (is.null(scale$trans)) { # No transform r <- value } else if (is.null(scale$trans$inverse)) { badTransform <- scale$trans$name r <- value } else { r <- scale$trans$inverse(value) } } transformed[[var]] <- r } return(list(value = as.data.frame(transformed), badTransform = badTransform)) } # Convert aesthetic values to something more friendly for the user # Takes a dataframe and converts all of its columns if possible # *** ONLY HANDLING LINETYPES AND SHAPES SO FAR - and not defaults 42, 22, ... # Colours defined using roloc and related packages .convertAes <- function(values) { linetypes <- c( "0" = "blank", "1" = "solid", "2" = "dashed", "3" = "dotted", "4" = "dotdash", "5" = "longdash", "6" = "twodash" ) shapes <- c( "open square", "open circle", "open triangle", "plus", "X", "open diamond", "downward triangle", "boxed X", "star", "crossed diamond", "circled plus", "six-pointed star", "boxed plus", "crossed circle", "boxed triangle", "solid square", "solid circle", "solid triangle", "solid diamond", "big solid circle", "small solid circle", "fillable circle", "fillable square", "fillable diamond", "fillable triangle", "fillable downward triangle" ) c <- values for (col in seq_along(values)) { aes <- names(values)[col] if (aes == "linetype") { c[, col] <- ifelse(values[[col]] %in% names(linetypes), linetypes[as.character(values[[col]])], c[, col] ) # If not found just return what we got } else if (aes == "shape") { c[, col] <- ifelse(values[, col] %in% 1:25, shapes[values[, col] + 1], c[, col]) } else if (aes %in% c("colour", "fill")) { c[, col] <- colourName(values[, col], ISCCNBScolours) } } return(c) } .addLineAesVars <- function(x, xbuild, line, layeri, groupdata, panel) { aesvars <- .findVaryingAesthetics(x, xbuild, layeri) linedata <- groupdata[, aesvars, drop = FALSE] nvals <- sapply(linedata, function(x) length(unique(x))) nonconstantAes <- aesvars[nvals > 1] for (aes in seq_along(nonconstantAes)) { line[[paste0(nonconstantAes[aes], "varying")]] <- TRUE } aesvars <- aesvars[nvals == 1] aesvals <- .convertAes(groupdata[1, aesvars, drop = FALSE]) ## Use unconverted aesthetics for reverse lookup of mappings ## groupdata[1,aesvars,drop=FALSE] rather than aesvals[1,,drop=FALSE] aesmap <- .mapAesDataValues( x, xbuild, layeri, aesvars, groupdata[1, aesvars, drop = FALSE] ) line[aesvars] <- aesvals if (length(aesmap) > 0) { names(aesmap) <- paste0(names(aesmap), "map") line[names(aesmap)] <- aesmap } return(line) } .addLineAesLabels <- function(x, xbuild, layeri, layer, panel) { aesvars <- .findVaryingAesthetics(x, xbuild, layeri) aeslabel <- .getGGGuideLabels(x, xbuild)[aesvars] if (length(aeslabel) > 0) { names(aeslabel) <- paste0(names(aeslabel), "label") layer <- append(layer, aeslabel) } return(layer) } .addAesVars <- function(x, xbuild, data, layeri, layer, panel) { # panel is not currently used in this function aesvars <- .findVaryingAesthetics(x, xbuild, layeri) aesvals <- .convertAes(data[aesvars]) aeslabel <- .getGGGuideLabels(x, xbuild)[aesvars] if (length(aeslabel) > 0) { names(aeslabel) <- paste0(names(aeslabel), "label") layer <- append(layer, aeslabel) } aesmap <- .mapAesDataValues(x, xbuild, layeri, aesvars, data[aesvars]) layer$scaledata <- append(layer$scaledata, aesvals) if (length(aesmap) == 0) { layer$scaledata <- cbind(layer$scaledata, aesvals) } else { names(aesmap) <- paste0(names(aesmap), "map") layer$scaledata <- cbind(layer$scaledata, aesvals, aesmap) } return(layer) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/VIMethod3_TH.R
#TODO add support for using an arbitary directory ViewSVG = function(file = "index"){ # Getting links svgHTMLFiles = .GetSVGLinks() # Get data and render whisker template data = list( files = svgHTMLFiles ) htmlTemplate = system.file("whisker/SVG/ViewSVG.html", package = "BrailleR") |> readLines() renderedText = whisker.render(htmlTemplate, data = data) # Write rendered html to file fileName = paste0(file, ".html") writeLines(renderedText, con = fileName) close(file(fileName)) if(interactive()){ browseURL(fileName) } return(invisible(NULL)) } .GetSVGLinks = function() { htmlFiles = list.files(pattern = ".html") svgHTMLFiles = list() for (file in htmlFiles) { # Search file to see if it is a svg html file. # This should always get it right as it is from the template file # It will need to be updated if the template file is updated. searchResult = readLines(file) |> grep('<div class="svg">', x = _, Value = TRUE) if(length(searchResult) >= 1) { svgHTMLFiles[[length(svgHTMLFiles) + 1]] = list(file=file) } } svgHTMLFiles }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/ViewSVG.R
WTF = function() { MainTitle = SubTitle = XAxisLabel = YAxisLabel = NULL if (!is.null(dev.list()) & # there must be an open graphics device length(grid::grid.ls(print = FALSE)$name) == 0) { # if not grid # already, then # convert gridGraphics::grid.echo() } # end open device condition if (length(grid::grid.ls(print = FALSE)$name) == 0) { .NoGraphicsDevice() GridLS = NULL } else { GridLS = grid::grid.ls(print = FALSE, flatten = TRUE) } # Now looking for things using the grobs on device ", dev.cur(), ". #print(GridLS) ## there is a dictionary listing of these in the gridGraphs paper. if (is.null(names(grid.get("graphics-plot-1-points-2")))) { PointSet = na.omit( data.frame( x = unclass(grid.get("graphics-plot-1-points-1")$x), y = unclass(grid.get("graphics-plot-1-points-1")$y), pch = unclass(grid.get("graphics-plot-1-points-1")$pch))) } else { PointSet = na.omit( data.frame( x = unclass(grid.get("graphics-plot-1-points-2")$x), y = unclass(grid.get("graphics-plot-1-points-2")$y), pch = unclass(grid.get("graphics-plot-1-points-2")$pch))) } # col=grid.get("graphics-plot-1-points-1")$col NPoints = nrow(PointSet) UniquePCH = unique(PointSet$pch) NPCH = length(UniquePCH) XAxisLabel = grid.get("graphics-plot-1-xlab-1")$label YAxisLabel = grid.get("graphics-plot-1-ylab-1")$label MainTitle = grid.get("graphics-plot-1-main-1")$label SubTitle = grid.get("graphics-plot-1-sub-1")$label cat('This graph has ') if (is.null(MainTitle)) { cat('no main title; ') } else { cat(paste0('the main title "', MainTitle, '"; ')) } if (is.null(SubTitle)) { cat(' and o subtitle;\n') } else { cat(paste0('the subtitle "', SubTitle, '";\n')) } if (is.null(XAxisLabel)) { cat('No label on the x axis;\n') } else { cat(paste0('"', XAxisLabel, '" as the x axis label;\n')) } if (is.null(YAxisLabel)) { cat('No label on the y axis;\n') } else { cat(paste0('"', YAxisLabel, '" as the y axis label;\n')) } if (NPoints > 0) { cat("There are", NPoints, "points marked on this graph.\n") } else { cat('There are no points marked on the graph.\n') } ## I'd like to say something like "This window is empty" or ## "This window has <b> rectangles." etc. etc. ## I would guess that a window having boxes and lines might be a boxplot, while a window having no lines but rectangles is a histogram. etc. return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WTF.R
.BlankWarning = function() { warning("") return(invisible(NULL)) } .CannotSeeWxPython = function(){ warning("Python cannot see the necessary wx module.You need to get that fixed.") return(invisible(NULL)) } .DeprecatedFunction = function() { warning("This function has been deprecated.") return(invisible(NULL)) } .DownloadAFile = function(){ warning("This command will download a file and save it to your hard drive.") return(invisible(NULL)) } .ExpectingText = function() { warning("A text string was expected. No action taken.") return(invisible(NULL)) } .ExperimentalFunction = function() { warning("This function is purely experimental. Use it at your own risk.") return(invisible(NULL)) } .FileDoesNotExist = function(file=NULL) { warning(.ifelse(is.null(file), "The specified file", file), " does not exist.") return(invisible(NULL)) } .FileExists = function(file) { warning(file, "already exists.") return(invisible(NULL)) } .FolderNotFound = function(folder=NULL) { warning(.ifelse(is.null(folder), "The specified folder", folder), " does not exist.") return(invisible(NULL)) } .InteractiveOnly = function() { warning("This function is meant for use in interactive mode only.") return(invisible(NULL)) } .NeedsPython = function() { warning("This function requires installation of Python 3.0 or above.") return(invisible(NULL)) } .NeedsWX = function() { warning("This function requires an installation of Python and wxPython.") return(invisible(NULL)) } .NoChangeWarning = function(text="The option must be either TRUE or FALSE.") { warning(text, "\nNo change has been made to this setting.") return(invisible(NULL)) } .NoConversion = function() { warning("There was a problem and no conversion was possible.") return(invisible(NULL)) } .NoGraphicsDevice = function(Text="to investigate.") { warning("There is no current graphics device", Text) return(invisible(NULL)) } .NotBaseRWarning = function(text = "") { warning(text, "and is not a base R function.") return(invisible(NULL)) } .OldCodeWarning = function(Old="", New="") { warning("Use of ", Old, "is not advised. Use", New, "instead.") return(invisible(NULL)) } .OverWriteNeeded = function(file=NULL) { warning("No action has been taken. Use `Overwrite=TRUE` if you want to replace it.") return(invisible(NULL)) } .PkgNotFound = function(Pkg=NULL) { warning("The ", .ifelse(is.null(Pkg), "specified package", Pkg), " does not exist.") return(invisible(NULL)) } .TempUnavailable = function() { warning("This command is temporarily unavailable.") return(invisible(NULL)) } .WindowsOnly = function() { warning("This function is for users running R under the Windows operating system.") return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/Warnings.R
## N.B. The first function was created before glimpse() was working nicely for a screen reader user; ## it is somewhat redundant now, but kept for backwards compatibility check_it = CheckIt = function(x, ...){ dplyr::glimpse(x) return(x) } what_is = WhatIs = function(x, ...){ cat("\n") VI(x, ...) cat("\n") return( invisible(x)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WhatIs.R
WhereXY = function(x, y = NULL, grid = c(4, 4), xDist = "uniform", yDist = xDist, addmargins = TRUE) { if (is.null(y)) { x = as.matrix(x) if (length(x[1, ]) != 2) { .NoYNeeds2X() } y = x[, 2] if (!is.numeric(y)) { .XOrYNotNumeric(which="y") } x = x[, 1] if (!is.numeric(x)) { .XOrYNotNumeric(which="x") } } XMin = min(x, na.rm = TRUE) YMin = min(y, na.rm = TRUE) XMax = max(x, na.rm = TRUE) YMax = max(y, na.rm = TRUE) XRange = XMax - XMin YRange = YMax - YMin if (xDist == "uniform") { XNew = cut(x, breaks = grid[1], labels = FALSE) } else { XMean = mean(x, na.rm = TRUE) XSD = sd(x, na.rm = TRUE) XBreaks = c((1 - 0.1 * sign(XMin)) * XMin, XMean + XSD * qnorm((1:(grid[1] - 1)) / grid[1]), (1 + 0.1 * sign(XMax)) * XMax) XNew = cut(x, breaks = XBreaks, labels = FALSE) } if (yDist == "uniform") { #YBreaks <- seq(YMax+0.001*YRange,YMin-0.001*YRange, length.out=grid[2]+1) YNew = cut(y, breaks = grid[2], labels = FALSE) } #cut(y,breaks=YBreaks, labels=FALSE)} else { YMean = mean(y, na.rm = TRUE) YSD = sd(y, na.rm = TRUE) YBreaks = c((1 - 0.1 * sign(YMin)) * YMin, YMean + YSD * qnorm((1:(grid[2] - 1)) / grid[2]), (1 + 0.1 * sign(YMax)) * YMax) YNew = cut(y, breaks = YBreaks, labels = FALSE) } XNew <- factor(XNew, levels = c(1:grid[1])) YNew <- factor(YNew, levels = c(1:grid[2])) Output = tapply(x, list(YNew, XNew), length) Output[is.na(Output)] = 0 Output = Output[rev(1:grid[2]), ] if (addmargins) { Output = addmargins(Output) } return(Output) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WhereXY.R
WhichFile = function(String, Folder, fixed=TRUE, DoesExist=TRUE){ Files=list.files(path=Folder, recursive =TRUE, full.names =TRUE) Out="" for(i in Files){ Text = readLines(i) if(DoesExist){ if(any(grep(String, Text, fixed=fixed))) Out=c(Out,i)} else{ if(!any(grep(String, Text, fixed=fixed))) Out=c(Out,i)} } return(Out) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WhichFile.R
## These commands can only be called from functions that have done OS checking ## They are left as internal commands for this reason ## the first function is the wrapper for the command line tool, and nothing more ## once working, look to update GetPython.R GetSoftware.R and installPython.R .winget = function(what, action=c("upgrade", "install", "show", "uninstall")){ Out = shell(paste("winget", action, what), intern=TRUE) return(Out) } # possibly create .winget7Zip .wingetMaxima and/or .wingetOctave .wingetPandoc = function(){ action = .ifelse(rmarkdown::pandoc_available(), "upgrade", "install") return(.winget("pandoc", action)) } # possibly create .wingetPython but need to wait for wxPython to be 3.10 compliant .wingetQuarto = function(){ action = .ifelse(is.null(quarto::quarto_path()), "install", "upgrade") return(.winget("Quarto", action)) } ## N.B. there is no "upgrade" of R, just installation of the latest version .wingetR=function(){ return(.winget("RProject.R", "install")) } # possibly create .wingetRStudio # possibly create .wingetRTools
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WinGet.R
.RunWriteRExecutable = function(file=NULL){ shell(paste0(Sys.which("WriteR"), .ifelse(is.null(file), "", file)), wait=FALSE) } .IsWriteRAvailable = function(){ Success = FALSE PyExists = TestPython() if(PyExists && .IsWxAvailable()){ Success=TRUE }else{ if(PyExists){ Success = .PullWxUsingPip() }else{ .NeedsPython() } } return(invisible(Success)) } # Running the WriteR application # only for Windows users at present. WriteR = function(file = NULL, math = c("webTeX", "MathJax")) { if (interactive()) { if (.Platform$OS.type == "windows") { if (.IsWriteRAvailable() | Sys.which("WriteR") != "") { if (!is.null(file)) { if (!file.exists(file)) { .FileCreated(file=file, where="in the current directory.") file.copy(system.file("Templates/simpleYAMLHeader.Rmd", package="BrailleR"), file) } } shell(paste0('"', file.path(system.file( "Python/WriteR/WriteR.pyw", package = "BrailleR")), '" ', .ifelse(is.null(file), "", file)), wait=FALSE) } else { .NeedsWX() .InstallPython() } } else { .WindowsOnly() } } else { .InteractiveOnly() } return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/WriteR.R
dotplot = function(x, ...) { UseMethod("dotplot") } dotplot.default = function(x, ...) { .NotBaseRWarning("The dotplot command is a wrapper for stripchart,") MC <- match.call(expand.dots = TRUE) MC[[1L]] <- quote(graphics::stripchart) names(MC)[2] = "" Out <- eval(MC, parent.frame()) if (length(MC$vertical) > 0) { Out$vertical = as.logical(MC$vertical) } else { Out$vertical = FALSE } Out$vals = list(sort(x)) Out$main = as.character(MC$main) # then overwrite if user has specified (even if in error) if (length(MC$group.names) > 0) Out$group.names = as.character(MC$group.names) if (length(MC$dlab) > 0) Out$dlab = as.character(MC$dlab) if (length(MC$glab) > 0) Out$glab = as.character(MC$glab) 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) = "dotplot" Out=Augment(Out) return(invisible(Out)) } dotplot.formula = function(x, ...) { .NotBaseRWarning("The dotplot command is a wrapper for stripchart,") MC <- match.call(expand.dots = TRUE) MC[[1L]] <- quote(graphics::stripchart) names(MC)[2] = "" Out <- eval(MC, parent.frame()) if (length(MC$vertical) > 0) { Out$vertical = as.logical(MC$vertical) } else { Out$vertical = FALSE } Temp = aggregate(x, FUN = sort) Out$vals = Temp[[2]] names(Out$vals) = Temp[[1]] # formula assigns glab which is old school Out$main = as.character(MC$main) # then overwrite if user has specified (even if in error) if (length(MC$group.names) > 0) Out$group.names = as.character(MC$group.names) if (length(MC$dlab) > 0) Out$dlab = as.character(MC$dlab) if (length(MC$glab) > 0) Out$glab = as.character(MC$glab) 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) = "dotplot" Out=Augment(Out) return(invisible(Out)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/dotplots.R
# as supplied by Duncan Murdoch # is pretty much the utils::history with use of file.edit() at the end. history = function(max.show = 25, reverse = FALSE, pattern, ...) { file1 <- tempfile("Rrawhist") savehistory(file1) rawhist <- readLines(file1) unlink(file1) if (!missing(pattern)) rawhist <- unique(grep(pattern, rawhist, value = TRUE, ...)) nlines <- length(rawhist) if (nlines) { inds <- max(1, nlines - max.show):nlines if (reverse) inds <- rev(inds) } else inds <- integer() file2 <- tempfile("hist") writeLines(rawhist[inds], file2) file.edit(file2) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/history.R
# this file is a quick and dirty hack necessary while an update to the installr package is finalised. # the installr commands are circumvented by adding a . to the front of the commands and putting it in the BrailleR package (temporarily). # Copyright (C) Tal Galili # # This file is part of installr. # # installr is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # installr is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # http://www.r-project.org/Licenses/ # # @title Downloads and installs python 2 or 3 # @description Downloads and installs the latest version of python 2 or 3 for Windows. # @details # Python is a programming language which has two versions under active development. # Make sure you know which version is required for the code you have to run, or alternatively, make sure you are developing code that is fit for your chosen version of Python. In addition, the Python installers are specific to 32 or 64 bit windows architectures. # # @return TRUE/FALSE - was the installation successful or not. # @export # @author Tal Galili and A. Jonathan R. Godfrey # @param page_with_download_url a link to the list of download links for Python # @param x64 logical: fetch a 64 bit version. default checks architecture of current R session. # @param version_number Either 2 or 3. Version 2/3 will lead to download of v2.7.xx/3.6.xx respectively. # @param ... extra parameters to pass to \link{install.URL} # @examples # \dontrun{ # install.python() # install.python(,3) # install.python(,2) # } .install.python = function (page_with_download_url = "https://www.python.org/downloads/windows/", version_number = 3, x64 = .is.x64(), ...) { page <- readLines(page_with_download_url, warn = FALSE) pat <- paste0("Latest Python ",version_number," Release") pat_exact_version <- paste0("Python ",version_number,"[0-9.]+") target_line <- grep(pat, page, value = TRUE) m <- regexpr(pat_exact_version, target_line) VersionNo <- regmatches(target_line, m)[1] VersionNo <- gsub("Python ", "", VersionNo) # https://www.python.org/ftp/python/3.5.1/python-3.5.1.exe # "https://www.python.org/ftp/python/3.5.1/python-3.5.1.exe" # or annoyingly, the extension for the Python 2.7 installer is msi. and requires # https://www.python.org/ftp/python/2.7.11/python-2.7.11.msi file_extension <- switch(as.character(version_number), "2" = "msi", "3" = "exe") URL <- paste0("https://www.python.org/ftp/python/",VersionNo, "/python-",VersionNo , ".", file_extension)[1] if(x64){ #different filenames for P3 Py27#Py3 URL <- sub(".exe", "-amd64.exe", URL) #Py3 URL <- sub(".msi", ".amd64.msi", URL) #Py2.7 } installr::install.URL(URL, ...) } .is.x64 <- function(){ .Platform$r_arch == "x64" }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/installPython.R
## Constructs the center of the scatterplot .AddXMLAddScatterCenter = function(root, sp=NULL) { annotation = .AddXMLAddAnnotation(root, position=4, id="center", kind="grouped") gs = sp$GroupSummaries len = length(gs$N) XML::addAttributes( annotation$root, speech="Scatter Plot", speech2=paste("Scatter Plot divided into", len, "sub intervals of equal width"), type="Center") annotations <- list() for (i in 1:len) { annotations[[i]] = .AddXMLtimeseriesSegment( root, position=i, mean=gs$MeanY[i], median=gs$MedianY[i], sd=gs$SDY[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)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/latest.R
nNonMissing = function(x){ length(na.omit(x)) # because length() alone would include NAs }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/nNonMissing.R
Notepad = notepad = function(file=""){ if (interactive()) { if (.Platform$OS.type == "windows") { shell(paste('notepad', file), wait=FALSE) } else { .WindowsOnly() } } else { .InteractiveOnly() } return(invisible(NULL)) } Explorer = explorer = function(){ if (interactive()) { if (.Platform$OS.type == "windows") { shell('explorer "."', wait=FALSE) } else { .WindowsOnly() } } else { .InteractiveOnly() } return(invisible(NULL)) } CMD = cmd = function(){ if (interactive()) { if (.Platform$OS.type == "windows") { shell('cmd', wait=FALSE) } else { .WindowsOnly() } } else { .InteractiveOnly() } return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/notepad.R
.CheckForPython27 = # ripe for removal function(){ PyPath = Sys.which("python") } .AddHeadingTags = function(htmlfile, outfile=htmlfile, LowestHeadingLevel){ InFile = readLines(htmlfile) TagDetails = .FindHeadingSizes(htmlfile) for(i in 1:min(length(TagDetails$Sizes), LowestHeadingLevel)){ cat("Font size", TagDetails$Sizes[i], "being turned into", TagDetails$HeadingTags[i], "\n") TempText = gsub(paste0('(.*)font-size:', TagDetails $Sizes[i], 'px">(.*)'), paste0("\\1font-size:", TagDetails$Sizes[i], 'px"><', TagDetails$HeadingTags[i], ">\\2</", TagDetails$HeadingTags[i], ">"), InFile) InFile = TempText } writeLines(TempText, outfile) } .FindHeadingSizes = function(htmlfile){ InFile = readLines(htmlfile) tempText = gsub("(.*)font-size:([0-9]+)px(.*)", "\\2", InFile) TextSize = suppressWarnings(as.integer(tempText)) TextSize[1]=0 for(i in 2:length(TextSize)){ TextSize[i] = ifelse(is.na(TextSize[i]), TextSize[i-1], TextSize[i]) } SizeFreqs = tapply(TextSize,TextSize,length) BodySize = as.integer(names(SizeFreqs)[which.max(SizeFreqs)]) SizesUsed = as.integer(names(SizeFreqs)) HSizes = SizesUsed[SizesUsed > BodySize] return(list(Sizes = sort(HSizes, TRUE), HeadingTags = paste0("h", 1:length(HSizes)))) } .DoubleGrave2LeftQuote = function(htmlfile, outfile=htmlfile){ InFile = readLines(htmlfile) tempText = gsub("(.*)``(.*)", '\\1"\\2', InFile) writeLines(tempText, outfile) } .AddParagraphTagsBetweenDivs = function(htmlfile, outfile=htmlfile){ InFile = readLines(htmlfile) tempText = gsub("(.*)</div><div(.*)", "\\1</div><p><div\\2", InFile) writeLines(tempText, outfile) } .PageNumbers2Headings = function(htmlfile, outfile=htmlfile, HeadingTag="h6"){ InFile = readLines(htmlfile) tempText = gsub("(.*)Page ([0-9]+)</a>(.*)", paste0("\\1<", HeadingTag, ">Page \\2</", HeadingTag, "></a>\\3"), InFile) writeLines(tempText, outfile) } .FindLastPage = function(htmlfile){ ReadIn = readLines(htmlfile) NLines=length(ReadIn) PageHooks = ReadIn[NLines-1] SepPageHooks = unlist(strsplit(PageHooks, '">')) NSepPageHooks = length(SepPageHooks ) LastPageNo = as.integer(unlist(strsplit(SepPageHooks[NSepPageHooks], "</a>"))[1]) return(LastPageNo) } .RemoveLigatures = function(infile, outfile=infile){ shell(paste0('python "', file.path(system.file( "Python/latin2html.py", package = "BrailleR")), '" "', infile, '" > "', outfile, '"')) return(invisible(NULL)) } .PullPDFMinerUsingPip = function(){ if(shell('python -c "import pdfminer"')==0){ system("pip install -U pdfminer") } else { system("pip install pdfminer") } return(invisible(TRUE)) } .IsPDFMinerAvailable = function(){ Success = FALSE if(TestPython() && shell('python -c "import pdfminer"')==0){ Success = TRUE }else{ if(TestPython()){ Success = .PullPDFMinerUsingPip() }else{ .NeedsPython() } } return(invisible(Success)) } pdf2html = function(pdffile, htmlfile=sub(".pdf", ".html", pdffile), HeadingLevels=4, PageTag="h6"){ .ExperimentalFunction() Success = FALSE if (.IsPDFMinerAvailable()) { shell(paste("pdf2txt.py -O TempDir -o tempfile.html -t html", pdffile)) .RemoveLigatures("tempfile.html", htmlfile) file.remove("tempfile.html") .AddHeadingTags(htmlfile, LowestHeadingLevel=HeadingLevels) .PageNumbers2Headings(htmlfile, outfile=htmlfile, HeadingTag=PageTag) Success = TRUE } else { .NoConversion() } return(invisible(Success)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/pdf2html.R
.onDetach = function(libpath) { options("BrailleR.VI" = NULL) } .onAttach = function(libname, pkgname) { options("BrailleR.VI" = TRUE) options("BrailleR.Advanced" = FALSE) if (interactive()) { packageStartupMessage( "The BrailleR.View option has been set to TRUE. \nConsult the help page for GoSighted() to see how settings can be altered.\nYou may wish to use the GetGoing() function as a quick way of getting started.") } else { packageStartupMessage("The BrailleR.View, option is set to FALSE.") } } .onLoad = function(libname, pkgname) { ns <- getNamespace(pkgname) Folder = SetupBrailleR() if (file.exists("BrailleROptions")) { OpSet = read.dcf("BrailleROptions", all = TRUE) } else { # first time package is used in this directory if (is.null(Folder)) { OpSet = read.dcf(system.file("MyBrailleR/BrailleROptions", package = "BrailleR"), all = TRUE) } else { OpSet = read.dcf(file.path(Folder, "/BrailleROptions"), all = TRUE) } # to do: # ask for permission to write a local copy ## write.dcf(OpSet, file="BrailleROptions") } OpSet$BrailleR.Folder = Folder OpSet$BrailleR.SigLevel = as.numeric(OpSet$BrailleR.SigLevel) OpSet$BrailleR.PValDigits = as.numeric(OpSet$BrailleR.PValDigits) OpSet$BrailleR.DotplotBins = as.numeric(OpSet$BrailleR.DotplotBins) OpSet$BrailleR.BRLPointSize = as.numeric(OpSet$BrailleR.BRLPointSize) OpSet$BrailleR.PaperWidth = as.numeric(OpSet$BrailleR.PaperWidth) OpSet$BrailleR.PaperHeight = as.numeric(OpSet$BrailleR.PaperHeight) #OpSet$ = as.numeric(OpSet$) do.call(options, as.list(OpSet)) Op <- getOption("repos") Op["CRAN"] <- "https://cran.rstudio.com/" options(repos = Op) options(BrailleR.View = interactive()) BrailleR = new.env(parent = .GlobalEnv) if (interactive()) { options("menu.graphics" = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/BrailleR/R/zzz.R
# this is a heading ## this is a level two heading Now it's time for some R ```{r no1} x=1:10 mean(x) ``` We can also ask for stuff in line such as `r mean(x)` into our sentence. ```{r AHistogram, fig.cap="My first histogram"} hist(rnorm(1000)) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Python/WriteR/Basics.Rmd
# First notes about WriteR --- an R markdown editor #### last updated by Jonathan Godfrey on 6 January 2016 Version: 0.160105.3 Credits: Original concept by Jonathan Godfrey, coding by James Curtis. Feedback: Bugs and enhancement suggestions should be sent to Jonathan Godfrey <[email protected]> ## What is WriteR? This editor was created because blind R users cannot use the excellent RStudio integrated development environment (IDE) with their screen reader software. The first task that the WriteR application makes possible for blind users is the processing of markdown with embedded R code. This could prove invaluable for blind students completing assignment work. ## What do I need? In addition to the files in the current download, you need to have three other applications installed on your computer to make the editor fully functional: 1. you must have R installed on your computer. If you do not edit the settings file, the first time you run the WriteR editor, it will search for the latest version of R that you have installed. This is necessary because some users will have multiple versions of R on their system. 2. the WriteR editor is currently written in Python so needs it to be installed on your computer. This will change once we've slowed down the pace of development. At that time, the download will be an executable file for each operating system or similar solution instead of source code that must be interpreted. Our hope is to re-release the application using C++ instead of Python. 3. to convert the markdown document you create into a fully accessible HTML document, you will also need pandoc. If you have pandoc installed on your computer it is already listed in your path as part of its default installation. ## Getting started with WriteR outside R The following is a set of instructions that is Windows-centric. If you are a Linux or Mac user and you know what you are doing given what you read for the Windows users, please do share your experiences with the developers. We'd love to pass your knowledge on to others and we will give you credit for your efforts. If you downloaded WriteR as a zip file then it has one program file and several test files, including the file you are now reading. Put the downloaded file into a folder where you want to do your working. Unzip it here. When you first open WriteR, by hittin Enter on the WriteR.pyw file, the application will create an options file called "WriteROptions" in the working directory alongside WriteR.pyw. You will need to open this file using your favourite text editor to review its contents. We are primarily concerned that WriteR has maanged to find your R installation when it created the WriteROptions file. The first thing you will need to do when WriteR opens is to choose a file to edit. If you do not want to edit an existing file, hit the "Escape" key or the "Cancel" button. If you have used the application before, the last file you edited will be opened automatically. A second option for opening WriteR does exist if you are comfortable using hte command line in Windows. If you navigate to the working directory where you can see the WriteR.pyw file, then you should be able to open the application by typing `WriteR.pyw` at the prompt. If you like this way of working, then you can look forward to expanding the use of the command line approach to add the name of the file you wish to edit as the argument to the command. If you did not understand the second option just presented, stick to using the first option given above. Linux users: do what? Mac users: do what? Go to the section which continues with help on basic editing of your first document. ## Getting started with WriteR from inside R WriteR is bundled in the BrailleR ppackage for R. Convenience functions have been written to get you started as easily as we can manage. ## Basic editing of your first document. Start editing your file once you can see WriteR has opened up a window properly. If you did not choose a file, some default text was put in the window for you. When you have typed enough and want to see how it is represented in HTML, you will "build" the HTML document. A menu item does exist for this but the hot key is set to f5. You must save your work immediately prior to the build process using the ctrl+s hot key. The newly updated HTML file is in the same folder as the Rmd file you are editing. If all has gone to plan, that will be the Working folder. You will need to browse to that folder manually to find the new file and open it in the browser of your choice. You can keep this file open. After you update the Rmd file in the editor and re-build the HTML, you will need to refresh the HTML file being viewed by hitting f5 in the browser. We'll try to make this a smoother exercise in future releases. So, the steps to update your html file after some editing of your Rmd file is: save, build, switch, refresh. In terms of hot keys, that is ctrl+s, f5, alt+tab, and f5. N.B. you might need to alt+tab a few times to work through the windows that are open at present. To find out how to create R markdown content, take a look at the file "Basics.Rmd" bundled with the application. Once you open it in WriteR, try to build it to see how the R content appears. There is plenty of documentation out there for writing R markdown documents so we don't need to include it here. ## Removing the WriteR editor The installation process is about as clean as it can be. To remove WriteR you only need to delete the folder where you put the files for the application. There is no uninstallation process to work through. ## Known bugs and suggestions ### Minor - the word editor appears when the file is first opened and needs to be deleted. This "starting text" can be tailored to whatever you like in the settings menu item. - the save as points to the wrong folder initially. Change this in the settings menu item. - the About dialogue needs the version number put in it. I'm using the date (in yymmdd format) as the minor version number at present. The major version number will remain at zero until we have a satisfactory level of development for a public release. - standard highlighting and hot keys for modification. e.g. highlight a word and bold it with ctrl+b. ### Major - a settings file and menu would definitely help. This was introduced in v0.150227 although it has a quirk about the labelling of the dialogue boxes when using Jaws as the screen reader. - perhaps we can allow other file types down the track. This could be useful for Rnw files for example. - spell checking would be nice. - as well as Build, can we have a Build and View hot key? - can we update the browser on build and view? ### Resolved:
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Python/WriteR/HelpPage.Rmd
## D'Agostino test for skewness in normally distributed data. ```{r} #| label = "GetMomentsPkg" library(moments) ``` ```{r} #| label = "{{ResponseName}}.at" {{ResponseName}}.at = {{ResponseName}} |> agostino.test() {{ResponseName}}.at ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Agostino.Rmd
## Anscombe-Glynn test of kurtosis for normal samples ```{r} #| label = "GetMomentsPkg" library(moments) ``` ```{r} #| label = "{{ResponseName}}.agt" {{ResponseName}}.agt = {{ResponseName}} |> anscombe.test() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Anscombe.Rmd
## Bartlett Test of Homogeneity of Variances Description: Performs Bartlett's test of the null hypothesis that the variances in each of the groups (samples) are the same. ```{r} #| label = "{{DataName}}BartlettTest" bartlett.test({{ResponseName}} ~ {{FactorName}}, data = {{DataName}}) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Bartlett.Rmd
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)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/BasicSummaryStats.R
## Bonett-Seier test of Geary's measure of kurtosis for normally distributed data. ```{r} #| label = "GetMomentsPkg" library(moments) ``` ```{r} #| label = "{{ResponseName}}.bt" {{ResponseName}}.bt = {{ResponseName}} |> bonet.test() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Bonett.Rmd
```{r} #| label = "{{DataName}}Boxplots", #| fig.cap = "Comparative boxplots for {{ResponseName}} grouped by #| {{FactorName}}." {{DataName}} |> ggplot(aes(y={{ResponseName}}, x={{FactorName}})) + geom_boxplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Boxplots.Rmd
## Breusch-Godfrey Test Description: Tests for higher-order serial correlation. ```{r} #| label = "GetLibLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.bg" {{DataName}}.bg = {{DataName}}.lm |> bgtest() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Brewsch.Rmd
## Cohen's Kappa Description: calculates weighted and unweighted kappa statistics and their 95% confidence intervals. ```{r} #! label="GetVCDPkg" library(vcd) ``` ```{r} #! label = "{{DataName}}.K" {{DataName}}.K <- Kappa({{DataName}}) summary({{DataName}}.K) print({{DataName}}.K, CI = TRUE) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/CohensKappa.Rmd
DataName.aov1 <- aov(ResponseName ~ SubjectName + PeriodName + TreatmentName, data=DataName) summary(DataName.aov <- aov(ResponseName ~ GroupName + PeriodName + TreatmentName + Error(SubjectName), data=DataName)) par(mfrow=c(2,2)) plot(DataName.aov1)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Crossover2x2.R
with(DataName, tapply(ResponseName, list(PeriodName, GroupName), mean)) summary(ResponseName.aov <- aov(ResponseName ~ GroupName + PeriodName + TreatName + Carry1Name + Error(SubjectName), data=DataName)) summary(ResponseName.aov <- aov(ResponseName ~ GroupName + PeriodName + Carry1Name + TreatName + Error(SubjectName), data=DataName))
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/CrossoverWith1Carry.R
require(data.table) DataSummary = as.data.table(DataName)[, list(Mean = mean(ResponseName, na.rm=T), StdDev = sd(ResponseName, na.rm=T), N=sum(!is.na(ResponseName)) ), FactorSet] DataSummary$"Standard Error" = DataSummary$StdDev/sqrt(DataSummary$N)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/DTGroupSummary.R
```{r} #| label = "{{DataName}}Dotplots", #| fig.cap = "Plots for {{ResponseName}} grouped by {{FactorName}}." {{DataName}} |> ggplot(aes(y={{ResponseName}}, x={{FactorName)}}) + geom_point() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Dotplots.Rmd
```{r} #| label = "getLibs" library(multcomp) library(tidyverse) library(knitr) library(broom) ``` ## Dunnett's procedure for comparing all treatments with a control ```{r} #| label = "{{DataName}}.Dunnett" {{DataName}}.Dunnett = glht({{DataName}}.lm, linfct = mcp({{FactorName}} = "Dunnett")) {{DataName}}.Dunnett |> tidy() |> kable(caption="Dunnett's multiple comparison procedure for the {{DataName}} data.) ``` ```{r} #| label = "getSummary" {{DataName}}.Dunnett|> summary() |> tidy() |> kable(caption="Summary of Dunnett's multiple comparison procedure for the {{DataName}} data.) ``` ```{r} #| label = "getCLD" {{DataName}}.Dunnett|> cld() |> tidy() |> kable(caption="Compact letter display of Dunnett's multiple comparison procedure for the {{DataName}} data.) ``` ```{r} #| label = "plot{{DataName}}.Dunnett", #| fig.cap = "Plot of Dunnett's procedure for {{ResponseName}} grouped by #| {{FactorName}}." plot({{DataName}}.Dunnett) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Dunnett.Rmd
## Durbin-Watson Test ```{r} #| label = "GetLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.dw" {{DataName}}.dw = {{DataName}}.lm |> dwtest() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/DurbinWatson.Rmd
```{r} #| label = "GetEMMEansPkg" library(emmeans) ``` ```{r} #| label = "{{DataName}}.lm.emmeans" emmeans({{DataName}}.lm, "{{FactorName}}") |> kable(caption="Estimated marginal means for {{ResponseName}}, grouped by {{FactorName}}.") ``` ```{r} #| label = "{{DataName}}.lm.emmeansPlotted", #| fig.cap = "plot of confidence intervals for estimated marginal means #| for {{ResponseName}} grouped by {{FactorName}}." emmeans({{DataName}}.lm, "{{FactorName}}") |> plot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/EMMeans.Rmd
```{r} #| label = "ChunkName" ... ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/EmptyChunk.Rmd
```{r} #| label = "{{DataName}}FittedLinePlot", #| fig.cap = "Plot of {{ResponseName}} versus {{PredictorName}} with fitted #| line added." library(ggplot2) {{DataName}} |> select({{ResponseName}}, {{PredictorName}}) |> filter(!is.na({{ResponseName}}), !is.na({{PredictorName}})) |> ggplot(aes(y={{ResponseName}}, x={{PredictorName}})) + geom_point() + geom_smooth(method="lm") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/FittedLinePlot.Rmd
## Fligner-Killeen Test of Homogeneity of Variances Description: Performs a Fligner-Killeen (median) test of the null that the variances in each of the groups (samples) are the same. ```{r} #| label = "{{DataName}}.FlignerTest" fligner.test({{ResponseName}} ~ {{FactorName}}, data = {{DataName}}) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Fligner.Rmd
## Friedman Rank Sum Test Description: Performs a Friedman rank sum test with unreplicated blocked data. friedman.test can be used for analyzing unreplicated complete block designs (i.e., there is exactly one observation in y for each combination of levels of groups and blocks) where the normality assumption may be violated. The null hypothesis is that apart from an effect of blocks, the location parameter of y is the same in each of the groups. ```{r} #| label = "GetRStatixPkg" library(rstatix) ``` ```{r} #| label = "{{DataName}}.ft" {{DataName}}.ft = {{DataName}} |> friedman_test({{ResponseName}} ~ {{FactorName}} | {{BlockingName}}) {{DataName}}.ft |> kable(caption="Friedman test for {{ResponseName}} disaggregated by {{FactorName}}, and adjusting for {{BlockingName}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Friedman.Rmd
```{r} #| label = "get{{DataName}}" {{DataName}} = read.csv("{{FileName}}", stringsAsFactors = TRUE) |> mutate() |> glimpse() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/GetData.Rmd
```{r} #| label = "getLibs", #| include = FALSE library(tidyverse) library({{PkgName}}) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/GetLibs.Rmd
```{r} #| label = "Desc{{DataName}}" {{DataName}} |> drop_na({{ResponseName}}) |> group_by({{FactorSet}}) |> summarise( Mean = mean({{ResponseName}}), StDev = sd({{ResponseName}}), Count = n() ) |> mutate(StdErr = StDev/sqrt(Count)) |> kable(caption="Descriptive statistics for {{ResponseName}} disaggregated by {{FactorSet}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/GroupSummary.Rmd
## Breusch-Pagan Test Description: Performs the Breusch-Pagan test against heteroskedasticity. ```{r} #| label = "GetLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.lm.bp" {{DataName}}.lm.bp = {{DataName}}.lm |> bptest() ``` ## Harrison-McCabe test Description: Harrison-McCabe test for heteroskedasticity. ```{r} #| label = "{{DataName}}.lm.hmc" {{DataName}}.lm.hmc = {{DataName}}.lm |> hmctest() ``` ## Goldfeld-Quandt Test Description: Goldfeld-Quandt test against heteroskedasticity. ```{r} #| label = "{{DataName}}.lm.gq" {{DataName}}.lm.gq = {{DataName}}.lm |> gqtest() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Heterogeneity.Rmd
## Jarque-Bera test for normality ```{r} #| label = "GetMomentsPkg" library(moments) ``` ```{r} #| label = "{{ResponseName}}.jbt" {{ResponseName}}.jbt = {{ResponseName}} |> jarque.test() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Jarque.Rmd
## Kruskal-Wallis Rank Sum Test ```{r} #| label = "GetRStatixPkg" library(rstatix) ``` ```{r} #| label = "{{DataName}}.kt" {{DataName}}.kt = {{DataName}} |> kruskal_test({{ResponseName}} ~ {{FactorName}}) {{DataName}}.kt |> kable(caption="Kruskal-Wallace nonparametric one-way test for differences in {{ResponseName}} grouped by {{FactorName}}.") ``` ```{r} #| label = "DunnTest" {{DataName}}.dt = {{DataName}} |> dunn_test({{ResponseName}} ~ {{FactorName}}) {{DataName}}.dt |> kable(caption="Dunn's multiple comparison test for {{ResponseName}} disaggregated by {{FactorName}}.") ``` ```{r} #| label = "getMeans" {{DataName}}.dt |> get_emmeans() |> kable(caption="Means of {{ResponseName}} disaggregated by {{FactorName}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Kruskal.Rmd
```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{RowFactor}}+{{ColFactor}}+{{FactorName}}, data = {{DataName}}) {{DataName}}.lm |> anova() ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm |> autoplot() ``` ```{GetMeans} library(emmeans) emmeans({{DataName}}.lm, pairwise ~{{FactorName}}) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/LatinSquare.Rmd
## Levene's Test ```{r} #| label = "GetRStatixPkg" library(rstatix) ``` ```{r} #| label = "{{DataName}}.lt" {{DataName}}.lt = {{DataName}} |> levene_test({{ResponseName}} ~ {{FactorName}}) {{DataName}}.lt |> kable(caption="Levene's test for homogeneity of variance of {{ResponseName}} grouped by {{FactorName}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Levene.Rmd
## Harvey-Collier Test Description: Harvey-Collier test for linearity. ```{r} #| label = "GetLibLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.harv" {{DataName}}.harv = {{DataName}}.lm |> harvtest() ``` ## Ramsey's RESET test for functional form. ```{r} #| label = "{{DataName}}.reset" {{DataName}}.reset = {{DataName}}.lm |> resettest() ``` ## Rainbow test for linearity. ```{r} #| label = "{{DataName}}.rain" {{DataName}}.rain = {{DataName}}.lm |> raintest() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Linearity.Rmd
```{r} #| label = "getLibs" library(tidyverse) library(broom) library(knitr) ``` ```{r} #| label = "getDistMat" ## add commands here to make # DistMat ``` ```{r} #| label = "{{DataName}}.mds" {{DataName}}.mds = DistMat |> cmdscale() colnames({{DataName}}.mds) = c("x", "y") ``` ```{r} #| label = "{{DataName}}.kmeans" {{DataName}}.kmeans = kmeans({{DataName}}.mds , NClust) {{DataName}}.kmeans |> tidy() |> kable(caption="Cluster details fort he {{DataName}} data.") ``` ```{r} #| label = "addClusters" {{DataName}}.mds = {{DataName}}.mds |> as_tibble() |> mutate(Labels = labels(DistMat), Cluster = as.factor({{DataName}}.kmeans$cluster)) ``` ```{r} #| label = "plot{{DataName}}.mds", #| fig.cap = "Multidimensional scaling of the {{DataName}} data." {{DataName}}.mds |>ggplot(aes(x=x, y=y, groups=Cluster)) + geom_point() ``` ```{r} #| label = "getClusters" {{DataName}}.mds |> arrange(Cluster) |> kable(caption="Cluster memberships for the {{DataName}} data.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/MDS.Rmd
DataName.maov <- manova(ResponseMatrix ~ FactorNames, data=DataName) summary(DataName.maov, test="Wilks") summary(DataName.maov, test="Roy") summary(DataName.maov, test="Hotelling-Lawley") summary(DataName.maov, test="Pillai") summary.aov(DataName.maov)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Manova.R
## Cox Test for Comparing Non-Nested Models ```{r} #| label = "GetLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.cox" {{DataName}}.cox = coxtest({{DataName}}.lm1,{{DataName}}.lm2) {{DataName}}.cox ``` ## The encompassing test of Davidson & MacKinnon for comparing non-nested models. ```{r} #| label = "{{DataName}}.encomp" {{DataName}}.encomp = encomptest({{DataName}}.lm1,{{DataName}}.lm2) {{DataName}}.encomp ``` ## The Davidson-MacKinnon J test for comparing non-nested models ```{r} #| label = "{{DataName}}.j" {{DataName}}.j = jtest({{DataName}}.lm1,{{DataName}}.lm2) {{DataName}}.j ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/NonNested.Rmd
```{r} #| label = "GetNortestPkg" library(nortest) ``` ```{r} #| label = "{{DataName}}-{{ResponseName}}Normality" NormalityResults = matrix(0, nrow=6, ncol=2) dimnames(NormalityResults) = list(c("Shapiro-Wilk", "Anderson-Darling", "Cramer-von Mises", "Lilliefors (Kolmoorov-Smirnov)", "Pearson chi-square", "Shapiro-Francia"), c("Statistic", "P Value")) {{ResponseName}}.swt = {{ResponseName}} |> shapiro.test() NormalityResults[1,] = c({{ResponseName}}.swt$statistic, {{ResponseName}}.swt$p.value) {{ResponseName}}.adt = {{ResponseName}} |> ad.test() NormalityResults[2,] = c({{ResponseName}}.adt$statistic, {{ResponseName}}.adt$p.value) {{ResponseName}}.cvmt = {{ResponseName}} |> cvm.test() NormalityResults[3,] = c({{ResponseName}}.cvmt$statistic, {{ResponseName}}.cvmt$p.value) {{ResponseName}}.lkst = {{ResponseName}} |> lillie.test() NormalityResults[4,] = c({{ResponseName}}.lkst$statistic, {{ResponseName}}.lkst$p.value) {{ResponseName}}.pt = {{ResponseName}} |> pearson.test() NormalityResults[5,] = c({{ResponseName}}.pt$statistic, {{ResponseName}}.pt$p.value) {{ResponseName}}.sft = {{ResponseName}} |> sf.test() NormalityResults[6,] = c({{ResponseName}}.sft$statistic, {{ResponseName}}.sft$p.value) NormalityResults |> kable(caption="Normality tests for {{ResponseName}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/NormalityTests.Rmd
```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{FactorName}}, data=DataName) library(broom) {{DataName}}.lm |> augment() {{DataName}}.lm |> anova() ``` ```{r} #| label = "glance{{DataName}}.lm" {{DataName}}.lm |> glance() |> kable() ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/OneWayLM.Rmd
## Welch Test for Equal Means in a One-Way Layout Description: Test whether two or more samples from normal distributions have the same means. The variances are not necessarily assumed to be equal. ```{r} #| label = "GetRStatixPkg" library(rstatix) ``` ```{r} #| label = "{{DataName}}.wt" {{DataName}}.wt = {{DataName}} |> welch_anova_test({{ResponseName}} ~ {{FactorName}}) {{DataName}}.wt |> kable(caption="Welch's one-way hypothesis test for {{ResponseName}} grouped by {{FactorName}}.") ``` ## Games Howell Post-hoc Tests Description: Performs Games-Howell test, which is used to compare all possible combinations of group differences when the assumption of homogeneity of variances is violated. This post hoc test provides confidence intervals for the differences between group means and shows whether the differences are statistically significant. ```{r} #| label = "{{DataName}}.ght" {{DataName}}.ght = {{DataName}} |> games_howell_test({{ResponseName}} ~ {{FactorName}}) {{DataName}}.ght |> kable((caption="Games-Howell multiple comparison test for {{ResponseName}} disaggregated by {{FactorName}}.") ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/OneWayTest.Rmd
```{r} #| label = "getLibs" library(tidyverse) library(broom) library(knitr) ``` ```{r} #| label = "{{DataName}}.pc" {{DataName}}.pc = {{DataName}} |> select(where(is.numeric)) |> prcomp(center=TRUE, scale=FALSE) ``` ```{r} #| label = "GetVariances" {{DataName}}.pc |> tidy(matrix = "pcs") |> kable(caption="Principal Component contributions for the {{DataName}} data.") ``` ```{r} #| label = "ScreePlot{{DataName}}.pc", #| fig.cap = "Scree plot for the principal components analysis of the #| {{DataName}} data." {{DataName}}.pc |> plot() ``` ```{r } #| label = "getLoadings" {{DataName}}.pc$rotation |> kable(caption="Principal Component Loadings for the {{DataName}} data.") ``` ```{r} #| label = "biplot{{DataName}}.pc", #| fig.cap = "Biplot for the {{DataName}} data." {{DataName}}.pc |> biplot() ``` ```{r} #| label = "augment{{DataName}}.pc" {{DataName}}.pc.fit = {{DataName}}.pc |> augment({{DataName}}) ``` ```{r} #| label = "scatter{{DataName}}.pc", #| fig.cap = "Scatter plot of the first and second principle component #| scores." {{DataName}}.pc.fit |> ggplot(aes(x=.fittedPC1, y=.fittedPC2)) + geom_point(size = 1.5) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/PCA.Rmd
```{r} #| label = "Plot{{DataName}}", #| fig.cap = "" {{DataName}} |> ggplot(aes(y={{ResponseName}}, x={{PredictorName}})) + geom_point() + geom_smooth() ``` ```{r} #| label = "{{DataName}}.poly" {{DataName}}.poly1 <- lm({{ResponseName}} ~ {{PredictorName}}, data = DataName) {{DataName}}.poly2 <- lm({{ResponseName}} ~ poly({{PredictorName}}, 2, raw=TRUE), data = DataName) {{DataName}}.poly3 <- lm({{ResponseName}} ~ poly({{PredictorName}}, 3, raw=TRUE), data = DataName) {{DataName}}.poly4 <- lm({{ResponseName}} ~ poly({{PredictorName}}, 4, raw=TRUE), data = DataName) anova({{DataName}}.poly1, {{DataName}}.poly2, {{DataName}}.poly3, {{DataName}}.poly4) ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.poly" library(ggfortify) # should really change the following to the preferred model {{DataName}}.poly4 |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/PolyReg.Rmd
## Quade test with unreplicated blocked data ```{r} #| label = "{{DataName}}.qt" {{DataName}}.qt = quade.test({{ResponseName}} ~ {{FactorName}} | {{BlockingName}}, data = {{DataName}}) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/Quade.Rmd
```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{BlockingName}}+{{FactorName}}, data = {{DataName}}) library(broom) augment({{DataName}}.lm) anova({{DataName}}.lm) ``` ```{r} #| label = "glance{{DataName}}.lm" {{DataName}}.lm |> glance() |> kable() ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) autoplot({{DataName}}.lm) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/RCB.Rmd
```{r} #| label = "{{DataName}}.lme" library(nlme) {{DataName}}.lme = lme({{ResponseName}} ~ {{FactorName}}, random=1|{{BlockingName}}, data = {{DataName}}) library(broom) augment({{DataName}}.lme) anova({{DataName}}.lme) ``` ```{r} #| label = "glance{{DataName}}.lme" {{DataName}}.lme |> glance() |> kable() ``` ```{r} #| label = "plot{{DataName}}.lme", #| fig.cap = "Residual analysis for {{DataName}}.lme" library(ggfortify) autoplot({{DataName}}.lme) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/RandomBlock.Rmd
```{r} #| label = "plot{{ModelName}}", #| fig.cap = "Residual analysis for {{ModelName}}." library(ggfortify) {{ModelName}} |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/ResidualAnalysis.Rmd
```{r} #| label = "{{DataName}}Plot", #| fig.cap = "Plot of {{ResponseName}} versus {{PredictorName}} with smoother #| added." library(ggplot2) {{DataName}} |> select({{ResponseName}}, {{PredictorName}}) |> filter(!is.na({{ResponseName}}), !is.na({{PredictorName}})) |> ggplot(aes(y={{ResponseName}}, x={{PredictorName}})) + geom_point() + geom_smooth() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/ScatterPlot.Rmd
## Durbin-Watson Test Description: Performs the Durbin-Watson test for autocorrelation of disturbances. ```{r} #| label = "GetLibLMTestPkg" library(lmtest) ``` ```{r} #| label = "{{DataName}}.dw" {{DataName}}.dw = {{DataName}}.lm |> dwtest() {{DataName}}.dw ``` ## Breusch-Godfrey Test Description: performs the Breusch-Godfrey test for higher-order serial correlation. ```{r} #| label = "{{DataName}}.bg" {{DataName}}.bg = {{DataName}}.lm |> bgtest(order=10) {{DataName}}.bg ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/SerialCorrelation.Rmd
```{r} #| label = "DataNamePlot", #| fig.cap = "Plot of {{ResponseName}} versus {{PredictorName}} with fitted #| line added." library(ggplot2) {{DataName}} |> ggplot(aes(y=ResponseName, x=PredictorName)) + geom.point() + geom_smooth(method="lm") ``` ```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{PredictorName}}, data={{DataName}}) library(broom) {{DataName}}.lm.aug = {{DataName}}.lm |> augment() {{DataName}}.lm |> summary() ``` ```{r} #| label = "glance{{DataName}}.lm" {{DataName}}.lm |> glance() |> kable(caption="Summary statistics for {{DataName}}.lm.") ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/SimpleRegression.Rmd
```{r} #| label = "{{DataName}}.lme" library(nlme) {{DataName}}.lme = lme({{ResponseName}} ~ {{BlockingName}}+{{Factor1Name}}*{{Factor2Name}}, random=~1|{{MainPlotID}}, data = {{DataName}}) library(broom) {{DataName}}.lme |> augment() {{DataName}}.lme |> anova() ``` ```{r} #| label = "glance{{DataName}}.lme" {{DataName}}.lme |> glance() |> kable() ``` ```{r} #| label = "plot{{DataName}}.lme", #| fig.cap = "Residual analysis for {{DataName}}.lme" library(ggfortify) {{DataName}}.lme |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/SplitPlot.Rmd
```{r} #| label = "setup", #| purl = FALSE, #| include = FALSE library(knitr) opts_chunk$set(dev=c("png", "pdf", "postscript", "svg")) opts_chunk$set(comment="", echo=FALSE, fig.path="FolderName/FileStem", fig.width=7) ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/StandardSetupChunk.Rmd
```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{Factor1Name}}*{{Factor2Name}}*{{Factor3Name}}, data = {{DataName}}) {{DataName}}.lm |> anova() ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/ThreeWay.Rmd
```{r} #| label = "getLibs" library(multcomp) library(tidyverse) library(knitr) library(broom) ``` ## Tukey's Honestly sinificant difference ```{r} #| label = "{{DataName}}.hsd" {{DataName}}.hsd = glht({{DataName}}.lm, linfct = mcp({{FactorName}} = "Tukey")) {{DataName}}.hsd |> tidy() |> kable(caption="Tukey's Honestly Significant Differences for the {{DataName}} data.) ``` ```{r} #| label = "getSummary" {{DataName}}.hsd |> summary() |> tidy() |> kable(caption="Summary of Tukey's Honestly Significant Differences for the {{DataName}} data.) ``` ```{r} #| label = "getCLD" {{DataName}}.hsd |> cld() |> tidy() |> kable(caption="Compact letter display for Tukey's Honestly Significant Differences for the {{DataName}} data.) ``` ```{r} #| label = "plot{{DataName}}.hsd", #| fig.cap = "Plot of Tukey's HSD for {{ResponseName}} grouped by #| {{FactorName}}." {{DataName}}.hsd |> plot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/TukeyHSD.Rmd
```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm = lm({{ResponseName}} ~ {{Factor1Name}}*{{Factor2Name}}, data = {{DataName}}) {{DataName}}.lm |> anova() ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/TwoWay.Rmd
--- title: "" author: "" date: "" output: html_document: toc: false number_sections: false css: my_style.css fig_height: 7 fig_width: 7 ---
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/YAMLHeader.Rmd
```{r} #| label = "{{DataName}}Plot", #| fig.cap = "Plot of {{ResponseName}} versus {{Covariate}} with fitted lines #| added for each {{FactorName}}." library(ggplot2) {{DataName}} |> ggplot(aes(y = {{ResponseName}}, x = {{Covariate}}, group = {{FactorName}})) + geom.point() + geom_smooth(method="lm") ``` ```{r} #| label = "{{DataName}}.lm" {{DataName}}.lm1 = lm({{ResponseName}} ~ {{FactorName}}, data = {{DataName}}) {{DataName}}.lm2 = lm({{ResponseName}} ~ {{FactorName}}+{{Covariate}}, data = {{DataName}}) {{DataName}}.lm3 = lm({{ResponseName}} ~ {{FactorName}}*{{Covariate}}, data = {{DataName}}) anova({{DataName}}.lm1, {{DataName}}.lm2, {{DataName}}.lm3) ``` ```{r} #| label = "glance{{DataName}}.lm" library(broom) glance({{DataName}}.lm1, {{DataName}}.lm2, {{DataName}}.lm3) |> kable(caption=Comparison of three models relating to ANCOVA of {{ResponseName}} using {{FactorName}} for groups and the {{covariate}} Covariate.") ``` ```{r} #| label = "plot{{DataName}}.lm", #| fig.cap = "Residual analysis for {{DataName}}.lm" library(ggfortify) {{DataName}}.lm3 |> autoplot() ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/ancova.Rmd
nNonMissing = function(x){ length(na.omit(x)) # because length() alone would include NAs }
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/nNonMissing.R
for(pkg in pkgList){ if(!do.call(require, list(pkg))) install.packages(pkg) do.call(library, list(pkg)) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/packages.R
PRESS <- function(LinearModel) { return(sum((residuals(LinearModel)/(1 - lm.influence(LinearModel)$hat))^2)) } PredRSquared <- function(LinearModel) { TSS <- sum(anova(LinearModel)$"Sum Sq") return(1 - PRESS(LinearModel)/TSS) }
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/press.R
--- title: "" author: "" date: "" output: html_document: toc: false number_sections: false fig_height: 5 fig_width: 7 ---
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/Templates/simpleYAMLHeader.Rmd
## ----download, eval=FALSE----------------------------------------------------- # chooseCRANmirror(ind=1) # install.packages("BrailleR") ## ----update, eval=FALSE------------------------------------------------------- # chooseCRANmirror(ind=1) # update.packages(ask=FALSE) ## ----start, eval=FALSE-------------------------------------------------------- # library(BrailleR) ## ----SetAuthor, eval=FALSE---------------------------------------------------- # SetAuthor("Jonathan Godfrey")
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/BrailleR.R
--- title: "Getting started with the BrailleR package" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{GettingStarted} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- The BrailleR package has been created for the benefit of blind people wishing to get more out of R than it already offers --- which is actually quite a lot! ## What you need You obviously have R installed or an intention to do so soon if you are reading this document. Aside from R and the add-on packages that BrailleR needs, there are no other software requirements. There are several optional software installations that could make life easier if they are installed before you need them. In order of necessity, they are: ### The document converter --- pandoc BrailleR requires the very useful file converter called pandoc. Get it from the [pandoc download page](https://github.com/jgm/pandoc/releases) ### The principal integrated development environment --- RStudio It is a good idea to install RStudio, even if you can't actually use it as a blind person using screen reading software. The reason is that RStudio installs a few other useful tools that we will make use of by other means. Get it from the [RStudio download page](https://posit.co/download/rstudio-desktop/) ### One programming language --- Python WriteR is a simple text editor written in wxPython that needs Python and wxPython. Unfortunately, they are two separate downloads at present. You do not need this editor so do not install Python unless you are really keen. ## Installing the BrailleR package To use the functionality of the BrailleR package you need to have it installed. The package has several dependencies so installation from the CRAN repository is recommended. This would be done by issuing the following two commands in an R session: ```{r download, eval=FALSE} chooseCRANmirror(ind=1) install.packages("BrailleR") ``` If for some reason you have difficulty with the above commands, you can install the BrailleR package using a zip file version available from a CRAN repository or the latest version on GitHub. From time to time, you should check that you are using the most recent version of the BrailleR package. You can update all installed packages using the commands: ```{r update, eval=FALSE} chooseCRANmirror(ind=1) update.packages(ask=FALSE) ``` Once you've got the package installed, you still need to get it running in your current R session by issuing one last command. When you issue the first of the following lines, the package start messages will also appear. ```{r start, eval=FALSE} library(BrailleR) ``` You're ready to go! ## Why will I use the BrailleR package as a novice? Blind users will want to use the BrailleR package while they are novice R users, but may also want to continue using some of the tools as their skill levels increase. Each of the following reasons for using the BrailleR package have their own example document which goes into more detail. ### BrailleR improves the accessibility of graphical information BrailleR converts standard graphs created by standard R commands into a textual form that can be interpreted by blind students who cannot access the graphs without printing the image to a tactile embosser, or who need the extra text to support any tactile images they do create. At present this is limited to only a few graph types found in base R functionality. [Example 1 shows how histogram](Ex1histograms.html) can be converted to a text representation. ### BrailleR helps gain access to the content of the R console BrailleR makes text output (that is visually appealing) more useful for a blind user who is reliant on synthesized speech or braille output to interpret the results. [Example 2 on data summaries](Ex2BasicNumerical.html) shows this for a data frame. ### BrailleR includes convenience functions Many analyses get repeated over and over again with different variables. Some people like a graphical user interface (GUI) but none of the GUIs developed for R to date are accessible by screen reader users. BrailleR includes some functions which generate pro forma analyses. When these functions are employed, they generate an HTML document that includes the analysis in an easy to use format. The R commands used to create the analysis are stored in an R script file so that a user can modify the commands if changes are necessary. [Example 3 Univariate Description](Ex3UnivariateDescription.html) shows how the UniDesc() function works, and [Example 4 for one response and one factor](Ex4SingleResponseOneGroupingFactor.html) shows how descriptive tools are created before a simple one-way analysis of variance model is fitted. ## Why will I use the BrailleR package if I am not a novice? I think some of the reasons for using the package while you are a novice R user remain relevant to more-experienced users, but perhaps the main reason for continuing to use BrailleR is that of efficiency. The convenience functions give you a starting point for analyses. Behind those convenience functions was an R markdown file that generated the R script and the HTML document. Getting into markdown is a great idea and will not take you long to learn. BrailleR also includes some tools for helping run your R jobs without running R. Experienced users do this all the time so these tools aren't really meant for blind users alone. ## Personalising BrailleR Once you've played with a few examples, you might want to settle on the way you want BrailleR to work for you. You might want your analyses to use your name instead of the default name `BrailleR`. Do this using the `SetAuthor()` function. e.g. ```{r SetAuthor, eval=FALSE} SetAuthor("Jonathan Godfrey") ``` OK, you ought to use your name not mine, but you get the point.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/BrailleR.Rmd
## ----setup, results="hide"---------------------------------------------------- library(BrailleR) ## ----hist, fig.cap="A histogram of 1000 random values from a normal distribution"---- x=rnorm(1000) VI(hist(x))
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/BrailleRHistory.R
--- title: "History of the BrailleR package" author: "A. Jonathan R. Godfrey" date: "14 September 2016" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{History} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- I am one of only two blind people in the world today who gained full-time employment as lecturers of statistics, that is, teaching statistics classes and doing research in theoretical matters as against applying statistical techniques. For years, I tried to keep my blindness separate from my research but I took some opportunities that came my way and heeded the advice of some colleagues to put more energy into improving the ability of blind students around the world to have greater access to statistics courses and statistical understanding. This document shows you a bit more insight into how I (with the help of some useful collaborations) got the BrailleR package to where it is now. ## My background My adult life has been centred around Massey University, initially as an extramural student and then studying on campus. I have undergraduate degrees in Finance and Operations Research, a Master's degree in Operations Research and a PhD in Statistics. I was a Graduate Assistant from 1998 to 2002, and then Assistant Lecturer from January 2003 to June 2004 when I became a Lecturer in Statistics. I was promoted to Senior Lecturer in late 2014. While I don't find it important, I do get asked about the condition that caused my blindness. It is Retinitis Pigmentosa. I do have some light perception, and can make use of it in familiar surroundings for orientation but it has no value to me for reading anything at all. I chose to work with screen reading software when I started university and obtained my first computer because my residual vision at the time was limiting my reading speed. I have therefore operated a computer as a totally blind user throughout my adult life. I did not learn braille until after I completed my PhD. This might seem strange, but there was very little material in a suitable digital format for me to read throughout my student life. Things have changed and I now spend a lot more time reading material and doing programming where the accuracy of braille is absolutely necessary. Braille has now become a very important part of my working life and I have a braille display connected to my computer most of the time. ## getting started I used to keep my research interests separate from my blindness, but I was regularly called upon to discuss how a blind person could study and teach Statistics by many people within New Zealand and occasionally from overseas. In 2009, I attended the Workshop on E-Inclusion in Mathematics and Science (WEIMS09) where I met other people interested in improving the success rates of blind students in the mathematical sciences. My paper was about accessibility of statistics courses, but I did point out the usefulness of R in preference to other tools I had used to that point in time [@Godfrey2009AccessiblePaper]. I discovered that there is room for me to take a leading role in the development of ideas that can help other blind people learn about statistical concepts. I have been invited to all six Summer University events run by the organizers of the International Conference on Computers Helping People (ICCHP), but have been unable to attend twice due to the high cost of transporting me to Europe. I have delivered an introductory workshop on using R at four of these events [@Godfrey2011SU-R; @Godfrey2013SU-R; @Godfrey2014SU-R, and @Godfrey2016SU-R]. Having observed the attendees at the 2011 Summer University as they came to grips with R, I knew there was more I could do to help them and other blind students. I started work on the BrailleR package [@BrailleRPackage] in the second half of 2011 and first proposed it could work for blind users at the Digitisation and E-Inclusion in Mathematics and Science (DEIMS12) workshop held in Tokyo during February 2012 [@Godfrey2012BrailleRPaper]. I wasn't to know the value of another talk I gave at DEIMS12 for another two years; this second talk and associated conference paper focused on how I was using Sweave to create accessible statistical reports for me and more beautifully formatted ones for my statistical consulting clients. [@Godfrey2012PuttingPaper]. I now know that the groundwork I had done contributed to my desire to present my workflow as a workshop at the 5^th^ Summer University in 2014 [@Godfrey2014SU-Sweave]. It also stood me in good stead for the work that followed in the way the package developed in late 2014 and early 2015. ## The starting point example The basic graph that has been used for almost every presentation of the BrailleR package is a histogram. There is a more detailed example, but the following commands create a set of numbers that can be kept for further processing once the graph has been created. It is the re-processing of these numbers that leads to the text description that follows. ```{r setup, results="hide"} library(BrailleR) ``` ```{r hist, fig.cap="A histogram of 1000 random values from a normal distribution"} x=rnorm(1000) VI(hist(x)) ``` This first example showed me what was possible if only I could get a few things sorted out. All histograms are created by a function that stores the results (both numeric and text details) and called the stored set of numbers a "histogram". The main issue is that storing the set of details is not consistent in R, nor is the fact that the stored object gets given a "class" to tell me what type of object it is. This problem haunted me for quite some time because I was talking to the wrong people about the problem; it was time to find people that held the solution instead of talking to the people that would benefit if a solution was found. ## Exposure of the BrailleR package outside the blind community It was obvious to me that getting the word out to the masses about the usefulness of R for blind students and professionals was crucial. I started to compile my notes built up from various posts made to email groups and individuals over the years, as well as the lessons I learned from attendance at the 2^nd^ Summer University event. This led to the eventual publication of my findings in [@GodfreyRJournal]. I know that this was a worthwhile task because it was read by teachers of blind students who were already using R for their courses. One such person tested R and a screen reader and managed to find a solution to a problem posed in @GodfreyRJournal which led to an addendum [@GodfreyErhardtRJournalAddendum]. I presented some of my work via a poster [@Godfrey2013BlindnessPoster] at the NZ Statistical Association conference in Hamilton during November 2013. This 'poster' presentation was developed as a multimedia presentation so that the audience could observe video footage, handle tactile images and be able to talk with me about the BrailleR Project. The plan to get talking with people instead of talking at them worked and I started a really useful collaboration with Paul Murrell from the University of Auckland. His major contributions didn't feature in the BrailleR package for some time, but we're making some really nice progress. Paul is an expert in graphics, especially their creation and manipulation in R. Our discussions about graphics has yielded a few titbits for my own work that have been tested for the package. We've been working on how to make scalable vector graphics that can be augmented to offer blind users greater interactivity and therefore hopefully greater understanding [see @GodfreyMurrell2016TactileGraphsPaper]. ## Review of statistical software I have been asked about the use of R in preference to other statistical software by many blind students, their support staff, and their teachers. Eventually I joined forces with the only other blind lecturer of statistics (Theodor Loots, University of Pretoria) to compare the most commonly used statistical software for its accessibility [@GodfreyLoots2014JSS]. I summarised this paper at the 5^th^ Summer University event [@Godfrey2014SU-StatsSoft], and offered a similar presentation at the 6^th^ Summer University event [@Godfrey2016SU-StatsSoft] with a few updates. ## Attendance at UseR conferences On my way to the 5^th^ Summer University event, I managed to attend the principal conference for R users (UseR!2014) in Los Angeles where I presented my findings [@Godfrey2014BlindUseROral]. Perhaps the most valuable outcome of this conference was the ability to attend a tutorial on use of the knitr package and then talk to its author, Yihui Xie. I'd already seen the knitr package before attending UseR!2014 and implemented it for some of my teaching material by updating the Sweave documents already in use. The real value came in realising what I could probably do if I used R markdown to do a few things I had found very hard using the Sweave way of working. More specifically, generating an R markdown file (Rmd) from an R script was much easier than generating a Sweave file (Rnw). Writing the convenience functions for the package started to look very achievable at this point, and so work began. I dug out some old work that wasn't fit for sharing and converted it to the markdown way of working. There has been sufficient progress in the BrailleR Project that I presented it at UseR!2015 [@Godfrey2015BaseRWeepsOral]. In 2016, I presented the associated work on writing R markdown documents for blind users could be done, and how blind authors might also therefore write their own documents [@GodfreyBilton2016UseROral]. ## The ongoing work The introduction of R markdown to the BrailleR package made a huge difference. I've been able to write enough example code that once I found a friendly postgraduate student (Timothy Bilton) to put some time into it, we've managed to add more convenience functionality. Timothy has improved some of my earlier work and tried a few things of his own. This has left me with the time to add increased functionality for helping blind users get into markdown for themselves. One of my irritations of working with markdown is that everyone else seems to write markdown and check their findings using RStudio, which remains inaccessible for me and other screen reader users. I took an old experiment where I wrote an accessible text editor in wxPython, and with the help of a postgraduate student from Computer Science (James Curtis) we've modified it to process Rmd files. This is now beyond experimental but there is still more to do on making this application truly useful [@GodfreyCurtis2016WriteRPaper]. ## Acknowledgements Contributions to the BrailleR Project are welcome from anyone who has an interest. I will acknowledge assistance in chronological order of the contributions I have received thus far. Greg Snow was the first person to assist when he gave me copies of the original R code and help files for the R2txt functions that were part of his TeachingDemos package [@TeachingDemos]. The Lions clubs of Karlsruhe supported my attendance at the 3^rd^ Summer University event in 2013. This gave me the first opportunity to put the package in front of an audience that I hope will gain from the package's existence. I've already mentioned the following contributors above:Paul Murrell, Yihui Xie, Timothy Bilton, and James Curtis. In December 2016, I was visiting Donal Fitzpatrick at Dublin City University and we were joined by Volker Sorge for a few days. Volker's work in creating an accessible tool for exploration of chemical molecules is now being broadened into statistical graphs. I also need to acknowledge the value of attending the Summer University events. I gain so much from my interactions with the students who attend, the other workshop leaders who gave me feedback, and the other professionals who assist blind students in their own countries. ## References
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/BrailleRHistory.rmd
## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ## ----hist, fig.cap="A histogram of 1000 random values from a normal distribution"---- x=rnorm(1000) VI(hist(x)) ## ----BrailleRHistExample------------------------------------------------------ example(hist)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex1histograms.R
--- title: "The BrailleR package Example 1" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 1: Histograms} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 1. ## Histograms The first and most commonly used example demonstrating the value of the BrailleR package to a blind user is the creation of a histogram. ```{r hist, fig.cap="A histogram of 1000 random values from a normal distribution"} x=rnorm(1000) VI(hist(x)) ``` The VI() command actually calls the VI.histogram() command as the hist() command creates an object of class "histogram". ## Important features The VI() command has added to the impact of issuing the hist() command as the actual graphic is generated for the sighted audience. The blind student can read from the text description so that they can interpret the information that the histogram offers the sighted world. The above example showed the standard implementation of the hist() function. The hist() function of the graphics package does not store the additional arguments that improve the visual attractiveness. The solution (perhaps temporary) is to mask the original function with one included in the BrailleR package that calls the graphics package function, and then adds extra detail for any added plotting arguments. This is best illustrated using the example included in the BrailleR::hist() function. ```{r BrailleRHistExample} example(hist) ``` ## Warning The VI() function is partially reliant on the use of the hist() function that is included in the BrailleR package. If a histogram is created using a command that directly links to the original hist() command found in the graphics package, then the VI() command's output will not be as useful to the blind user. This mainly affects the presentation of the title and axis labels; it should not affect the details of the counts etc. within the histogram itself. This behaviour could arise if the histogram is sought indirectly. If for example, a function offers (as a side effect) to create a histogram, the author of the function may have explicitly stated use of the hist() function from the graphics package using graphics::hist() instead of hist(). Use of graphics::hist() will bypass the BrailleR::hist() function that the VI() command needs. This should not create error messages.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex1histograms.rmd
## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ## ----UseSummary--------------------------------------------------------------- summary(airquality) ## ----UseVI-------------------------------------------------------------------- VI(airquality)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex2BasicNumerical.R
--- title: "The BrailleR package Example 2" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 2: Basic numerical summaries} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 2. ## Basic numerical summaries The standard presentation of a summary of a data frame where each variable is given its own column is difficult for a screen reader user to read as the processing of information is done line by line. For example: ```{r UseSummary} summary(airquality) ``` The VI() command actually calls the VI.data.frame() command. It then processes each variable one by one so that the results are printed variable by variable instead of summary statistic by summary statistic. For example: ```{r UseVI} VI(airquality) ``` ## Important features Note that in this case, the blind student could choose to present the summary of each variable as generated by the VI() command, or the output from the standard summary() command. There is no difference in the information that is ultimately presented in this case.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex2BasicNumerical.rmd
## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ## ----Example, eval=FALSE------------------------------------------------------ # example(UniDesc)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex3UnivariateDescription.R
--- title: "The BrailleR package Example 3" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 3: Univariate Description} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 3. ## Description of a single numeric variable There are many commands needed to get the numeric and graphic summary measures that might be required to collect all relevant information on a single numeric variable. The UniDesc() command has been written as a shortcut for a blind user who wishes to obtain: - the counts of points in the sample that were observed and not observed, - the mean and trimmed mean, - the five number summary: minimum, lower quartile, median, upper quartile, and maximum, - the interquartile range (IQR) and standard deviation, - measures of skewness and kurtosis (thanks to the moments package), - a histogram and/or a boxplot, - a normality (quantile-quantile) plot, - various tests for normality (thanks to the nortest package), and - tests on the significance of the skewness and kurtosis (again, thanks to the moments package). In addition, the blind user may need any/all of the graphs in a variety of formats (png, pdf, eps, or svg), nicely formatted tables for insertion into documents (LaTeX or HTML), and access to the code that generated these graphs and tables (an R script). The UniDesc() function can deliver all of this with minimal effort from the user. In addition, the output HTML file is opened automatically if R is being used interactively, giving the blind user immediate access to the information. The content is presented using sufficiently marked up HTML code including headings and tables so that the blind user can make best use of their screen reading software. All graphs included in the HTML file can be presented using a text description available from the VI() functionality of the BrailleR package. The main output document (HTML) can be viewed by issuing the command ```{r Example, eval=FALSE} example(UniDesc) ``` while running R interactively.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex3UnivariateDescription.rmd
## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ## ----Example, eval=FALSE------------------------------------------------------ # example(OneFactor)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex4SingleResponseOneGroupingFactor.R
--- title: "The BrailleR package Example 4" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 4: A single continuous response with one grouping factor} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` ## Analysis of a single continuous variable with respect to a single grouping factor There are many commands needed to get the numeric and graphic summary measures that might be required to collect all relevant information on a single numeric variable when it might depend on a grouping factor. The OneFactor() command has been written as a shortcut for a blind user who wishes to obtain: - the counts of observations within each group, - the mean, standard deviation and standard error for each group, - boxplots and/or dotplots, - the one-way analysis of variance, and - Tukey's Honestly Significant Difference (HSD) test on the significance of the between group differences. In addition, the blind user may need any/all of the graphs in a variety of formats (png, pdf, eps, or svg), nicely formatted tables for insertion into documents (LaTeX or HTML), and access to the code that generated these graphs and tables (an R script). The OneFactor() function can deliver all of this with minimal effort from the user. In addition, the output HTML file is opened automatically if using R interactively, giving the blind user immediate access to the information. The content is presented using sufficiently marked up HTML code including headings and tables so that the blind user can make best use of their screen reading software. All graphs included in the HTML file can be presented using a text description available from the VI() functionality of the BrailleR package. The main output document (HTML) can be viewed by issuing the command ```{r Example, eval=FALSE} example(OneFactor) ``` while running R interactively.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/Ex4SingleResponseOneGroupingFactor.rmd
## ---- setupLibrarys, message = FALSE, warnings = FALSE------------------------ library(ggplot2) library(BrailleR) ## ----Basic plot Describe------------------------------------------------------ basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() Describe(basicPlot) ## ----VI implicit call--------------------------------------------------------- basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() basicPlot ## ----VI explicit call--------------------------------------------------------- VI(basicPlot) ## ----VI geomHLine, fig.show='hide'-------------------------------------------- hline <- ggplot(mtcars, aes(mpg, cyl)) + geom_hline(yintercept = 5) hline ## ----VI geomPoint, fig.show='hide'-------------------------------------------- point <- ggplot(mtcars, aes(mpg, cyl)) + geom_point() point ## ----VI geomBar, fig.show='hide'---------------------------------------------- bar <- ggplot(mtcars, aes(mpg)) + geom_histogram() bar ## ----VI geomLine, fig.show='hide'--------------------------------------------- line <- ggplot(mtcars, aes(mpg, wt)) + geom_line() line ## ----VI geomBoxplot, fig.show='hide'------------------------------------------ boxplot <- ggplot(mtcars, aes(mpg, as.factor(cyl))) + geom_boxplot() boxplot ## ----VI geomSmooth, fig.show='hide'------------------------------------------- smooth <- ggplot(mtcars, aes(mpg, wt)) + geom_smooth() smooth ## ----VI geomRibbon, fig.show='hide'------------------------------------------- ribbon <- ggplot(diamonds, aes(x = carat, y = price)) + geom_area(aes(y = price)) ribbon ## ----VI geomBlank, fig.show='hide'-------------------------------------------- blank <- ggplot(BOD, aes(x = demand, y = Time)) + geom_line() + expand_limits(x = c(15, 23, 6), y = c(30)) blank ## ----svg geom line, eval = FALSE, echo=FALSE---------------------------------- # line <- ggplot(mtcars, aes(mpg, wt)) + # geom_line() # MakeAccessibleSVG(line) ## ----svg geom point, eval = FALSE, echo=FALSE--------------------------------- # point <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + # geom_point() # MakeAccessibleSVG(point) ## ----svg geom bar, eval = FALSE, echo=FALSE----------------------------------- # bar <- ggplot(iris, aes(Sepal.Length)) + # geom_bar() # MakeAccessibleSVG(bar) ## ---- svg geom smooth, eval = FALSE, echo=FALSE------------------------------- # smooth <- ggplot(mtcars, aes(mpg, wt)) + # geom_smooth() # MakeAccessibleSVG(smooth)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/ExploringGraphs.R
--- title: "Exploring Graphs" author: "James Thompson" date: 16/02/2023 bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Exploring Graphs} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- *Problem* Much of statistics course work in your first year will revolve around making and interpreting graphs. Now for a sighted user R and R studio with ggplot2 etc it is quite a straight forward procedure. However without the use of sight this becomes a challenge. *Solution* In BrailleR there are three avenues that can be taken to fix this they are: [Describe] is for learning, [VI] is about getting quick information and [SVG Plots] are for a detailed dive into a plot. Each of these are designed to serve the user and give them potential to 'view' the information a graph has to offer. *Note* All of the code below is run after these 'setup' functions ```{r, setupLibrarys, message = FALSE, warnings = FALSE} library(ggplot2) library(BrailleR) ``` # Describe This function will take a graph object and give you the non contextual information about the graph layers. It is designed as a learning tool to help you understand what a particular graph is trying to show you. It also provides applicable information about how this graph type works in ggplot. An example of this would be something like this ```{r Basic plot Describe} basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() Describe(basicPlot) ``` As can be seen there is a title a general description and then some r hints. This structure is the same for all Describe output expect for when using it in `MakeAccessibleSVG()`. However more can be found about that here: [How to use] ## Multiple layers If you have multiple layers in the plot it will default to asking you what layers you want. You can always tell it which layer to describe by giving the layer number or vector of numbers to the `whichLayer` argument. However more about this can be read in the function documentation. # VI This function can be thought of as a text 'Visual Inspection' of the graph. It has enough information that you might be able to draw some conclusions however it mostly will tell you about the layout of the graph. This function can also be used to investigate non graph objects like lm and aov etc. Only the graph application will be discussed here. ## ggplot There is full support here for many layers as well as faceted displays (multiple plots in one graph object). For every graph there will be a few lines at the start telling you the title subtitle what the axes are and there tick marks. This is the same across all of the graph printouts. It is the individual layer sections can be quite different. The VI function is built into the print function for ggplot objects. This means anytime you have BrailleR loaded and try to display a ggplot it will give you the text output. This effect can be seen below ```{r VI implicit call} basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() basicPlot ``` However you can also easily call it explicitly without having to print the graph. ```{r VI explicit call} VI(basicPlot) ``` Below is not only a list of the supported Geom but also a little explanation about there printouts. ### GeomHLine ```{r VI geomHLine, fig.show='hide'} hline <- ggplot(mtcars, aes(mpg, cyl)) + geom_hline(yintercept = 5) hline ``` As this is quite a simple geom it is quite a simple printout. It will tell you how many lines and at what height they are at. ### GeomPoint ```{r VI geomPoint, fig.show='hide'} point <- ggplot(mtcars, aes(mpg, cyl)) + geom_point() point ``` Information will include here the number of points and the shape. There is also a percentage of approximately how many points can be seen. This is used to help you understand the over plotting. This is only effective for when the points sizes are not too big (size < 18). Don't worry it will only show you the percentage if it is accurate. ### GeomBar / GeomCol ```{r VI geomBar, fig.show='hide'} bar <- ggplot(mtcars, aes(mpg)) + geom_histogram() bar ``` Even though there is a geom_histogram, geom_bar and geom_col in the backend of ggplot it is the same. So for the VI they are treated all pretty much the same. There will be information just on the number of bars displayed. ### GeomLine ```{r VI geomLine, fig.show='hide'} line <- ggplot(mtcars, aes(mpg, wt)) + geom_line() line ``` Very similar to the hline it will tell you about how many lines there are. Then for each line it will tell you the number of points that make up the line. ### GeomBoxplot ```{r VI geomBoxplot, fig.show='hide'} boxplot <- ggplot(mtcars, aes(mpg, as.factor(cyl))) + geom_boxplot() boxplot ``` As a boxplot is effectively a 5 number summary with outliers this printout will include all of that information. It shall include this summary for each boxplot in the layer. ### GeomSmooth ```{r VI geomSmooth, fig.show='hide'} smooth <- ggplot(mtcars, aes(mpg, wt)) + geom_smooth() smooth ``` This output tell you the method used to get the smoothed curve and the confidence interval level which is set. It also tells you what percentage of the graph is covered by the CI. This information can be used to quickly gauge how confident the graph is ### GeomRibbon / GeomArea ```{r VI geomRibbon, fig.show='hide'} ribbon <- ggplot(diamonds, aes(x = carat, y = price)) + geom_area(aes(y = price)) ribbon ``` Once again this layer gives you some information about the layers data. It will tell you whether it is bound on the y or x axis and then if it is constant or non constant width. For it to be bound on the y axis means that it covers the whole range of x and vice versa for y. It includes some widths and centers throughout 5 points in the layer. The width will either be bottom to top for y bound or left to right for x bound. It also includes the area covered statistic found in the smooth layer. ### GeomBlank ```{r VI geomBlank, fig.show='hide'} blank <- ggplot(BOD, aes(x = demand, y = Time)) + geom_line() + expand_limits(x = c(15, 23, 6), y = c(30)) blank ``` GeomBlank is made by the expand_limits function. It is a normal layer like all the others however it just doesn't have any points to be displayed. So what this VI does is explain the effect that this layer had on the limits. It shall tell you how much larger the x and y axis are. ## Base Base R graphics support is kept in here and does work to some extant. However it should be considered deprecated and replaced by the ggplot graphics. There is support for the base plots: - Boxplot - Dotplot - Histogram # SVG Plots SVG plots in BrailleR are used create webpages that a user can explore by using arrow keys and some basic navigation buttons. The `MakeAccessibleSVG()` function is the easiest way to do this. You simply pass it a graph object and it will create the webpage and load it for you in your default browser. The functions that `MakeAccessibleSVG()` uses to create SVGs are `SVGThis()`, `AddXML()` and `BrowseSVG()`. These are available to use but really shouldn't be needed. There is one last function `ViewSVG()`. This will bring up a webpage that has a list and links of all of the svg webpages available in the current working directory. Below is the code used to make the example ```r plot.example = ggplot(mtcars, aes(wt, mpg)) + geom_point() + geom_smooth() MakeAccessibleSVG(plot.example) ``` [example SVG webpage](../rawHTML/plot.example-SVG.html) ## How to use Using the function is as simple as passing a graph object to `MakeAccessibleSVG()` like this: ```r simplePlot = ggplot(mtcars, aes(mpg, wt)) + geom_point() MakeAccessibleSVG(simplePlot) ``` On completion of the function it will open the webpage in your default web browser. On the webpage there are 4 sections. 1. The graph 2. VI output 3. List of keys to help explore graph 4. Describe output. The VI and Describe output is simply there as convenience. The VI will look exactly the same as the output to console. However the describe will look slightly different with that first title line being changed to just the geom type header. This should help with it being navigable on the webpage. ### Graph structure I will explain a little bit about the structure of the graph and how you can explore it. The explanations will speak of trees, sub trees, parents, children and nodes. Hopefully you are familiar with what these words mean in this context. A quick summary is to think of a family tree. The root is Adam and Eve. Each of there descendant have there subtrees. Your parents are the final subtree for your branch and you and your siblings are all children nodes (assuming you don't have kids yet). Every person is a node. For these accessible svgs the graph is the root. Each section has its own sub tree. The order of subtrees goes: 1. title (if present) 2. x axis 3. y axis 4. first ggplot layer 5. second ggplot layer 6. etc... There can be an arbitrary number of ggplot layers. These are just added in line ### How to navigate Navigation around the graph should be somewhat intuitive. Up arrow to go to you parent. Down arrow to go to first child. Left and right to go to your siblings. Other useful keys are: **X** which will enable the descriptive mode. This simply means you can get more / different information at any particular node you are at. Note that not all nodes will have this extra information so don't be worry if it doesn't do anything. **A** This activate keyboard exploration so once you have focuses on the SVG you press A and then are good to with exploring using the arrow keys. ## ggplot All of the readouts of plots numbers will be formatted and rounded to help make it easier to read. Less geoms are supported as SVGs than are supported by VI. This is mostly because they have not yet been developed. In general there will be no more than 5 children nodes to the geom tree. You might be able to go into each child node of the geom to see more information or there could be a summary of the section at each child node. Below is geom specific information ### Geom_line ```{r svg geom line, eval = FALSE, echo=FALSE} line <- ggplot(mtcars, aes(mpg, wt)) + geom_line() MakeAccessibleSVG(line) ``` For this layer there we be sub trees for each line. Within each individual line subtree if the line is disjoint there will be more subtrees for each continuous section of the line. Once you are looking at either the continuous section or the whole section you can click through to actually look at the line. If there are more than 5 lines then it will summarizes them. If there are 5 or less then you can press through and individually see the line start and finish locations. ### Geom_Point ```{r svg geom point, eval = FALSE, echo=FALSE} point <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() MakeAccessibleSVG(point) ``` Geom points is a lot simpler. Depending on the number of points the information the children have will be different. If there are more than 5 points it will display a summary of the points. If there are 5 or less points you will get a summary of each individual point. It is worth noting that due to current technical difficulties the points will not be highlighted at all. More information can be found at [Github issue](https://github.com/ajrgodfrey/BrailleR/issues/90) ### Geom_Bar ```{r svg geom bar, eval = FALSE, echo=FALSE} bar <- ggplot(iris, aes(Sepal.Length)) + geom_bar() MakeAccessibleSVG(bar) ``` This geom is also quite simple. There will be a children node for each of the bars in the plot. There is some slight differences between the histograms and the bar charts. For continuous x axis graphs you get information about the width of the bar its height and the density. For categorical you will simple get the the location on x axis and the value on the y axis. There is no summary as of this moment regardless of how many bars are in the plot. ### Geom_Smooth ```{r, svg geom smooth, eval = FALSE, echo=FALSE} smooth <- ggplot(mtcars, aes(mpg, wt)) + geom_smooth() MakeAccessibleSVG(smooth) ``` For the smoother the graph will be split into 5 sections no matter how few underlying data points there are. This means there are 5 children to the geoms node. Each child will either have one or two children. The first child will be the line and the second child would be the confidence interval if it is present in the graph (This is determined by the `se` argument in `geom_smooth()`) You can however see simple information about the line and confidence interval from the section nodes description. ## Base R Like with VI there is some support for base r graphics however all of this support could be considered deprecated. These are: - Dotplot - Boxplot - Scatterplot - Histogram - Tsplot
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/ExploringGraphs.Rmd
--- title: "Getting started with the WriteR application" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{IntroWriteR} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ## Introduction The WriteR application was written to support use of R markdown and the BrailleR package. It is a Python script making use of wxPython to help build the graphic user interface (GUI) in such a way that it works for screen reader users. The script is in the BrailleR package, but it cannot run unless the user has both Python and wxPython installed. Two commands have been included in the BrailleR package to help Windows users obtain installation files for them. ## Getting Python and wxPython (Windows users only) Issue the following commands at the R prompt `library(BrailleR)` `GetPython()` `GetWxPython()` These commands automatically download the installation files and start the installation process going. The downloaded files will be saved in your MyBrailleR folder. You will need to follow the instructions and answer questions that arise whenever you install new software. These are reputable installation files from the primary sites for Python and wxPython. Windows and any security software you might have should know that, but you can never tell! You will probably need to let Windows know it is OK to install the software in the default location. That pop-up might not appear as the window with focus so if things look like they're going slowly, look around for the pop-up window. Once you have completed both installations, you are ready to go. You shouldn't need those installation files again, but keep them just in case. They will have been saved in your `MyBrailleR` folder. ## Opening WriteR from BrailleR Opening WriteR is as easy as typing WriteR! Well almost. You have the option of specifying a filename; if that file exists, it gets opened for you, and if it doesn't exist, then it gets created with a few lines already included at the top to help get you started. Try: `WriteR("MyFirst.Rmd")` ## What can I do with WriteR? The window you are in has a number of menus, a status bar at the bottom and a big space in the middle for your work. Take a quick look at those menus; some will look familiar because they are common to many Windows applications. The file you have open is a markdown file. It is just text which is why it is so easy to read. The file extension of `Rmd` means it is an R markdown file. There are several flavours of markdown in common use, but they are practically all the same except for some very minor differences. A markdown file can be converted into many file formats for distribution. These include HTML, pdf, Microsoft Word, Open Office, and a number of different slide presentation formats. Let's make the HTML file now. ## Our first HTML file Making your first HTML file is as easy as hitting a single key, or using one of the options in the `Build` menu. The variety of options are the commonly used ones in RStudio. Navigate to the current working directory using your file browser. To find out where that is, type `getwd()` back in the R window. You should see the file `MyFirst.Rmd` and once you have built it, the associated HTML file. Open the HTML file and see how the markdown has been rendered. You may need to switch back and forth between the WriteR window and your browser to compare the plain text and the beautiful HTML. Now edit the Rmd file in WriteR to your heart's content.
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/IntroWriteR.Rmd
## ----GetLibraries------------------------------------------------------------- library(BrailleR) library(ggplot2) dsmall = diamonds[1:100,] ## ----g1----------------------------------------------------------------------- g1 = qplot(carat, price, data = diamonds) # summary(g1) g1 # VI(g1) ### automatic since BrailleR v0.32.0 ## ----g2----------------------------------------------------------------------- g2 = qplot(carat, price, data = dsmall, colour = color) # summary(g2) g2 ## ----g3----------------------------------------------------------------------- g3 = qplot(carat, price, data = dsmall, shape = cut) # summary(g3) g3 ## ----g4----------------------------------------------------------------------- # to get semi-transparent points g4 = qplot(carat, price, data = diamonds, alpha = I(1/100)) # summary(g4) g4 ## ----g5----------------------------------------------------------------------- # to add a smoother (default is loess for n<1000) g5 = qplot(carat, price, data = dsmall, geom = c("point", "smooth")) # summary(g5) g5 #! g5a = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), span = 1) library(splines) #! g5b = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), method = "lm") #! g5c = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), method = "lm", formula = y ~ ns(x,5)) ## ----g6, include=FALSE-------------------------------------------------------- # continuous v categorical g6 = qplot(color, price / carat, data = diamonds, geom = "jitter", alpha = I(1 / 50)) # summary(g6) g6 # VI(g6) ### automatic since BrailleR v0.32.0 g6a = qplot(color, price / carat, data = diamonds, geom = "boxplot") # summary(g6a) g6a ## ----g7----------------------------------------------------------------------- # univariate plots g7a = qplot(carat, data = diamonds, geom = "histogram") # summary(g7a) g7a g7b = qplot(carat, data = diamonds, geom = "histogram", binwidth = 1, xlim = c(0,3)) g7b g7c = qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.1, xlim = c(0,3)) g7c g7d = qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.01, xlim = c(0,3)) # summary(g7d) g7d ## ----g8, include=FALSE-------------------------------------------------------- g8 = qplot(carat, data = diamonds, geom = "density") # summary(g8) g8 ## ----g9, include=FALSE-------------------------------------------------------- # data is separated by implication using the following... g9 = qplot(carat, data = diamonds, geom = "density", colour = color) # summary(g9) g9 g10 = qplot(carat, data = diamonds, geom = "histogram", fill = color) # summary(g10) g10 ## ----g11---------------------------------------------------------------------- # bar charts for categorical variable g11a = qplot(color, data = diamonds) # summary(g11a) g11a g11b = qplot(color, data = diamonds, geom = "bar") # summary(g11b) g11b g12a = qplot(color, data = diamonds, geom = "bar", weight = carat) # summary(g12a) g12a g12b = qplot(color, data = diamonds, geom = "bar", weight = carat) + scale_y_continuous("carat") # summary(g12b) g12b ## ----g13---------------------------------------------------------------------- # time series plots g13a = qplot(date, unemploy / pop, data = economics, geom = "line") # summary(g13a) g13a g13b = qplot(date, uempmed, data = economics, geom = "line") # summary(g13b) g13b ## ----g14, include=FALSE------------------------------------------------------- # path plots year <- function(x) as.POSIXlt(x)$year + 1900 g14a = qplot(unemploy / pop, uempmed, data = economics, geom = c("point", "path")) # summary(g14a) g14a #g14b = qplot(unemploy / pop, uempmed, data = economics, geom = "path", colour = year(date)) + scale_area() #summary(g14b) ## ----g15, include=FALSE------------------------------------------------------- # facets is the ggplot term for trellis' panels g15a = qplot(carat, data = diamonds, facets = color ~ ., geom = "histogram", binwidth = 0.1, xlim = c(0, 3)) # summary(g15a) g15a g15b = qplot(carat, ..density.., data = diamonds, facets = color ~ ., geom = "histogram", binwidth = 0.1, xlim = c(0, 3)) # summary(g15b) g15b ## ----g16---------------------------------------------------------------------- # rescaling of the axes g16 = qplot(carat, price, data = dsmall, log = "xy") # summary(g16) g16 ## ----g17, include=FALSE------------------------------------------------------- # Facets syntax without a "." before the "~" causes grief g17 = qplot(displ, hwy, data=mpg, facets =~ year) + geom_smooth() # summary(g17) g17
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/qplot.R
--- title: Testing the VI.ggplot() within the BrailleR package" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{qplot} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- This vignette contained many more plots in its initial development. The set has been cut back considerably to offer meaningful testing only, and because much of the material was moved over to a book called [BrailleR in Action](https://R-Resources.massey.ac.nz/BrailleRInAction/). Doing so also had an advantage of speeding up the package creation, testing, and installation. N.B. the commands here are either exact copies of the commands presented in Wickham (2009) or some minor alterations to them. Notably, some code given in the book no longer works. This is given a `#!` The `ggplot2` package has a `summary` method that often but not always offers something to show that things have changed from one plot to another. Summary commands are included below but commented out. ```{r GetLibraries} library(BrailleR) library(ggplot2) dsmall = diamonds[1:100,] ``` ```{r g1} g1 = qplot(carat, price, data = diamonds) # summary(g1) g1 # VI(g1) ### automatic since BrailleR v0.32.0 ``` If the user does not actually plot the graph, they can still find out what it will look like once it is plotted by using the `VI()` command on the graph object. This became unnecessary from version 0.32.0 of BrailleR. N.B. All `VI()` commands can now be deleted from this document. ```{r g2} g2 = qplot(carat, price, data = dsmall, colour = color) # summary(g2) g2 ``` ```{r g3} g3 = qplot(carat, price, data = dsmall, shape = cut) # summary(g3) g3 ``` ```{r g4} # to get semi-transparent points g4 = qplot(carat, price, data = diamonds, alpha = I(1/100)) # summary(g4) g4 ``` ```{r g5} # to add a smoother (default is loess for n<1000) g5 = qplot(carat, price, data = dsmall, geom = c("point", "smooth")) # summary(g5) g5 #! g5a = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), span = 1) library(splines) #! g5b = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), method = "lm") #! g5c = qplot(carat, price, data = dsmall, geom = c("point", "smooth"), method = "lm", formula = y ~ ns(x,5)) ``` ```{r g6, include=FALSE} # continuous v categorical g6 = qplot(color, price / carat, data = diamonds, geom = "jitter", alpha = I(1 / 50)) # summary(g6) g6 # VI(g6) ### automatic since BrailleR v0.32.0 g6a = qplot(color, price / carat, data = diamonds, geom = "boxplot") # summary(g6a) g6a ``` ```{r g7} # univariate plots g7a = qplot(carat, data = diamonds, geom = "histogram") # summary(g7a) g7a g7b = qplot(carat, data = diamonds, geom = "histogram", binwidth = 1, xlim = c(0,3)) g7b g7c = qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.1, xlim = c(0,3)) g7c g7d = qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.01, xlim = c(0,3)) # summary(g7d) g7d ``` ```{r g8, include=FALSE} g8 = qplot(carat, data = diamonds, geom = "density") # summary(g8) g8 ``` ```{r g9, include=FALSE} # data is separated by implication using the following... g9 = qplot(carat, data = diamonds, geom = "density", colour = color) # summary(g9) g9 g10 = qplot(carat, data = diamonds, geom = "histogram", fill = color) # summary(g10) g10 ``` ```{r g11} # bar charts for categorical variable g11a = qplot(color, data = diamonds) # summary(g11a) g11a g11b = qplot(color, data = diamonds, geom = "bar") # summary(g11b) g11b g12a = qplot(color, data = diamonds, geom = "bar", weight = carat) # summary(g12a) g12a g12b = qplot(color, data = diamonds, geom = "bar", weight = carat) + scale_y_continuous("carat") # summary(g12b) g12b ``` ```{r g13} # time series plots g13a = qplot(date, unemploy / pop, data = economics, geom = "line") # summary(g13a) g13a g13b = qplot(date, uempmed, data = economics, geom = "line") # summary(g13b) g13b ``` ```{r g14, include=FALSE} # path plots year <- function(x) as.POSIXlt(x)$year + 1900 g14a = qplot(unemploy / pop, uempmed, data = economics, geom = c("point", "path")) # summary(g14a) g14a #g14b = qplot(unemploy / pop, uempmed, data = economics, geom = "path", colour = year(date)) + scale_area() #summary(g14b) ``` ```{r g15, include=FALSE} # facets is the ggplot term for trellis' panels g15a = qplot(carat, data = diamonds, facets = color ~ ., geom = "histogram", binwidth = 0.1, xlim = c(0, 3)) # summary(g15a) g15a g15b = qplot(carat, ..density.., data = diamonds, facets = color ~ ., geom = "histogram", binwidth = 0.1, xlim = c(0, 3)) # summary(g15b) g15b ``` ```{r g16} # rescaling of the axes g16 = qplot(carat, price, data = dsmall, log = "xy") # summary(g16) g16 ``` ```{r g17, include=FALSE} # Facets syntax without a "." before the "~" causes grief g17 = qplot(displ, hwy, data=mpg, facets =~ year) + geom_smooth() # summary(g17) g17 ```
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/doc/qplot.Rmd
chooseCRANmirror(ind=1) update.packages(ask=FALSE, binary=TRUE)
/scratch/gouwar.j/cran-all/cranData/BrailleR/inst/scripts/UpdatePackages.R
--- title: "Getting started with the BrailleR package" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{GettingStarted} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- The BrailleR package has been created for the benefit of blind people wishing to get more out of R than it already offers --- which is actually quite a lot! ## What you need You obviously have R installed or an intention to do so soon if you are reading this document. Aside from R and the add-on packages that BrailleR needs, there are no other software requirements. There are several optional software installations that could make life easier if they are installed before you need them. In order of necessity, they are: ### The document converter --- pandoc BrailleR requires the very useful file converter called pandoc. Get it from the [pandoc download page](https://github.com/jgm/pandoc/releases) ### The principal integrated development environment --- RStudio It is a good idea to install RStudio, even if you can't actually use it as a blind person using screen reading software. The reason is that RStudio installs a few other useful tools that we will make use of by other means. Get it from the [RStudio download page](https://posit.co/download/rstudio-desktop/) ### One programming language --- Python WriteR is a simple text editor written in wxPython that needs Python and wxPython. Unfortunately, they are two separate downloads at present. You do not need this editor so do not install Python unless you are really keen. ## Installing the BrailleR package To use the functionality of the BrailleR package you need to have it installed. The package has several dependencies so installation from the CRAN repository is recommended. This would be done by issuing the following two commands in an R session: ```{r download, eval=FALSE} chooseCRANmirror(ind=1) install.packages("BrailleR") ``` If for some reason you have difficulty with the above commands, you can install the BrailleR package using a zip file version available from a CRAN repository or the latest version on GitHub. From time to time, you should check that you are using the most recent version of the BrailleR package. You can update all installed packages using the commands: ```{r update, eval=FALSE} chooseCRANmirror(ind=1) update.packages(ask=FALSE) ``` Once you've got the package installed, you still need to get it running in your current R session by issuing one last command. When you issue the first of the following lines, the package start messages will also appear. ```{r start, eval=FALSE} library(BrailleR) ``` You're ready to go! ## Why will I use the BrailleR package as a novice? Blind users will want to use the BrailleR package while they are novice R users, but may also want to continue using some of the tools as their skill levels increase. Each of the following reasons for using the BrailleR package have their own example document which goes into more detail. ### BrailleR improves the accessibility of graphical information BrailleR converts standard graphs created by standard R commands into a textual form that can be interpreted by blind students who cannot access the graphs without printing the image to a tactile embosser, or who need the extra text to support any tactile images they do create. At present this is limited to only a few graph types found in base R functionality. [Example 1 shows how histogram](Ex1histograms.html) can be converted to a text representation. ### BrailleR helps gain access to the content of the R console BrailleR makes text output (that is visually appealing) more useful for a blind user who is reliant on synthesized speech or braille output to interpret the results. [Example 2 on data summaries](Ex2BasicNumerical.html) shows this for a data frame. ### BrailleR includes convenience functions Many analyses get repeated over and over again with different variables. Some people like a graphical user interface (GUI) but none of the GUIs developed for R to date are accessible by screen reader users. BrailleR includes some functions which generate pro forma analyses. When these functions are employed, they generate an HTML document that includes the analysis in an easy to use format. The R commands used to create the analysis are stored in an R script file so that a user can modify the commands if changes are necessary. [Example 3 Univariate Description](Ex3UnivariateDescription.html) shows how the UniDesc() function works, and [Example 4 for one response and one factor](Ex4SingleResponseOneGroupingFactor.html) shows how descriptive tools are created before a simple one-way analysis of variance model is fitted. ## Why will I use the BrailleR package if I am not a novice? I think some of the reasons for using the package while you are a novice R user remain relevant to more-experienced users, but perhaps the main reason for continuing to use BrailleR is that of efficiency. The convenience functions give you a starting point for analyses. Behind those convenience functions was an R markdown file that generated the R script and the HTML document. Getting into markdown is a great idea and will not take you long to learn. BrailleR also includes some tools for helping run your R jobs without running R. Experienced users do this all the time so these tools aren't really meant for blind users alone. ## Personalising BrailleR Once you've played with a few examples, you might want to settle on the way you want BrailleR to work for you. You might want your analyses to use your name instead of the default name `BrailleR`. Do this using the `SetAuthor()` function. e.g. ```{r SetAuthor, eval=FALSE} SetAuthor("Jonathan Godfrey") ``` OK, you ought to use your name not mine, but you get the point.
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/BrailleR.Rmd
--- title: "History of the BrailleR package" author: "A. Jonathan R. Godfrey" date: "14 September 2016" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{History} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- I am one of only two blind people in the world today who gained full-time employment as lecturers of statistics, that is, teaching statistics classes and doing research in theoretical matters as against applying statistical techniques. For years, I tried to keep my blindness separate from my research but I took some opportunities that came my way and heeded the advice of some colleagues to put more energy into improving the ability of blind students around the world to have greater access to statistics courses and statistical understanding. This document shows you a bit more insight into how I (with the help of some useful collaborations) got the BrailleR package to where it is now. ## My background My adult life has been centred around Massey University, initially as an extramural student and then studying on campus. I have undergraduate degrees in Finance and Operations Research, a Master's degree in Operations Research and a PhD in Statistics. I was a Graduate Assistant from 1998 to 2002, and then Assistant Lecturer from January 2003 to June 2004 when I became a Lecturer in Statistics. I was promoted to Senior Lecturer in late 2014. While I don't find it important, I do get asked about the condition that caused my blindness. It is Retinitis Pigmentosa. I do have some light perception, and can make use of it in familiar surroundings for orientation but it has no value to me for reading anything at all. I chose to work with screen reading software when I started university and obtained my first computer because my residual vision at the time was limiting my reading speed. I have therefore operated a computer as a totally blind user throughout my adult life. I did not learn braille until after I completed my PhD. This might seem strange, but there was very little material in a suitable digital format for me to read throughout my student life. Things have changed and I now spend a lot more time reading material and doing programming where the accuracy of braille is absolutely necessary. Braille has now become a very important part of my working life and I have a braille display connected to my computer most of the time. ## getting started I used to keep my research interests separate from my blindness, but I was regularly called upon to discuss how a blind person could study and teach Statistics by many people within New Zealand and occasionally from overseas. In 2009, I attended the Workshop on E-Inclusion in Mathematics and Science (WEIMS09) where I met other people interested in improving the success rates of blind students in the mathematical sciences. My paper was about accessibility of statistics courses, but I did point out the usefulness of R in preference to other tools I had used to that point in time [@Godfrey2009AccessiblePaper]. I discovered that there is room for me to take a leading role in the development of ideas that can help other blind people learn about statistical concepts. I have been invited to all six Summer University events run by the organizers of the International Conference on Computers Helping People (ICCHP), but have been unable to attend twice due to the high cost of transporting me to Europe. I have delivered an introductory workshop on using R at four of these events [@Godfrey2011SU-R; @Godfrey2013SU-R; @Godfrey2014SU-R, and @Godfrey2016SU-R]. Having observed the attendees at the 2011 Summer University as they came to grips with R, I knew there was more I could do to help them and other blind students. I started work on the BrailleR package [@BrailleRPackage] in the second half of 2011 and first proposed it could work for blind users at the Digitisation and E-Inclusion in Mathematics and Science (DEIMS12) workshop held in Tokyo during February 2012 [@Godfrey2012BrailleRPaper]. I wasn't to know the value of another talk I gave at DEIMS12 for another two years; this second talk and associated conference paper focused on how I was using Sweave to create accessible statistical reports for me and more beautifully formatted ones for my statistical consulting clients. [@Godfrey2012PuttingPaper]. I now know that the groundwork I had done contributed to my desire to present my workflow as a workshop at the 5^th^ Summer University in 2014 [@Godfrey2014SU-Sweave]. It also stood me in good stead for the work that followed in the way the package developed in late 2014 and early 2015. ## The starting point example The basic graph that has been used for almost every presentation of the BrailleR package is a histogram. There is a more detailed example, but the following commands create a set of numbers that can be kept for further processing once the graph has been created. It is the re-processing of these numbers that leads to the text description that follows. ```{r setup, results="hide"} library(BrailleR) ``` ```{r hist, fig.cap="A histogram of 1000 random values from a normal distribution"} x=rnorm(1000) VI(hist(x)) ``` This first example showed me what was possible if only I could get a few things sorted out. All histograms are created by a function that stores the results (both numeric and text details) and called the stored set of numbers a "histogram". The main issue is that storing the set of details is not consistent in R, nor is the fact that the stored object gets given a "class" to tell me what type of object it is. This problem haunted me for quite some time because I was talking to the wrong people about the problem; it was time to find people that held the solution instead of talking to the people that would benefit if a solution was found. ## Exposure of the BrailleR package outside the blind community It was obvious to me that getting the word out to the masses about the usefulness of R for blind students and professionals was crucial. I started to compile my notes built up from various posts made to email groups and individuals over the years, as well as the lessons I learned from attendance at the 2^nd^ Summer University event. This led to the eventual publication of my findings in [@GodfreyRJournal]. I know that this was a worthwhile task because it was read by teachers of blind students who were already using R for their courses. One such person tested R and a screen reader and managed to find a solution to a problem posed in @GodfreyRJournal which led to an addendum [@GodfreyErhardtRJournalAddendum]. I presented some of my work via a poster [@Godfrey2013BlindnessPoster] at the NZ Statistical Association conference in Hamilton during November 2013. This 'poster' presentation was developed as a multimedia presentation so that the audience could observe video footage, handle tactile images and be able to talk with me about the BrailleR Project. The plan to get talking with people instead of talking at them worked and I started a really useful collaboration with Paul Murrell from the University of Auckland. His major contributions didn't feature in the BrailleR package for some time, but we're making some really nice progress. Paul is an expert in graphics, especially their creation and manipulation in R. Our discussions about graphics has yielded a few titbits for my own work that have been tested for the package. We've been working on how to make scalable vector graphics that can be augmented to offer blind users greater interactivity and therefore hopefully greater understanding [see @GodfreyMurrell2016TactileGraphsPaper]. ## Review of statistical software I have been asked about the use of R in preference to other statistical software by many blind students, their support staff, and their teachers. Eventually I joined forces with the only other blind lecturer of statistics (Theodor Loots, University of Pretoria) to compare the most commonly used statistical software for its accessibility [@GodfreyLoots2014JSS]. I summarised this paper at the 5^th^ Summer University event [@Godfrey2014SU-StatsSoft], and offered a similar presentation at the 6^th^ Summer University event [@Godfrey2016SU-StatsSoft] with a few updates. ## Attendance at UseR conferences On my way to the 5^th^ Summer University event, I managed to attend the principal conference for R users (UseR!2014) in Los Angeles where I presented my findings [@Godfrey2014BlindUseROral]. Perhaps the most valuable outcome of this conference was the ability to attend a tutorial on use of the knitr package and then talk to its author, Yihui Xie. I'd already seen the knitr package before attending UseR!2014 and implemented it for some of my teaching material by updating the Sweave documents already in use. The real value came in realising what I could probably do if I used R markdown to do a few things I had found very hard using the Sweave way of working. More specifically, generating an R markdown file (Rmd) from an R script was much easier than generating a Sweave file (Rnw). Writing the convenience functions for the package started to look very achievable at this point, and so work began. I dug out some old work that wasn't fit for sharing and converted it to the markdown way of working. There has been sufficient progress in the BrailleR Project that I presented it at UseR!2015 [@Godfrey2015BaseRWeepsOral]. In 2016, I presented the associated work on writing R markdown documents for blind users could be done, and how blind authors might also therefore write their own documents [@GodfreyBilton2016UseROral]. ## The ongoing work The introduction of R markdown to the BrailleR package made a huge difference. I've been able to write enough example code that once I found a friendly postgraduate student (Timothy Bilton) to put some time into it, we've managed to add more convenience functionality. Timothy has improved some of my earlier work and tried a few things of his own. This has left me with the time to add increased functionality for helping blind users get into markdown for themselves. One of my irritations of working with markdown is that everyone else seems to write markdown and check their findings using RStudio, which remains inaccessible for me and other screen reader users. I took an old experiment where I wrote an accessible text editor in wxPython, and with the help of a postgraduate student from Computer Science (James Curtis) we've modified it to process Rmd files. This is now beyond experimental but there is still more to do on making this application truly useful [@GodfreyCurtis2016WriteRPaper]. ## Acknowledgements Contributions to the BrailleR Project are welcome from anyone who has an interest. I will acknowledge assistance in chronological order of the contributions I have received thus far. Greg Snow was the first person to assist when he gave me copies of the original R code and help files for the R2txt functions that were part of his TeachingDemos package [@TeachingDemos]. The Lions clubs of Karlsruhe supported my attendance at the 3^rd^ Summer University event in 2013. This gave me the first opportunity to put the package in front of an audience that I hope will gain from the package's existence. I've already mentioned the following contributors above:Paul Murrell, Yihui Xie, Timothy Bilton, and James Curtis. In December 2016, I was visiting Donal Fitzpatrick at Dublin City University and we were joined by Volker Sorge for a few days. Volker's work in creating an accessible tool for exploration of chemical molecules is now being broadened into statistical graphs. I also need to acknowledge the value of attending the Summer University events. I gain so much from my interactions with the students who attend, the other workshop leaders who gave me feedback, and the other professionals who assist blind students in their own countries. ## References
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/BrailleRHistory.rmd
--- title: "The BrailleR package Example 1" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 1: Histograms} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 1. ## Histograms The first and most commonly used example demonstrating the value of the BrailleR package to a blind user is the creation of a histogram. ```{r hist, fig.cap="A histogram of 1000 random values from a normal distribution"} x=rnorm(1000) VI(hist(x)) ``` The VI() command actually calls the VI.histogram() command as the hist() command creates an object of class "histogram". ## Important features The VI() command has added to the impact of issuing the hist() command as the actual graphic is generated for the sighted audience. The blind student can read from the text description so that they can interpret the information that the histogram offers the sighted world. The above example showed the standard implementation of the hist() function. The hist() function of the graphics package does not store the additional arguments that improve the visual attractiveness. The solution (perhaps temporary) is to mask the original function with one included in the BrailleR package that calls the graphics package function, and then adds extra detail for any added plotting arguments. This is best illustrated using the example included in the BrailleR::hist() function. ```{r BrailleRHistExample} example(hist) ``` ## Warning The VI() function is partially reliant on the use of the hist() function that is included in the BrailleR package. If a histogram is created using a command that directly links to the original hist() command found in the graphics package, then the VI() command's output will not be as useful to the blind user. This mainly affects the presentation of the title and axis labels; it should not affect the details of the counts etc. within the histogram itself. This behaviour could arise if the histogram is sought indirectly. If for example, a function offers (as a side effect) to create a histogram, the author of the function may have explicitly stated use of the hist() function from the graphics package using graphics::hist() instead of hist(). Use of graphics::hist() will bypass the BrailleR::hist() function that the VI() command needs. This should not create error messages.
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/Ex1histograms.rmd
--- title: "The BrailleR package Example 2" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 2: Basic numerical summaries} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 2. ## Basic numerical summaries The standard presentation of a summary of a data frame where each variable is given its own column is difficult for a screen reader user to read as the processing of information is done line by line. For example: ```{r UseSummary} summary(airquality) ``` The VI() command actually calls the VI.data.frame() command. It then processes each variable one by one so that the results are printed variable by variable instead of summary statistic by summary statistic. For example: ```{r UseVI} VI(airquality) ``` ## Important features Note that in this case, the blind student could choose to present the summary of each variable as generated by the VI() command, or the output from the standard summary() command. There is no difference in the information that is ultimately presented in this case.
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/Ex2BasicNumerical.rmd
--- title: "The BrailleR package Example 3" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 3: Univariate Description} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` # The BrailleR package Example 3. ## Description of a single numeric variable There are many commands needed to get the numeric and graphic summary measures that might be required to collect all relevant information on a single numeric variable. The UniDesc() command has been written as a shortcut for a blind user who wishes to obtain: - the counts of points in the sample that were observed and not observed, - the mean and trimmed mean, - the five number summary: minimum, lower quartile, median, upper quartile, and maximum, - the interquartile range (IQR) and standard deviation, - measures of skewness and kurtosis (thanks to the moments package), - a histogram and/or a boxplot, - a normality (quantile-quantile) plot, - various tests for normality (thanks to the nortest package), and - tests on the significance of the skewness and kurtosis (again, thanks to the moments package). In addition, the blind user may need any/all of the graphs in a variety of formats (png, pdf, eps, or svg), nicely formatted tables for insertion into documents (LaTeX or HTML), and access to the code that generated these graphs and tables (an R script). The UniDesc() function can deliver all of this with minimal effort from the user. In addition, the output HTML file is opened automatically if R is being used interactively, giving the blind user immediate access to the information. The content is presented using sufficiently marked up HTML code including headings and tables so that the blind user can make best use of their screen reading software. All graphs included in the HTML file can be presented using a text description available from the VI() functionality of the BrailleR package. The main output document (HTML) can be viewed by issuing the command ```{r Example, eval=FALSE} example(UniDesc) ``` while running R interactively.
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/Ex3UnivariateDescription.rmd
--- title: "The BrailleR package Example 4" author: "A. Jonathan R. Godfrey" bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Example 4: A single continuous response with one grouping factor} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(fig.width=7, fig.height=5, comment="") library(BrailleR) ``` ## Analysis of a single continuous variable with respect to a single grouping factor There are many commands needed to get the numeric and graphic summary measures that might be required to collect all relevant information on a single numeric variable when it might depend on a grouping factor. The OneFactor() command has been written as a shortcut for a blind user who wishes to obtain: - the counts of observations within each group, - the mean, standard deviation and standard error for each group, - boxplots and/or dotplots, - the one-way analysis of variance, and - Tukey's Honestly Significant Difference (HSD) test on the significance of the between group differences. In addition, the blind user may need any/all of the graphs in a variety of formats (png, pdf, eps, or svg), nicely formatted tables for insertion into documents (LaTeX or HTML), and access to the code that generated these graphs and tables (an R script). The OneFactor() function can deliver all of this with minimal effort from the user. In addition, the output HTML file is opened automatically if using R interactively, giving the blind user immediate access to the information. The content is presented using sufficiently marked up HTML code including headings and tables so that the blind user can make best use of their screen reading software. All graphs included in the HTML file can be presented using a text description available from the VI() functionality of the BrailleR package. The main output document (HTML) can be viewed by issuing the command ```{r Example, eval=FALSE} example(OneFactor) ``` while running R interactively.
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/Ex4SingleResponseOneGroupingFactor.rmd
--- title: "Exploring Graphs" author: "James Thompson" date: 16/02/2023 bibliography: BrailleRPublications.bib vignette: > %\VignetteIndexEntry{Exploring Graphs} %\VignetteEngine{knitr::rmarkdown} output: knitr:::html_vignette --- *Problem* Much of statistics course work in your first year will revolve around making and interpreting graphs. Now for a sighted user R and R studio with ggplot2 etc it is quite a straight forward procedure. However without the use of sight this becomes a challenge. *Solution* In BrailleR there are three avenues that can be taken to fix this they are: [Describe] is for learning, [VI] is about getting quick information and [SVG Plots] are for a detailed dive into a plot. Each of these are designed to serve the user and give them potential to 'view' the information a graph has to offer. *Note* All of the code below is run after these 'setup' functions ```{r, setupLibrarys, message = FALSE, warnings = FALSE} library(ggplot2) library(BrailleR) ``` # Describe This function will take a graph object and give you the non contextual information about the graph layers. It is designed as a learning tool to help you understand what a particular graph is trying to show you. It also provides applicable information about how this graph type works in ggplot. An example of this would be something like this ```{r Basic plot Describe} basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() Describe(basicPlot) ``` As can be seen there is a title a general description and then some r hints. This structure is the same for all Describe output expect for when using it in `MakeAccessibleSVG()`. However more can be found about that here: [How to use] ## Multiple layers If you have multiple layers in the plot it will default to asking you what layers you want. You can always tell it which layer to describe by giving the layer number or vector of numbers to the `whichLayer` argument. However more about this can be read in the function documentation. # VI This function can be thought of as a text 'Visual Inspection' of the graph. It has enough information that you might be able to draw some conclusions however it mostly will tell you about the layout of the graph. This function can also be used to investigate non graph objects like lm and aov etc. Only the graph application will be discussed here. ## ggplot There is full support here for many layers as well as faceted displays (multiple plots in one graph object). For every graph there will be a few lines at the start telling you the title subtitle what the axes are and there tick marks. This is the same across all of the graph printouts. It is the individual layer sections can be quite different. The VI function is built into the print function for ggplot objects. This means anytime you have BrailleR loaded and try to display a ggplot it will give you the text output. This effect can be seen below ```{r VI implicit call} basicPlot <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() basicPlot ``` However you can also easily call it explicitly without having to print the graph. ```{r VI explicit call} VI(basicPlot) ``` Below is not only a list of the supported Geom but also a little explanation about there printouts. ### GeomHLine ```{r VI geomHLine, fig.show='hide'} hline <- ggplot(mtcars, aes(mpg, cyl)) + geom_hline(yintercept = 5) hline ``` As this is quite a simple geom it is quite a simple printout. It will tell you how many lines and at what height they are at. ### GeomPoint ```{r VI geomPoint, fig.show='hide'} point <- ggplot(mtcars, aes(mpg, cyl)) + geom_point() point ``` Information will include here the number of points and the shape. There is also a percentage of approximately how many points can be seen. This is used to help you understand the over plotting. This is only effective for when the points sizes are not too big (size < 18). Don't worry it will only show you the percentage if it is accurate. ### GeomBar / GeomCol ```{r VI geomBar, fig.show='hide'} bar <- ggplot(mtcars, aes(mpg)) + geom_histogram() bar ``` Even though there is a geom_histogram, geom_bar and geom_col in the backend of ggplot it is the same. So for the VI they are treated all pretty much the same. There will be information just on the number of bars displayed. ### GeomLine ```{r VI geomLine, fig.show='hide'} line <- ggplot(mtcars, aes(mpg, wt)) + geom_line() line ``` Very similar to the hline it will tell you about how many lines there are. Then for each line it will tell you the number of points that make up the line. ### GeomBoxplot ```{r VI geomBoxplot, fig.show='hide'} boxplot <- ggplot(mtcars, aes(mpg, as.factor(cyl))) + geom_boxplot() boxplot ``` As a boxplot is effectively a 5 number summary with outliers this printout will include all of that information. It shall include this summary for each boxplot in the layer. ### GeomSmooth ```{r VI geomSmooth, fig.show='hide'} smooth <- ggplot(mtcars, aes(mpg, wt)) + geom_smooth() smooth ``` This output tell you the method used to get the smoothed curve and the confidence interval level which is set. It also tells you what percentage of the graph is covered by the CI. This information can be used to quickly gauge how confident the graph is ### GeomRibbon / GeomArea ```{r VI geomRibbon, fig.show='hide'} ribbon <- ggplot(diamonds, aes(x = carat, y = price)) + geom_area(aes(y = price)) ribbon ``` Once again this layer gives you some information about the layers data. It will tell you whether it is bound on the y or x axis and then if it is constant or non constant width. For it to be bound on the y axis means that it covers the whole range of x and vice versa for y. It includes some widths and centers throughout 5 points in the layer. The width will either be bottom to top for y bound or left to right for x bound. It also includes the area covered statistic found in the smooth layer. ### GeomBlank ```{r VI geomBlank, fig.show='hide'} blank <- ggplot(BOD, aes(x = demand, y = Time)) + geom_line() + expand_limits(x = c(15, 23, 6), y = c(30)) blank ``` GeomBlank is made by the expand_limits function. It is a normal layer like all the others however it just doesn't have any points to be displayed. So what this VI does is explain the effect that this layer had on the limits. It shall tell you how much larger the x and y axis are. ## Base Base R graphics support is kept in here and does work to some extant. However it should be considered deprecated and replaced by the ggplot graphics. There is support for the base plots: - Boxplot - Dotplot - Histogram # SVG Plots SVG plots in BrailleR are used create webpages that a user can explore by using arrow keys and some basic navigation buttons. The `MakeAccessibleSVG()` function is the easiest way to do this. You simply pass it a graph object and it will create the webpage and load it for you in your default browser. The functions that `MakeAccessibleSVG()` uses to create SVGs are `SVGThis()`, `AddXML()` and `BrowseSVG()`. These are available to use but really shouldn't be needed. There is one last function `ViewSVG()`. This will bring up a webpage that has a list and links of all of the svg webpages available in the current working directory. Below is the code used to make the example ```r plot.example = ggplot(mtcars, aes(wt, mpg)) + geom_point() + geom_smooth() MakeAccessibleSVG(plot.example) ``` [example SVG webpage](../rawHTML/plot.example-SVG.html) ## How to use Using the function is as simple as passing a graph object to `MakeAccessibleSVG()` like this: ```r simplePlot = ggplot(mtcars, aes(mpg, wt)) + geom_point() MakeAccessibleSVG(simplePlot) ``` On completion of the function it will open the webpage in your default web browser. On the webpage there are 4 sections. 1. The graph 2. VI output 3. List of keys to help explore graph 4. Describe output. The VI and Describe output is simply there as convenience. The VI will look exactly the same as the output to console. However the describe will look slightly different with that first title line being changed to just the geom type header. This should help with it being navigable on the webpage. ### Graph structure I will explain a little bit about the structure of the graph and how you can explore it. The explanations will speak of trees, sub trees, parents, children and nodes. Hopefully you are familiar with what these words mean in this context. A quick summary is to think of a family tree. The root is Adam and Eve. Each of there descendant have there subtrees. Your parents are the final subtree for your branch and you and your siblings are all children nodes (assuming you don't have kids yet). Every person is a node. For these accessible svgs the graph is the root. Each section has its own sub tree. The order of subtrees goes: 1. title (if present) 2. x axis 3. y axis 4. first ggplot layer 5. second ggplot layer 6. etc... There can be an arbitrary number of ggplot layers. These are just added in line ### How to navigate Navigation around the graph should be somewhat intuitive. Up arrow to go to you parent. Down arrow to go to first child. Left and right to go to your siblings. Other useful keys are: **X** which will enable the descriptive mode. This simply means you can get more / different information at any particular node you are at. Note that not all nodes will have this extra information so don't be worry if it doesn't do anything. **A** This activate keyboard exploration so once you have focuses on the SVG you press A and then are good to with exploring using the arrow keys. ## ggplot All of the readouts of plots numbers will be formatted and rounded to help make it easier to read. Less geoms are supported as SVGs than are supported by VI. This is mostly because they have not yet been developed. In general there will be no more than 5 children nodes to the geom tree. You might be able to go into each child node of the geom to see more information or there could be a summary of the section at each child node. Below is geom specific information ### Geom_line ```{r svg geom line, eval = FALSE, echo=FALSE} line <- ggplot(mtcars, aes(mpg, wt)) + geom_line() MakeAccessibleSVG(line) ``` For this layer there we be sub trees for each line. Within each individual line subtree if the line is disjoint there will be more subtrees for each continuous section of the line. Once you are looking at either the continuous section or the whole section you can click through to actually look at the line. If there are more than 5 lines then it will summarizes them. If there are 5 or less then you can press through and individually see the line start and finish locations. ### Geom_Point ```{r svg geom point, eval = FALSE, echo=FALSE} point <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() MakeAccessibleSVG(point) ``` Geom points is a lot simpler. Depending on the number of points the information the children have will be different. If there are more than 5 points it will display a summary of the points. If there are 5 or less points you will get a summary of each individual point. It is worth noting that due to current technical difficulties the points will not be highlighted at all. More information can be found at [Github issue](https://github.com/ajrgodfrey/BrailleR/issues/90) ### Geom_Bar ```{r svg geom bar, eval = FALSE, echo=FALSE} bar <- ggplot(iris, aes(Sepal.Length)) + geom_bar() MakeAccessibleSVG(bar) ``` This geom is also quite simple. There will be a children node for each of the bars in the plot. There is some slight differences between the histograms and the bar charts. For continuous x axis graphs you get information about the width of the bar its height and the density. For categorical you will simple get the the location on x axis and the value on the y axis. There is no summary as of this moment regardless of how many bars are in the plot. ### Geom_Smooth ```{r, svg geom smooth, eval = FALSE, echo=FALSE} smooth <- ggplot(mtcars, aes(mpg, wt)) + geom_smooth() MakeAccessibleSVG(smooth) ``` For the smoother the graph will be split into 5 sections no matter how few underlying data points there are. This means there are 5 children to the geoms node. Each child will either have one or two children. The first child will be the line and the second child would be the confidence interval if it is present in the graph (This is determined by the `se` argument in `geom_smooth()`) You can however see simple information about the line and confidence interval from the section nodes description. ## Base R Like with VI there is some support for base r graphics however all of this support could be considered deprecated. These are: - Dotplot - Boxplot - Scatterplot - Histogram - Tsplot
/scratch/gouwar.j/cran-all/cranData/BrailleR/vignettes/ExploringGraphs.Rmd