multcompView/0000755000176200001440000000000014414551362012752 5ustar liggesusersmultcompView/NAMESPACE0000644000176200001440000000210514414525367014175 0ustar liggesusers# Generated by roxygen2: do not edit by hand S3method(extract_p,TukeyHSD) S3method(extract_p,default) S3method(extract_p,mc) S3method(plot,multcompLetters) S3method(plot,multcompTs) S3method(print,multcompLetters) export(extract_p) export(multcompBoxplot) export(multcompLetters) export(multcompLetters2) export(multcompLetters3) export(multcompLetters4) export(multcompTs) export(plotBoxes) export(plotLetters) export(plotTs) export(vec2mat) export(vec2mat2) importFrom(graphics,lines) importFrom(graphics,par) importFrom(graphics,plot) importFrom(graphics,polygon) importFrom(graphics,rect) importFrom(graphics,text) importFrom(grid,convertHeight) importFrom(grid,convertWidth) importFrom(grid,gpar) importFrom(grid,grid.newpage) importFrom(grid,grid.text) importFrom(grid,grobHeight) importFrom(grid,grobWidth) importFrom(grid,popViewport) importFrom(grid,pushViewport) importFrom(grid,textGrob) importFrom(grid,unit) importFrom(grid,viewport) importFrom(stats,TukeyHSD) importFrom(stats,aov) importFrom(stats,model.frame) importFrom(stats,terms) multcompView/README0000644000176200001440000000055614414525367013646 0ustar liggesusers1. Put any C/C++/Fortran code in 'src' 2. If you have compiled code, add a .First.lib() function in 'R' to load the shared library 3. Edit the help file skeletons in 'man' 4. Run R CMD build to create the index files 5. Run R CMD check to check the package 6. Run R CMD build to make the package file Read "Writing R Extensions" for more information. multcompView/man/0000755000176200001440000000000014414525367013533 5ustar liggesusersmultcompView/man/plot.multcompTs.Rd0000644000176200001440000001454214414525367017154 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.multcompTs.R \name{plot.multcompTs} \alias{plot.multcompTs} \title{plot multcomp graphics} \usage{ \method{plot}{multcompTs}( x, horizontal = FALSE, col = 1:6, type = c("Ts", "boxes"), orientation = c("standard", "reverse"), add = FALSE, at, width, fig = c(0, 1, 0, 1), lwd = 3, label.levels = if (add) NA else 0.05, label.groups = NA, T.base = 0.4, ... ) } \arguments{ \item{x}{an object of class 'multcompTs' or 'multcompLetters'.} \item{horizontal}{A logical scalar indicating whether the list of items compared reads left to right (horizontal = TRUE) or top to bottom (horizontal = FALSE). If this multcomp graphic accompanies boxplots for different levels or groups compared, the 'boxplot' argument 'horizontal' is the negation of the multcomp plot 'horizontal' argument.} \item{col}{The color for each group of items or factor levels. The colors will cross the different items or factor levels and will therefore have the orientation specified via 'horizontal'. If the number of columns exceeds length(col), col is recycled. For alternative choices for col, see "Color Specification" in the \code{\link{par}} help page.} \item{type}{An alternative display for either multcompTs or multcompLetters is 'boxes' (or rectangles). If type="boxes" with "multcompTs", the "base(s)" of each "T" will be indicated by a triangle.} \item{orientation}{The "standard" orientation has the 'multcompTs' pointing towards the names of the items or factor levels; with the "reverse" orientation, the bases of the "Ts" point away. By default, the names are on the left or below unless the mean of the relevant 'fig' range is less than 0.5.} \item{add}{TRUE to add to an existing plot; FALSE to start a new plot. The names of the factor levels or items compared will be plotted only if add=FALSE.} \item{at}{A numeric vector or matrix or a list with components "at" and "width". If a list, both components must be either a numeric vector or matrix. The numeric vector "at" (whether the function argument or "at" component of the "at" list) must be either a numeric vector or matrix giving the locations where the "Ts" or "Letters" graphics should be drawn. length(at) is 1, 2 or 3 times the number of the number of factor levels or items compared. If length(at) is twice the number of levels or items compared, it gives the range of the display for that level; the base of a "T" will be at the midpoint. If length(at) is three times the number of items compared, the intermediate number will be the center of the base of the "T".} \item{width}{A numeric vector or matrix with as many rows as "Ts" or "groups" and with up to three columns. With one column, it will be the "center" of the plot range for that group. With two columns, they will delimit the range. With three, they will provide "bottom", "center", and "top" of the range for that set of grouping indicators. If "at" is a list, the argument "width" is ignored and is taken from the list "at".} \item{fig}{A numerical vector of the form 'c(x1, x2, y1, y2)' giving the coordinates of the figure region in the display region of the plot device, as described on the \code{\link{par}} help page.} \item{lwd}{width of line to connect elements of "T" graphics that might not otherwise be connected.} \item{label.levels}{NA for no labels or distance away from the plot for the labels as a proportion of the plot range.} \item{label.groups}{NA for no labels or distance away from the plot for the labels as a proportion of the plot range.} \item{T.base}{A numeric scalar giving the proportion of the available space devoted to the base of the Ts; used only when type="Ts".} \item{...}{graphical parameters can be given as described on the \code{\link{plot}} help page or for plot.multcompLetters as describe on the \code{\link[grid]{gpar}} help page.} } \value{ A list with two components: \item{at }{ A matrix with three columns giving the middle and extremes of the display for each of the factor levels or items compared. } \item{width }{ A matrix with as many rows as "Ts" or comparitor levels and with two columns giving the plot range for that comparitor level. } } \description{ Plot graphic(s) for multcompTs or multcompLetters objects } \details{ The requested graphic is either plotted by itself or added to an existing plot as specified by the arguments. The placement can be controlled by 'fig' and 'at'. The fontsize and fontface of a plot of a multcompLetters object with 'type = "Letters"' can be adjusted as describe on the \code{\link[grid]{gpar}} help page. } \examples{ ## ## plot(multcompTs(...)) ## dif4 <- c(.1, .02, .03, 1) names(dif4) <- c("A-B", "A-C", "B-C", "A-D") (mcT4 <- multcompTs(dif4)) # Standard plot, base of "Ts" point left mcT4.1 <- plot(mcT4, label.groups=0.05) # Redo using "at" = list plot(mcT4, label.groups=0.05, at=mcT4.1) # Same plot with group labels closer to the figure plot(mcT4, label.groups=0.02) # Base of "Ts" point right plot(mcT4, label.groups=TRUE, orientation="r") # Base of "Ts" point down plot(mcT4, horizontal=TRUE, label.groups=0.05) # Base of "Ts" point up plot(mcT4, horizontal=TRUE, label.groups=0.05, orientation="r") # Same 4 plots but with boxes & triangles, not Ts plot(mcT4, label.groups=0.05, type="b") plot(mcT4, label.groups=0.05, orientation="r", type="b") plot(mcT4, horizontal=TRUE, label.groups=0.05, type="b") plot(mcT4, horizontal=TRUE, label.groups=0.05, orientation="r", type="b") ## ## plot(multcompLetters(...)) ## # ... using dif4 from above (mcL4 <- multcompLetters(dif4, Letters=LETTERS)) # Standard plot \dontrun{ # Requires (grid) mcL4.1 <- plot(mcL4, label.groups=0.05) # Redo using "at" = list plot(mcL4, label.groups=0.05, at=mcL4.1) # With bold face and larger font plot(mcL4, label.groups=0.05, fontsize=28, fontface="bold") # Horizontal rather than vertical plot(mcL4, horizontal=TRUE, label.groups=0.05) } # Same as boxes rather than letters plot(mcL4, label.groups=0.05, type="b") plot(mcL4, horizontal=TRUE, label.groups=0.05, type="b") } \seealso{ \code{\link{multcompTs}} \code{\link{multcompLetters}} \code{\link{multcompBoxplot}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} multcompView/man/plotLetters.Rd0000644000176200001440000001231214414525367016342 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotLetters.R \name{plotLetters} \alias{plotLetters} \title{plot multcomp displays} \usage{ plotLetters( obj, at, horizontal, col, add, label.levels, font.family = "mono", fig = par("fig"), mar = par("mar"), ... ) } \arguments{ \item{obj}{a matrix describing which levels (rows) will be plotted with which groups (columns). For plotTs and plotBoxes, obj is a matrix of numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if that "letter" (group or column of obj) is to be plotted with that level (row of obj).} \item{at}{an array with one row for each level and 3 columns giving low, middle and high levels for the display for that level.} \item{horizontal}{A logical scalar indicating whether the list of items compared reads left to right (horizontal = TRUE) or top to bottom (horizontal = FALSE). If this multcomp graphic accompanies boxplots for different levels or groups compared, the 'boxplot' argument 'horizontal' is the negation of the multcomp plot 'horizontal' argument.} \item{col}{The color for each group of items or factor levels. The colors will cross the different items or factor levels and will therefore have the orientation specified via 'horizontal'. If the number of columns exceeds length(col), col is recycled. For alternative choices for col, see "Color Specification" in the \code{\link{par}} help page.} \item{add}{TRUE to add to an existing plot; FALSE to start a new plot. The names of the factor levels or items compared will be plotted only if add=FALSE.} \item{label.levels}{Distance from the plot region to print the names of the levels as a proportion of the plot range; NA for no level labels.} \item{font.family}{character string naming the font family used by "plotLetters". This function plots the different "Letters" in different colors by plotting one color at a time. It's currently not smart enough to align the letters properly except by assuming a mono-spaced font.} \item{fig}{figure region = (x0, x1, y0, y1) as a proportion of the device region.} \item{mar}{margin = (lower, left, upper, right) in lines.} \item{...}{graphical parameters can be given as described on the \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page.} \item{width}{an array with one row for each group of levels in the display and 3 columns giving low, middle and high levels for the display for that group.} \item{lwd}{line width for the display outline.} \item{label.groups}{Distance from the plot region to print the names of the groups as a proportion of the plot range; NA for no level labels.} \item{T.base}{A numeric scalar giving the proportion of the available space devoted to the base of the Ts.} \item{orientation}{If 'reversed', the base(s) of each "T" or traingle indicating the master level(s) of that "undifferentiated class" will point right or up (depending on horizontal) rather than down or left.} } \value{ "Done" } \description{ Helper functions for plot.multcompTs and plot.multcompLetters. These not intended to be called directly and are hidden in a namespace. You can use 'getAnywhere' to see them. } \details{ The requested graphic is either plotted by itself or added to an existing plot as specified by the arguments. "plotTs" and "plotBoxes" use traditional R graphics and will not be discussed further here. "plotLetters" uses 'grid' graphics, because it seems to provide more support for controlling the side-by-side placement of "Letters" of possibly different colors and widths. The "Letters" display will be positioned in the "plot region" defined by fig and mar, assuming the entire device region is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, 1, 0, 1), this makes the plot region 3.7 lines wide. With the default mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this contradictory negative width, and centers the plot at the midpoint of h0 = fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = fig[4]-mar[3]/37. The "Letters" for the different levels compared are rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) else c(v0, v1). With "n" levels compared and at.rng = range(at[, "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to match At.rng; if(diff(At.rng)<=0), an error message is issued. Meanwhile, the "Letters" are centered at the midpoint of W.rng = if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the argument "width" used by plotTs and plotBoxes is not used (and not even accepted) by plotLetters. If(label.levels), these are positioned in the midpoint of the right margin in the "W" direction. } \examples{ # Designed to be called from plot.multcompTs # or plot.multcompLetters, NOT directly by users. } \seealso{ \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} \keyword{internal} multcompView/man/vec2mat.Rd0000644000176200001440000000465114414525367015371 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/vec2mat.R \name{vec2mat} \alias{vec2mat} \title{Convert a vector with hyphenated names into a matrix.} \usage{ vec2mat(x, sep = "-") } \arguments{ \item{x}{Either (1) a vector with hyphenated names indicating pairs of factor levels, groups or items that are and are not significantly different or (2) a matrix indicating same. If x is already a matrix, it is checked for symmetry. NAs are not allowed.} \item{sep}{"strsplit" character to apply to names(x).} } \value{ A symmetrix matrix of the same class as the input with names obtained from unique(strsplit(names(x))). All nonspecified elements will be 1 if class(x) is numeric, FALSE if logical and "" if character. Used by the functions 'multcompLetters' and 'multcompTs'. } \description{ Convert a vector with hypehnated names into a symmetric matrix with names obtained from vect2mat2(names(x)). } \details{ x must have names each of which contains exactly one hyphen; if not, vec2mat issues an error message. If the same comparison is present multiple times, the last value is used; no check is made for duplicates. } \examples{ dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("a-b", "a-c", "b-c") vec2mat(dif3) dif3. <- 1:3 names(dif3.) <- c("a-b", "a-c", "b-c") vec2mat(dif3.) dif.ch <- c("this",'is','it') names(dif.ch) <- c("a-b", "a-c", "b-c") vec2mat(dif.ch) vec2mat(array(1, dim=c(2,2))) \dontshow{ try(vec2mat(array(1:24, dim=2:4)))# must be 2-d try(vec2mat(array(1:6, dim=2:3)))# must be square try(vec2mat(array(1:4, dim=c(2,2))))# must be symmetric try(vec2mat(array(1, dim=c(2,2)))) # diag should be 0 try(vec2mat(array(TRUE, dim=c(2,2)))) # diag should be FALSE try(vec2mat(array("a", dim=c(2,2)))) # diag should be "" try(vec2mat(c(1:3, NA))) # NAs not allowed try(vec2mat(1:3))# Error: No names errVec2 <- 1:3 names(errVec2) <- c("a", "b-a", "b-c") try(vec2mat(errVec2))# Error: missing hyphen (sep character) errVec3 <- 1:3 names(errVec3) <- c("a-c", "b-a", "b-c-d") try(vec2mat(errVec3)) # Error: multiple hyphens (sep characters) dif4 <- 1:4 names(dif4) <- c("a-b", "a-c", "b-c", "b-a") # Both "b-a" and "a-b" specified; # use the latest. vec2mat(dif4) } } \seealso{ \code{\link{multcompLetters}} \code{\link{multcompTs}} } \author{ Spencer Graves } \keyword{array} \keyword{manip} multcompView/man/multcompTs.Rd0000644000176200001440000001147514414525367016201 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multcompTs.R \name{multcompTs} \alias{multcompTs} \title{"T" depiction of undiffentiated classes} \usage{ multcompTs(x, compare = "<", threshold = 0.05, sep = ".") } \arguments{ \item{x}{One of the following: (1) A square, symmetric matrix with row names. (2) A vector with hyphenated names, which identify individual items or factor levels after "strsplit(..., '-')". (3) An object of class "dist". If x (or x[1]) is not already of class "logical", it is replaced with do.call(compare, list(x, threshold)), which by default converts numbers (typically p-values) less than 0.05 to TRUE and everything else to FALSE. If x is a matrix, its diagonal must be or must convert to FALSE.} \item{compare}{function or binary operator; not used if class(x) is "logical".} \item{threshold}{Second (reference) argument to "compare".} \item{sep}{Concatonation character for names of objects with identical similarity / dissimilarity patterns. The output of multcompTs is matrix for which the number of rows = (number of columns + number of uses of the "sep" character).} } \value{ An object of class "multcompTs", which is a matrix of values -1, 0, 1, with one row for each level compared and one column for each "T", read as follows: 1 = base of the "T" represented by that column, 0 = level(s) not significantly different, and (-1) = leves(s) significantly different. If two or more levels have the same pattern of significant and insignificant differences, they are combined into a single column that can be represented by a "T" with multiple bases. The column name will be a character string concatonating all row names with "1" in that column separated by the "sep" character. Thus, the matrix should have as many 1's as it has rows. Also, the lower triangular portion should have as many "-1's" as there are "TRUE" (e.g., significant) differences among the comparisons. } \description{ Convert a logical vector or a vector of p-values or a correlation or distance matrix into a matrix with an associated visual display to show whether the differences between items exceed a threshold. Designed for use with the output of functions like TukeyHSD, diststats, simint, simtest, csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. } \details{ Produces a matrix of class "multcompTs", describing the "undifferentiated classes" that identify the other factor levels or items that are not distinct or not significantly different from the "base" of the "T"; if two or more levels have the same pattern of significant differences, the two are combined into one "T" with two "bases". The resulting T's are similar to the "undifferentiated classes" discussed by Donaghue (2004). } \examples{ ## ## 0. Conference presentation comparing Ts and Letters ## dir(system.file('doc', package='multcompView'), pattern='\\\\.pdf$', full.name=TRUE) ## ## 1. logical vector indicating different pairs ## dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("a-b", "a-c", "b-c") multcompTs(dif3) ## ## 2. numeric vector indicating statistical significance ## dif4 <- c(.01, .02, .03, 1) names(dif4) <- c("a-b", "a-c", "b-d", "a-d") (diff4.T <- multcompTs(dif4)) plot(diff4.T) ## ## 3. Distance matrix ## dJudge <- dist(USJudgeRatings) dJt <- multcompTs(dJudge, compare='>', threshold = median(dJudge)) # comparison of 43 judges; compact but undecipherable: plot(dJt, cex.axis=.5) x <- array(1:9, dim=c(3,3), dimnames=list(LETTERS[1:3], NULL) ) d3 <- dist(x) dxTs <- multcompTs(d3, compare=">", threshold=2) plot(dxTs) d3d <- dist(x, diag=TRUE) dxdTs <- multcompTs(d3d, compare=">", threshold=2) \dontshow{stopifnot(} all.equal(dxTs, dxdTs) \dontshow{)} d3u <- dist(x, upper=TRUE) dxuTs <- multcompTs(d3d, compare=">", threshold=2) \dontshow{stopifnot(} all.equal(dxTs, dxuTs) \dontshow{)} ## ## 4. cor matrix ## set.seed(4) x100 <- matrix(rnorm(100), ncol=5, dimnames=list(NULL, LETTERS[1:5]) ) cx <- cor(x100) cxTs <- multcompTs(abs(cx), threshold=.3) plot(cxTs) } \references{ John R. Donaghue (2004) "Implementing Shaffer's multiple comparison procedure for a large number of groups", pp. 1-23 in Benjamini, Bretz and Sarkar (eds) Recent Developments in Multiple Comparison Procedures (Institute of Mathematical Statistics Lecture Notes-Monograph Series vol. 47) Spencer Graves and Hans-Peter Piepho (2006) "Simple Visualizations of Paired Comparisons", \href{../doc/VisualizingPairedComparisons.pdf}{\code{vignette("VisualizingPairedComparisons", package = "multcompView")}} } \seealso{ \code{\link{multcompBoxplot}} \code{\link{multcompLetters}} \code{\link{plot.multcompTs}} \code{\link{vec2mat}} \code{\link{dist}} } \author{ Spencer Graves and Hans-Peter Piepho } \keyword{dplot} multcompView/man/multcompLetters.Rd0000644000176200001440000001730114414530347017221 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multcompLetters.R \name{multcompLetters} \alias{multcompLetters} \alias{multcompLetters2} \alias{multcompLetters3} \alias{multcompLetters4} \title{Letter summary of similarities and differences} \usage{ multcompLetters( x, compare = "<", threshold = 0.05, Letters = c(letters, LETTERS, "."), reversed = FALSE ) multcompLetters2(formula, x, data, ...) multcompLetters3(z, y, x, data, ...) multcompLetters4(object, comp, ...) } \arguments{ \item{x}{One of the following: (1) A square, symmetric matrix with row names. (2) A vector with hyphenated names, which identify individual items or factor levels after "strsplit". (3) An object of class "dist". If x (or x[1]) is not already of class "logical", it is replaced with do.call(compare, list(x, threshold)), which by default converts numbers (typically p-values) less than 0.05 to TRUE and everything else to FALSE. If x is a matrix, its diagonal must be or must convert to FALSE.} \item{compare}{function or binary operator; not used if class(x) is "logical".} \item{threshold}{Second (reference) argument to "compare".} \item{Letters}{Vector of distinct characters (or character strings) used to connect levels that are not significantly different. They should be recogizable when concatonated. The last element of "Letters" is used as a prefix for a reuse of "Letters" if more are needed than are provided. For example, with the default "Letters", if 53 distinct connection colums are required, they will be "a", ..., "z", "A", ..., "Z", and ".a". If 54 are required, the last one will be ".b". If 105 are required, the last one will be "..a", etc. (If the algorithm generates that many distinct groups, the display may be too busy to be useful, but the algorithm shouldn't break.)} \item{reversed}{A logical value indicating whether the order of the letters should be reversed. Defaults to FALSE.} \item{formula}{The formula used to make the test (lm, aov, glm, etc.). Like y ~ x.} \item{data}{Data used to make the test.} \item{...}{Extra arguments passed to multcompLetters.} \item{z}{Categorical variables used in the test.} \item{y}{Value of the response variable.} \item{object}{An object of class aov or lm for the time being.} \item{comp}{A object with multiple comparison or a function name to perform a multiple comparison.} } \value{ An object of class 'multcompLetters', which is a list with the following components: \item{Letters }{character vector with names = the names of the levels or groups compared and with values = character strings in which common values of the function argument "Letters" identify levels or groups that are not significantly different (or more precisely for which the corresponding element of "x" was FALSE or was converted to FALSE by "compare"). } \item{monospacedLetters }{ Same as "Letters" but with spaces so the individual grouping letters will line up with a monspaced type font. } \item{LetterMatrix }{Logical matrix with one row for each level compared and one column for each "Letter" in the "letter-based representation". The output component "Letters" is obtained by concatonating the column names of all columns with TRUE in that row. } multcompLetters4 will return a named list with the terms containing a object of class 'multcompLetters' as produced by \code{multcompLetters}. } \description{ Convert a logical vector or a vector of p-values or a correlation or distance matrix into a character-based display in which common characters identify levels or groups that are not significantly different. Designed for use with the output of functions like TukeyHSD, diststats, simint, simtest, csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. } \details{ Produces a "Letter-Based Representation of All- Pairwise Comparisons" as described by Piepho (2004). (The present algorithm does NOT perform his "sweeping" step.) \code{multcompLettersx} are wrapper of multcompLetters that will reorder the levels of the data so that the letters appear in a descending order of the mean. \code{mulcompletters3} is similar to \code{multcompletters2} except that it uses vector names to separte and the later has an formula interface. \code{multcompLetters4} will take a aov or lm object and a comparison test and will produce all the letters for the terms and interactions. } \section{Functions}{ \itemize{ \item \code{multcompLetters2()}: \item \code{multcompLetters3()}: create a compact letters display and order the letters \item \code{multcompLetters4()}: create a compact letters display using a aov object }} \examples{ ## ## 1. a logical vector indicating signficant differences ## dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("A-B", "A-C", "B-C") dif3L <- multcompLetters(dif3) dif3L print(dif3L) print(dif3L, TRUE) ## ## 2. numeric vector indicating statistical significance ## dif4 <- c(.01, .02, .03, 1) names(dif4) <- c("a-b", "a-c", "b-d", "a-d") (diff4.T <- multcompLetters(dif4)) (dif4.L1 <- multcompLetters(dif4, Letters=c("*", "."))) # "Letters" can be any character strings, # but they should be recognizable when # concatonated. ## ## 3. distance matrix ## dJudge <- dist(USJudgeRatings) dJl <- multcompLetters(dJudge, compare='>', threshold = median(dJudge)) # comparison of 43 judges; compact but undecipherable: dJl x <- array(1:9, dim=c(3,3), dimnames=list(LETTERS[1:3], NULL) ) d3 <- dist(x) dxLtrs <- multcompLetters(d3, compare=">", threshold=2) d3d <- dist(x, diag=TRUE) dxdLtrs <- multcompLetters(d3d, compare=">", threshold=2) \dontshow{stopifnot(} all.equal(dxLtrs, dxdLtrs) \dontshow{)} d3u <- dist(x, upper=TRUE) dxuLtrs <- multcompLetters(d3d, compare=">", threshold=2) \dontshow{stopifnot(} all.equal(dxLtrs, dxuLtrs) \dontshow{)} ## ## 4. cor matrix ## set.seed(4) x100 <- matrix(rnorm(100), ncol=5, dimnames=list(NULL, LETTERS[1:5]) ) cx <- cor(x100) cxLtrs <- multcompLetters(abs(cx), threshold=.3) ## ##5. reversed ## dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("A-B", "A-C", "B-C") dif3L <- multcompLetters(dif3) dif3L.R <- multcompLetters(dif3, rev = TRUE) dif3L dif3L.R ## ##6. multcompletters2 usage experiment <- data.frame(treatments = gl(11, 20, labels = c("dtl", "ctrl", "treat1", "treat2", "treatA2", "treatB", "treatB2", "treatC", "treatD", "treatA1", "treatX")), y = c(rnorm(20, 10, 5), rnorm(20, 20, 5), rnorm(20, 22, 5), rnorm(20, 24, 5), rnorm(20, 35, 5), rnorm(20, 37, 5), rnorm(20, 40, 5), rnorm(20, 43, 5), rnorm(20, 45, 5), rnorm(20, 60, 5), rnorm(20, 60, 5))) exp_tukey <- TukeyHSD(exp_aov <- aov(y ~ treatments, data = experiment)) exp_letters1 <- multcompLetters(exp_tukey$treatments[,4]) exp_letters1 #Notice lowest mean treatments gets a "e" #Ordered letters multcompLetters2(y ~ treatments, exp_tukey$treatments[,"p adj"], experiment) multcompLetters2(y ~ treatments, exp_tukey$treatments[,"p adj"], experiment, reversed = TRUE) ##7. multcompletters3 usage multcompLetters3("treatments", "y", exp_tukey$treatments[,"p adj"], experiment) ##8. multcompletters4 usage multcompLetters4(exp_aov, exp_tukey) } \references{ Piepho, Hans-Peter (2004) "An Algorithm for a Letter-Based Representation of All-Pairwise Comparisons", Journal of Computational and Graphical Statistics, 13(2)456-466. } \seealso{ \code{\link{multcompBoxplot}} \code{\link{plot.multcompLetters}} \code{\link{print.multcompLetters}} \code{\link{multcompTs}} \code{\link{vec2mat}} } \author{ Spencer Graves, Hans-Peter Piepho and Luciano Selzer } \keyword{dplot} multcompView/man/extract_p.Rd0000644000176200001440000000312014414530347016001 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/extract_p.R \name{extract_p} \alias{extract_p} \alias{extract_p.default} \alias{extract_p.TukeyHSD} \alias{extract_p.mc} \title{Extracts p-values} \usage{ extract_p(x) \method{extract_p}{default}(x) \method{extract_p}{TukeyHSD}(x) \method{extract_p}{mc}(x) } \arguments{ \item{x}{A object that has p-values or logical values.} } \value{ A named vector with p-values or logical values. } \description{ For a given object it will look for the column named "p adj" or "difference" and extract its value mantaining its names } \section{Methods (by class)}{ \itemize{ \item \code{extract_p(default)}: \item \code{extract_p(TukeyHSD)}: extract p values from a TukeyHSD object \item \code{extract_p(mc)}: }} \examples{ experiment <- data.frame(treatments = gl(11, 20, labels = c("dtl", "ctrl", "treat1", "treat2", "treatA2", "treatB", "treatB2", "treatC", "treatD", "treatA1", "treatX")), y = c(rnorm(20, 10, 5), rnorm(20, 20, 5), rnorm(20, 22, 5), rnorm(20, 24, 5), rnorm(20, 35, 5), rnorm(20, 37, 5), rnorm(20, 40, 5), rnorm(20, 43, 5), rnorm(20, 45, 5), rnorm(20, 60, 5), rnorm(20, 60, 5))) exp_tukey <- TukeyHSD(exp_aov <- aov(y ~ treatments, data = experiment)) extract_p(exp_tukey) if(require(pgirmess)){ extract_p(kruskalmc(y ~ treatments, data = experiment)) } } \seealso{ \code{\link{multcompLetters}} \code{\link{multcompTs}} } \author{ Luciano Selzer } \keyword{array} \keyword{manip} multcompView/man/print.multcompLetters.Rd0000644000176200001440000000217214414537040020351 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/print.multcompLetters.R \name{print.multcompLetters} \alias{print.multcompLetters} \title{print a multcompLetters object} \usage{ \method{print}{multcompLetters}(x, all = FALSE, ...) } \arguments{ \item{x}{an object of class 'multcompLetters'} \item{all}{FALSE to print only the character vector representations of the 'multcompLetters' comparison summary; TRUE to print also the matrix representation.} \item{...}{Other optional print parameters as described on the \code{\link{print}} help page.} } \value{ the named, character vector representation of the 'multcompLetters' evaluation of the distance relationships } \description{ print method for an object of class 'multcompLetters'. } \details{ Prints only the Letters component of the 'multcompLetters' list unless all=TRUE. } \examples{ dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("A-B", "A-C", "B-C") dif3L <- multcompLetters(dif3) dif3L print(dif3L) print(dif3L, TRUE) } \seealso{ \code{\link{multcompLetters}} } \author{ Spencer Graves } \keyword{dplot} multcompView/man/vec2mat2.Rd0000644000176200001440000000243014414525367015444 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/vec2mat2.R \name{vec2mat2} \alias{vec2mat2} \title{Convert a vector of hyphenated names into a character matrix.} \usage{ vec2mat2(x, sep = "-") } \arguments{ \item{x}{Vector of hyphenated names} \item{sep}{"strsplit" character to apply to names(x).} } \value{ A character matrix with rownames = x and with the character string preceeding the "sep" character in the first column and the character string following the "sep" character in the second column. } \description{ Convert a vector of hyphenated names into a character matrix with 2 columns containing the names split in each row. } \details{ If each element of x does not contain exactly 1 "sep" character, an error is issued. } \examples{ vec2mat2(c("a-b", "a-c", "b-c")) vec2mat2(c("a-b", "b-a")) \dontshow{ (tst3 <- substring(try( vec2mat2(c("a", "b-a", "b-c"))), 1, 20) =="Error in vec2mat2(c(") # Error: name without a sep character (tst4 <- substring(try( vec2mat2(c("a-c", "b-a", "b-c-d"))), 1, 20) =="Error in vec2mat2(c(") # Error: multiple hyphens (sep characters) } } \seealso{ \code{\link{vec2mat}} \code{\link{multcompLetters}} } \author{ Spencer Graves } \keyword{array} \keyword{manip} multcompView/man/multcompView-package.Rd0000644000176200001440000000371714414525367020116 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multcompView-package.R \docType{package} \name{multcompView-package} \alias{multcompView-package} \alias{multcompView} \title{Summarize multiple paired comparisons} \description{ Convert a logical vector or a vector of p-values or a difference or distance matrix into a display identifying the pairs for which the differences were not significantly different or for which the difference exceeded a threshold. } \details{ \tabular{ll}{ Package: \tab multcompView\cr Type: \tab Package\cr Version: \tab 0.1-0\cr Date: \tab 2006-08-06\cr License: \tab GPL\cr } Convert a logical vector or a vector of p-values or a difference or distance matrix into either a letter-based display using "multcompLetters" or a graphic roughly like a "T" using "multcompTs" to identify factor levels or similar groupings that are or are not significantly different. Designed for use in conjunction with the output of functions like TukeyHSD, diststats, simint, simtest, csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. } \examples{ dif3 <- c(FALSE, FALSE, TRUE) names(dif3) <- c("a-b", "a-c", "b-c") multcompTs(dif3) multcompLetters(dif3) library(MASS) multcompBoxplot(Postwt~Treat, data=anorexia) } \references{ Piepho, Hans-Peter (2004) "An Algorithm for a Letter-Based Representation of All-Pairwise Comparisons", Journal of Computational and Graphical Statistics, 13(2)456-466. John R. Donaghue (2004) "Implementing Shaffer's multiple comparison procedure for a large number of groups", pp. 1-23 in Benjamini, Bretz and Sarkar (eds) Recent Developments in Multiple Comparison Procedures (Institute of Mathematical Statistics Lecture Notes-Monograph Series vol. 47) } \author{ Spencer Graves and Hans-Peter Piepho with help from Sundar Dorai-Raj Maintainer: Spencer Graves } \keyword{aplot} \keyword{dplot} \keyword{htest} \keyword{package} multcompView/man/plotTs.Rd0000644000176200001440000001227014414525367015311 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotTs.R \name{plotTs} \alias{plotTs} \title{plot multcomp displays} \usage{ plotTs( obj, at, width, horizontal, col, add, lwd, label.levels, label.groups, T.base, orientation = "", ... ) } \arguments{ \item{obj}{a matrix describing which levels (rows) will be plotted with which groups (columns). For plotTs and plotBoxes, obj is a matrix of numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if that "letter" (group or column of obj) is to be plotted with that level (row of obj).} \item{at}{an array with one row for each level and 3 columns giving low, middle and high levels for the display for that level.} \item{width}{an array with one row for each group of levels in the display and 3 columns giving low, middle and high levels for the display for that group.} \item{horizontal}{A logical scalar indicating whether the list of items compared reads left to right (horizontal = TRUE) or top to bottom (horizontal = FALSE). If this multcomp graphic accompanies boxplots for different levels or groups compared, the 'boxplot' argument 'horizontal' is the negation of the multcomp plot 'horizontal' argument.} \item{col}{The color for each group of items or factor levels. The colors will cross the different items or factor levels and will therefore have the orientation specified via 'horizontal'. If the number of columns exceeds length(col), col is recycled. For alternative choices for col, see "Color Specification" in the \code{\link{par}} help page.} \item{add}{TRUE to add to an existing plot; FALSE to start a new plot. The names of the factor levels or items compared will be plotted only if add=FALSE.} \item{lwd}{line width for the display outline.} \item{label.levels}{Distance from the plot region to print the names of the levels as a proportion of the plot range; NA for no level labels.} \item{label.groups}{Distance from the plot region to print the names of the groups as a proportion of the plot range; NA for no level labels.} \item{T.base}{A numeric scalar giving the proportion of the available space devoted to the base of the Ts.} \item{orientation}{If 'reversed', the base(s) of each "T" or traingle indicating the master level(s) of that "undifferentiated class" will point right or up (depending on horizontal) rather than down or left.} \item{...}{graphical parameters can be given as described on the \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page.} \item{font.family}{character string naming the font family used by "plotLetters". This function plots the different "Letters" in different colors by plotting one color at a time. It's currently not smart enough to align the letters properly except by assuming a mono-spaced font.} \item{fig}{figure region = (x0, x1, y0, y1) as a proportion of the device region.} \item{mar}{margin = (lower, left, upper, right) in lines.} } \value{ "Done" } \description{ Helper functions for plot.multcompTs and plot.multcompLetters. These not intended to be called directly and are hidden in a namespace. You can use 'getAnywhere' to see them. } \details{ The requested graphic is either plotted by itself or added to an existing plot as specified by the arguments. "plotTs" and "plotBoxes" use traditional R graphics and will not be discussed further here. "plotLetters" uses 'grid' graphics, because it seems to provide more support for controlling the side-by-side placement of "Letters" of possibly different colors and widths. The "Letters" display will be positioned in the "plot region" defined by fig and mar, assuming the entire device region is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, 1, 0, 1), this makes the plot region 3.7 lines wide. With the default mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this contradictory negative width, and centers the plot at the midpoint of h0 = fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = fig[4]-mar[3]/37. The "Letters" for the different levels compared are rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) else c(v0, v1). With "n" levels compared and at.rng = range(at[, "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to match At.rng; if(diff(At.rng)<=0), an error message is issued. Meanwhile, the "Letters" are centered at the midpoint of W.rng = if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the argument "width" used by plotTs and plotBoxes is not used (and not even accepted) by plotLetters. If(label.levels), these are positioned in the midpoint of the right margin in the "W" direction. } \examples{ # Designed to be called from plot.multcompTs # or plot.multcompLetters, NOT directly by users. } \seealso{ \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} \keyword{internal} multcompView/man/plot.multcompLetters.Rd0000644000176200001440000001344414414525367020210 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.multcompLetters.R \name{plot.multcompLetters} \alias{plot.multcompLetters} \alias{plot.multcomp} \title{plot multcomp graphics} \usage{ \method{plot}{multcompLetters}( x, horizontal = FALSE, col = 1:6, type = c("Letters", "boxes"), add = FALSE, at, width, fig = c(0, 1, 0, 1), label.levels = if (add) NA else 0.05, label.groups = NA, ... ) } \arguments{ \item{x}{an object of class 'multcompTs' or 'multcompLetters'.} \item{horizontal}{A logical scalar indicating whether the list of items compared reads left to right (horizontal = TRUE) or top to bottom (horizontal = FALSE). If this multcomp graphic accompanies boxplots for different levels or groups compared, the 'boxplot' argument 'horizontal' is the negation of the multcomp plot 'horizontal' argument.} \item{col}{The color for each group of items or factor levels. The colors will cross the different items or factor levels and will therefore have the orientation specified via 'horizontal'. If the number of columns exceeds length(col), col is recycled. For alternative choices for col, see "Color Specification" in the \code{\link{par}} help page.} \item{type}{An alternative display for either multcompTs or multcompLetters is 'boxes' (or rectangles). If type="boxes" with "multcompTs", the "base(s)" of each "T" will be indicated by a triangle.} \item{add}{TRUE to add to an existing plot; FALSE to start a new plot. The names of the factor levels or items compared will be plotted only if add=FALSE.} \item{at}{A numeric vector or matrix or a list with components "at" and "width". If a list, both components must be either a numeric vector or matrix. The numeric vector "at" (whether the function argument or "at" component of the "at" list) must be either a numeric vector or matrix giving the locations where the "Ts" or "Letters" graphics should be drawn. length(at) is 1, 2 or 3 times the number of the number of factor levels or items compared. If length(at) is twice the number of levels or items compared, it gives the range of the display for that level; the base of a "T" will be at the midpoint. If length(at) is three times the number of items compared, the intermediate number will be the center of the base of the "T".} \item{width}{A numeric vector or matrix with as many rows as "Ts" or "groups" and with up to three columns. With one column, it will be the "center" of the plot range for that group. With two columns, they will delimit the range. With three, they will provide "bottom", "center", and "top" of the range for that set of grouping indicators. If "at" is a list, the argument "width" is ignored and is taken from the list "at".} \item{fig}{A numerical vector of the form 'c(x1, x2, y1, y2)' giving the coordinates of the figure region in the display region of the plot device, as described on the \code{\link{par}} help page.} \item{label.levels}{NA for no labels or distance away from the plot for the labels as a proportion of the plot range.} \item{label.groups}{NA for no labels or distance away from the plot for the labels as a proportion of the plot range.} \item{...}{graphical parameters can be given as described on the \code{\link{plot}} help page or for plot.multcompLetters as describe on the \code{\link[grid]{gpar}} help page.} } \value{ A list with two components: \item{at }{ A matrix with three columns giving the middle and extremes of the display for each of the factor levels or items compared. } \item{width }{ A matrix with as many rows as "Ts" or comparitor levels and with two columns giving the plot range for that comparitor level. } } \description{ Plot graphic(s) for multcompTs or multcompLetters objects } \details{ The requested graphic is either plotted by itself or added to an existing plot as specified by the arguments. The placement can be controlled by 'fig' and 'at'. The fontsize and fontface of a plot of a multcompLetters object with 'type = "Letters"' can be adjusted as describe on the \code{\link[grid]{gpar}} help page. } \examples{ ## ## plot(multcompTs(...)) ## dif4 <- c(.1, .02, .03, 1) names(dif4) <- c("A-B", "A-C", "B-C", "A-D") (mcT4 <- multcompTs(dif4)) # Standard plot, base of "Ts" point left mcT4.1 <- plot(mcT4, label.groups=0.05) # Redo using "at" = list plot(mcT4, label.groups=0.05, at=mcT4.1) # Same plot with group labels closer to the figure plot(mcT4, label.groups=0.02) # Base of "Ts" point right plot(mcT4, label.groups=TRUE, orientation="r") # Base of "Ts" point down plot(mcT4, horizontal=TRUE, label.groups=0.05) # Base of "Ts" point up plot(mcT4, horizontal=TRUE, label.groups=0.05, orientation="r") # Same 4 plots but with boxes & triangles, not Ts plot(mcT4, label.groups=0.05, type="b") plot(mcT4, label.groups=0.05, orientation="r", type="b") plot(mcT4, horizontal=TRUE, label.groups=0.05, type="b") plot(mcT4, horizontal=TRUE, label.groups=0.05, orientation="r", type="b") ## ## plot(multcompLetters(...)) ## # ... using dif4 from above (mcL4 <- multcompLetters(dif4, Letters=LETTERS)) # Standard plot \dontrun{ # Requires (grid) mcL4.1 <- plot(mcL4, label.groups=0.05) # Redo using "at" = list plot(mcL4, label.groups=0.05, at=mcL4.1) # With bold face and larger font plot(mcL4, label.groups=0.05, fontsize=28, fontface="bold") # Horizontal rather than vertical plot(mcL4, horizontal=TRUE, label.groups=0.05) } # Same as boxes rather than letters plot(mcL4, label.groups=0.05, type="b") plot(mcL4, horizontal=TRUE, label.groups=0.05, type="b") } \seealso{ \code{\link{multcompTs}} \code{\link{multcompLetters}} \code{\link{multcompBoxplot}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} multcompView/man/plotBoxes.Rd0000644000176200001440000001225714414525367016010 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotBoxes.R \name{plotBoxes} \alias{plotBoxes} \title{plot multcomp displays} \usage{ plotBoxes( obj, at, width, horizontal, col, add, label.levels, label.groups, orientation = "", ... ) } \arguments{ \item{obj}{a matrix describing which levels (rows) will be plotted with which groups (columns). For plotTs and plotBoxes, obj is a matrix of numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if that "letter" (group or column of obj) is to be plotted with that level (row of obj).} \item{at}{an array with one row for each level and 3 columns giving low, middle and high levels for the display for that level.} \item{width}{an array with one row for each group of levels in the display and 3 columns giving low, middle and high levels for the display for that group.} \item{horizontal}{A logical scalar indicating whether the list of items compared reads left to right (horizontal = TRUE) or top to bottom (horizontal = FALSE). If this multcomp graphic accompanies boxplots for different levels or groups compared, the 'boxplot' argument 'horizontal' is the negation of the multcomp plot 'horizontal' argument.} \item{col}{The color for each group of items or factor levels. The colors will cross the different items or factor levels and will therefore have the orientation specified via 'horizontal'. If the number of columns exceeds length(col), col is recycled. For alternative choices for col, see "Color Specification" in the \code{\link{par}} help page.} \item{add}{TRUE to add to an existing plot; FALSE to start a new plot. The names of the factor levels or items compared will be plotted only if add=FALSE.} \item{label.levels}{Distance from the plot region to print the names of the levels as a proportion of the plot range; NA for no level labels.} \item{label.groups}{Distance from the plot region to print the names of the groups as a proportion of the plot range; NA for no level labels.} \item{orientation}{If 'reversed', the base(s) of each "T" or traingle indicating the master level(s) of that "undifferentiated class" will point right or up (depending on horizontal) rather than down or left.} \item{...}{graphical parameters can be given as described on the \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page.} \item{lwd}{line width for the display outline.} \item{T.base}{A numeric scalar giving the proportion of the available space devoted to the base of the Ts.} \item{font.family}{character string naming the font family used by "plotLetters". This function plots the different "Letters" in different colors by plotting one color at a time. It's currently not smart enough to align the letters properly except by assuming a mono-spaced font.} \item{fig}{figure region = (x0, x1, y0, y1) as a proportion of the device region.} \item{mar}{margin = (lower, left, upper, right) in lines.} } \value{ "Done" } \description{ Helper functions for plot.multcompTs and plot.multcompLetters. These not intended to be called directly and are hidden in a namespace. You can use 'getAnywhere' to see them. } \details{ The requested graphic is either plotted by itself or added to an existing plot as specified by the arguments. "plotTs" and "plotBoxes" use traditional R graphics and will not be discussed further here. "plotLetters" uses 'grid' graphics, because it seems to provide more support for controlling the side-by-side placement of "Letters" of possibly different colors and widths. The "Letters" display will be positioned in the "plot region" defined by fig and mar, assuming the entire device region is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, 1, 0, 1), this makes the plot region 3.7 lines wide. With the default mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this contradictory negative width, and centers the plot at the midpoint of h0 = fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = fig[4]-mar[3]/37. The "Letters" for the different levels compared are rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) else c(v0, v1). With "n" levels compared and at.rng = range(at[, "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to match At.rng; if(diff(At.rng)<=0), an error message is issued. Meanwhile, the "Letters" are centered at the midpoint of W.rng = if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the argument "width" used by plotTs and plotBoxes is not used (and not even accepted) by plotLetters. If(label.levels), these are positioned in the midpoint of the right margin in the "W" direction. } \examples{ # Designed to be called from plot.multcompTs # or plot.multcompLetters, NOT directly by users. } \seealso{ \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} \keyword{internal} multcompView/man/multcompBoxplot.Rd0000644000176200001440000001375214414525367017242 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/multcompBoxplot.R \name{multcompBoxplot} \alias{multcompBoxplot} \title{boxplot with multcomp graphics} \usage{ multcompBoxplot( formula, data, horizontal = TRUE, compFn = "TukeyHSD", sortFn = "mean", decreasing = TRUE, plotList = list(boxplot = list(fig = c(0, 0.75, 0, 1)), multcompTs = list(fig = c(0.7, 0.85, 0, 1)), multcompLetters = list(fig = c(0.87, 0.97, 0.03, 0.98), fontsize = 20, fontface = "bold")) ) } \arguments{ \item{formula}{a two sided formula like "y~z", where both "y" and "z" are columns of the data.frame "data", "y" is numeric, and "z" is a factor. This will be passed as the first argument for both 'boxplot' and 'compFn', and so must work in both contexts. NOTE: Any more complicated formula may produce errors or unanticipated results.} \item{data}{A data.frame for evaluating 'formula'.} \item{horizontal}{TRUE for horizontal boxplots and vertical multcompTs and / or multcompLetters; FALSE for the opposite.} \item{compFn}{a function whose output will serve as the the only non-default input to either 'multcompTs' or 'multcompLetters'. The default "TukeyHSD" actually translates to 'TukeyHSD(aov(formula, data))[[1]][, "p adj"]'.} \item{sortFn}{If sortFn is a function or a character string naming a function, it is used to summarize the subset of y corresponding to each level of z into a single number, which will then be used to sort the levels of z according to the argumment 'decreasing'. This step is skipped if sortFn is NULL or NA or if it is neither a function nor a character string that might name a function. If sortFn is a character string but a function by that name is not found in the search path, multcompBoxplot stops with, 'Error in do.call(sortFn, list(x = x)) : could not find function ...'.} \item{decreasing}{If the levels of z are to be sorted using the output of 'sortFn', this is uses as the 'decreasing' in 'order' to sort the levels of z for plotting.} \item{plotList}{A list with names in c("boxplot", "multcompTs", "multcompLetters"). Replicates are allowed. If present, they produce, e.g., multiple "multcompTs" side by side. This can be used to compare the visual effects of different arguments to "plot.multcompTs". Each component of 'plotList' is itself a list of arguments to pass to either "boxplot", "plot.multcompTs" or "plot.multcompLetters". Placement can be controlled via 'fig' arguments passed (indirectly) of the form 'c(x1, x2, y1, y2)'. If(horizontal==TRUE), fig gives the coordinates of the figure region in the display region of the plot device, as described on the \code{\link{par}} help page; if(horizontal==FALSE), fig[c(3,4,1,2)] gives c(x1, x2, y1, y2) for placement of that portion of the plot.} } \value{ This function invisibly returns a list with one component for each component of plotList containing the output of the appropriate "plot.multcomp" call plus the output of "compFn". } \description{ Create boxplots with multcompTs and / or multcompLetters } \details{ For formula = y~z, if 'sortFn' is a function or the name of a function, 'multcompBoxplot' starts by applying sortFn to the subsets of y corresponding to each level of z, and then sorting those summaries in increasing or decreasing order, per 'decreasing'. If 'sortFn' is NULL or NA, this sort step is skipped. 'multcompBoxplot' then creates 'boxplot' as specified in 'plotList'. Next, 'compFn' is called to generate comparisons to feed to the functions (\code{\link{multcompTs}} and / or \code{\link{multcompLetters}}, whose output is then passed to (\code{\link{plot.multcomp}}) for plotting. Components of the relevant sublists of 'plotList' are made available to \code{\link{par}} or (for \code{\link{plot.multcompLetters}}) to \code{\link[grid]{gpar}}. } \examples{ # Example from help("TukeyHSD") multcompBoxplot(breaks~tension, data=warpbreaks) # 'sortFn' can be either a function or a function name # default order is 'decreasing=TRUE' multcompBoxplot(breaks~tension, data=warpbreaks, sortFn=median, decreasing=FALSE) ################## library(multcomp) data(recovery) # Horizontal boxplots with both # multcomp Ts and Letters on the right # Using recovery{multcomp} data set multcompBoxplot(minutes~blanket, recovery) # Plotting boxes rather than letters and Ts multcompBoxplot(minutes~blanket, recovery, plotList=list( boxplot=list(fig=c(0, 0.75, 0, 1), las=1, cex.axis=1.5), multcompTs=list(fig=c(0.7, 0.85, 0, 1), type='boxes'), multcompLetters=list( fig=c(0.87, 0.97, 0.03, 0.98), type='boxes') ) ) #################### # Vertical boxplots with both # multcomp Ts and Letters on the top multcompBoxplot(minutes~blanket, recovery, horizontal=FALSE) # Horizontal boxplots with 2 different # displays of the "Ts" on the left multcompBoxplot(minutes~blanket, recovery, plotList=list( boxplot=list(fig=c(0.3, 1, 0, 1)), multcompTs=list(fig=c(0, 0.15, 0, 1), orientation="reverse"), multcompTs=list(fig=c(0.15, 0.3, 0, 1), type="boxes", orientation="reverse", mar=c(5,2, 4, 0)+.1) ) ) library(MASS) anorx <- multcompBoxplot(Postwt~Treat, data=anorexia) \dontrun{ # Confirm than sortFn=NULL or NA # leaves the order unchanged library(multcomp) data(cholesterol) cholesterol$trt3 <- with(cholesterol, factor( as.character(trt), levels=levels(trt)[c(5:4,1:3)])) multcompBoxplot(response ~ trt3, cholesterol, sortFn=NULL) multcompBoxplot(response ~ trt3, cholesterol, sortFn=NA) } } \seealso{ \code{\link{boxplot}} \code{\link{multcompTs}} \code{\link{multcompLetters}} \code{\link{plot.multcomp}} \code{\link{TukeyHSD}} \code{\link{par}} \code{\link[grid]{gpar}} } \author{ Spencer Graves } \keyword{aplot} multcompView/DESCRIPTION0000644000176200001440000000155014414551362014461 0ustar liggesusersPackage: multcompView Type: Package Title: Visualizations of Paired Comparisons Version: 0.1-9 Date: 2023-04-09 Author: Spencer Graves, Hans-Peter Piepho and Luciano Selzer with help from Sundar Dorai-Raj Maintainer: Luciano Selzer Description: Convert a logical vector or a vector of p-values or a correlation, difference, or distance matrix into a display identifying the pairs for which the differences were not significantly different. Designed for use in conjunction with the output of functions like TukeyHSD, dist{stats}, simint, simtest, csimint, csimtest{multcomp}, friedmanmc, kruskalmc{pgirmess}. License: GPL Imports: grid Suggests: multcomp, pgirmess, MASS Packaged: 2023-04-09 13:31:25 UTC; Luciano RoxygenNote: 7.2.3 NeedsCompilation: no Repository: CRAN Date/Publication: 2023-04-09 15:00:02 UTC multcompView/R/0000755000176200001440000000000014414525367013161 5ustar liggesusersmultcompView/R/print.multcompLetters.R0000644000176200001440000000216114414537027017636 0ustar liggesusers#' print a multcompLetters object #' #' print method for an object of class 'multcompLetters'. #' #' Prints only the Letters component of the 'multcompLetters' list unless #' all=TRUE. #' #' @param x an object of class 'multcompLetters' #' @param all FALSE to print only the character vector representations of the #' 'multcompLetters' comparison summary; TRUE to print also the matrix #' representation. #' @param ... Other optional print parameters as described on the #' \code{\link{print}} help page. #' @return the named, character vector representation of the #' 'multcompLetters' evaluation of the distance relationships #' @author Spencer Graves #' @seealso \code{\link{multcompLetters}} #' @keywords dplot #' @export #' @examples #' #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("A-B", "A-C", "B-C") #' dif3L <- multcompLetters(dif3) #' dif3L #' print(dif3L) #' print(dif3L, TRUE) #' "print.multcompLetters" <- function(x, all=FALSE, ...){ { if(all){ class(x) <- NULL print(x, ...) } else print(x$Letters, ...) } invisible(x$Letters) } multcompView/R/plotBoxes.R0000644000176200001440000001672514414525367015276 0ustar liggesusers#' plot multcomp displays #' #' Helper functions for plot.multcompTs and plot.multcompLetters. These not #' intended to be called directly and are hidden in a namespace. You can use #' 'getAnywhere' to see them. #' #' The requested graphic is either plotted by itself or added to an existing #' plot as specified by the arguments. #' #' "plotTs" and "plotBoxes" use traditional R graphics and will not be #' discussed further here. #' #' "plotLetters" uses 'grid' graphics, because it seems to provide more support #' for controlling the side-by-side placement of "Letters" of possibly #' different colors and widths. The "Letters" display will be positioned in #' the "plot region" defined by fig and mar, assuming the entire device region #' is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 #' lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, #' 1, 0, 1), this makes the plot region 3.7 lines wide. With the default #' mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 #' - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this #' contradictory negative width, and centers the plot at the midpoint of h0 = #' fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = #' fig[4]-mar[3]/37. The "Letters" for the different levels compared are #' rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) #' else c(v0, v1). With "n" levels compared and at.rng = range(at[, #' "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to #' match At.rng; if(diff(At.rng)<=0), an error message is issued. #' #' Meanwhile, the "Letters" are centered at the midpoint of W.rng = #' if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the #' argument "width" used by plotTs and plotBoxes is not used (and not even #' accepted) by plotLetters. If(label.levels), these are positioned in the #' midpoint of the right margin in the "W" direction. #' #' @param obj a matrix describing which levels (rows) will be plotted with #' which groups (columns). For plotTs and plotBoxes, obj is a matrix of #' numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if #' that "letter" (group or column of obj) is to be plotted with that level (row #' of obj). #' @param at an array with one row for each level and 3 columns giving low, #' middle and high levels for the display for that level. #' @param width an array with one row for each group of levels in the display #' and 3 columns giving low, middle and high levels for the display for that #' group. #' @param horizontal A logical scalar indicating whether the list of items #' compared reads left to right (horizontal = TRUE) or top to bottom #' (horizontal = FALSE). If this multcomp graphic accompanies boxplots for #' different levels or groups compared, the 'boxplot' argument 'horizontal' is #' the negation of the multcomp plot 'horizontal' argument. #' @param col The color for each group of items or factor levels. The colors #' will cross the different items or factor levels and will therefore have the #' orientation specified via 'horizontal'. If the number of columns exceeds #' length(col), col is recycled. For alternative choices for col, see "Color #' Specification" in the \code{\link{par}} help page. #' @param add TRUE to add to an existing plot; FALSE to start a new plot. The #' names of the factor levels or items compared will be plotted only if #' add=FALSE. #' @param lwd line width for the display outline. #' @param label.levels Distance from the plot region to print the names of the #' levels as a proportion of the plot range; NA for no level labels. #' @param label.groups Distance from the plot region to print the names of the #' groups as a proportion of the plot range; NA for no level labels. #' @param T.base A numeric scalar giving the proportion of the available space #' devoted to the base of the Ts. #' @param orientation If 'reversed', the base(s) of each "T" or traingle #' indicating the master level(s) of that "undifferentiated class" will point #' right or up (depending on horizontal) rather than down or left. #' @param font.family character string naming the font family used by #' "plotLetters". This function plots the different "Letters" in different #' colors by plotting one color at a time. It's currently not smart enough to #' align the letters properly except by assuming a mono-spaced font. #' @param fig figure region = (x0, x1, y0, y1) as a proportion of the device #' region. #' @param mar margin = (lower, left, upper, right) in lines. #' @param ... graphical parameters can be given as described on the #' \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page. #' @return "Done" #' @author Spencer Graves #' @seealso \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} #' \code{\link[grid]{gpar}} #' @keywords aplot internal #' @examples #' #' # Designed to be called from plot.multcompTs #' # or plot.multcompLetters, NOT directly by users. #' @importFrom graphics par text lines polygon rect #' @export "plotBoxes" <- function(obj, at, width, horizontal, col, add, label.levels, label.groups, orientation="", ...){ if(orientation=="reverse") width[,] <- width[, 3:1] lvl.rng <- range(at) gp.rng <- range(width) n <- dim(obj)[1] k <- dim(obj)[2] # Convert to character to use with "switch" ob. <- array(as.character(obj), dim=dim(obj), dimnames=dimnames(obj)) { if(horizontal){ plot(lvl.rng, gp.rng, type="n", xlab="", ylab="", bty="n", axes=FALSE, ...) for(i in 1:k){ for(j in 1:n) switch(ob.[j,i], "-1"=next, "0" =rect(at[j, "bottom"], width[i, "bottom"], at[j, "top"], width[i, "top"], density=(-1), col=col[i], lty="blank"), "1" =polygon( x=at[j, c("bottom", "top", "center", "bottom")], y=width[i, c("top", "top", "bottom", "top")], density=(-1), col=col[i], lty="blank") ) } # Labels? if(!is.na(label.levels)) text(at[, "center"], gp.rng[1]-label.levels*diff(gp.rng), dimnames(obj)[[1]]) if(!is.na(label.groups)) text(lvl.rng[1]-label.groups*diff(lvl.rng), width[, "center"], dimnames(obj)[[2]]) } else{ plot(gp.rng, lvl.rng, type="n", xlab="", ylab="", bty="n", axes=FALSE, ...) for(i in 1:k){ for(j in 1:n) switch(ob.[j,i], "-1"=next, "0" =rect(width[i, "bottom"],at[j, "bottom"], width[i, "top"],at[j, "top"], density=(-1), col=col[i], lty="blank"), "1" =polygon( x=width[i, c("top", "top", "bottom", "top")], y=at[j, c("bottom", "top", "center", "bottom")], density=(-1), col=col[i], lty="blank") ) } # Labels? if(!is.na(label.levels)){ text(gp.rng[1]-label.levels*diff(gp.rng), at[, "center"], dimnames(obj)[[1]]) } if(!is.na(label.groups)) text(width[, "center"], lvl.rng[1]-label.groups*diff(lvl.rng), dimnames(obj)[[2]]) } } "Done" } multcompView/R/plotTs.R0000644000176200001440000001754614414525367014606 0ustar liggesusers#' plot multcomp displays #' #' Helper functions for plot.multcompTs and plot.multcompLetters. These not #' intended to be called directly and are hidden in a namespace. You can use #' 'getAnywhere' to see them. #' #' The requested graphic is either plotted by itself or added to an existing #' plot as specified by the arguments. #' #' "plotTs" and "plotBoxes" use traditional R graphics and will not be #' discussed further here. #' #' "plotLetters" uses 'grid' graphics, because it seems to provide more support #' for controlling the side-by-side placement of "Letters" of possibly #' different colors and widths. The "Letters" display will be positioned in #' the "plot region" defined by fig and mar, assuming the entire device region #' is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 #' lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, #' 1, 0, 1), this makes the plot region 3.7 lines wide. With the default #' mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 #' - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this #' contradictory negative width, and centers the plot at the midpoint of h0 = #' fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = #' fig[4]-mar[3]/37. The "Letters" for the different levels compared are #' rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) #' else c(v0, v1). With "n" levels compared and at.rng = range(at[, #' "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to #' match At.rng; if(diff(At.rng)<=0), an error message is issued. #' #' Meanwhile, the "Letters" are centered at the midpoint of W.rng = #' if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the #' argument "width" used by plotTs and plotBoxes is not used (and not even #' accepted) by plotLetters. If(label.levels), these are positioned in the #' midpoint of the right margin in the "W" direction. #' #' @aliases plotTs #' @param obj a matrix describing which levels (rows) will be plotted with #' which groups (columns). For plotTs and plotBoxes, obj is a matrix of #' numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if #' that "letter" (group or column of obj) is to be plotted with that level (row #' of obj). #' @param at an array with one row for each level and 3 columns giving low, #' middle and high levels for the display for that level. #' @param width an array with one row for each group of levels in the display #' and 3 columns giving low, middle and high levels for the display for that #' group. #' @param horizontal A logical scalar indicating whether the list of items #' compared reads left to right (horizontal = TRUE) or top to bottom #' (horizontal = FALSE). If this multcomp graphic accompanies boxplots for #' different levels or groups compared, the 'boxplot' argument 'horizontal' is #' the negation of the multcomp plot 'horizontal' argument. #' @param col The color for each group of items or factor levels. The colors #' will cross the different items or factor levels and will therefore have the #' orientation specified via 'horizontal'. If the number of columns exceeds #' length(col), col is recycled. For alternative choices for col, see "Color #' Specification" in the \code{\link{par}} help page. #' @param add TRUE to add to an existing plot; FALSE to start a new plot. The #' names of the factor levels or items compared will be plotted only if #' add=FALSE. #' @param lwd line width for the display outline. #' @param label.levels Distance from the plot region to print the names of the #' levels as a proportion of the plot range; NA for no level labels. #' @param label.groups Distance from the plot region to print the names of the #' groups as a proportion of the plot range; NA for no level labels. #' @param T.base A numeric scalar giving the proportion of the available space #' devoted to the base of the Ts. #' @param orientation If 'reversed', the base(s) of each "T" or traingle #' indicating the master level(s) of that "undifferentiated class" will point #' right or up (depending on horizontal) rather than down or left. #' @param font.family character string naming the font family used by #' "plotLetters". This function plots the different "Letters" in different #' colors by plotting one color at a time. It's currently not smart enough to #' align the letters properly except by assuming a mono-spaced font. #' @param fig figure region = (x0, x1, y0, y1) as a proportion of the device #' region. #' @param mar margin = (lower, left, upper, right) in lines. #' @param ... graphical parameters can be given as described on the #' \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page. #' @return "Done" #' @author Spencer Graves #' @seealso \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} #' \code{\link[grid]{gpar}} #' @keywords aplot internal #' @importFrom graphics par text lines polygon rect #' @examples #' #' # Designed to be called from plot.multcompTs #' # or plot.multcompLetters, NOT directly by users. #' #' @export #' "plotTs" <- function(obj, at, width, horizontal, col, add, lwd, label.levels, label.groups, T.base, orientation="", ...){ if(orientation=="reverse") width[,] <- width[, 3:1] lvl.rng <- range(at) gp.rng <- range(width) n <- dim(obj)[1] k <- dim(obj)[2] # compute the base of the Ts Tb <- T.base[1] a.b <- at[, "bottom"] a.c <- at[, "center"] a.t <- at[, "top"] at.5 <- cbind(a.c-Tb*(a.c-a.b), a.c+Tb*(a.t-a.c)) { if(horizontal){ plot(lvl.rng, gp.rng, type="n", xlab="", ylab="", bty="n", axes=FALSE, ...) for(i in 1:k){ for(j in 1:n){ if(obj[j,i]<0)next # Top of the "T" rect(at[j, "bottom"], width[i, "center"], at[j, "top"], width[i, "top"], density=(-1), col=col[i], lty="blank") if(obj[j,i]>0) rect(at.5[j, 1], width[i, "bottom"], at.5[j, 2], width[i, "top"], density=(-1), col=col[i], lty="blank") # Leg(s) of the "T" } # Bridge across the top in case of gaps lines(range(at[obj[, i]>(-1), ]), rep(width[i, "top"],2), col=col[i], lwd=lwd) } # Labels? if(!is.na(label.levels)){ text(at[, "center"], gp.rng[1]-label.levels*diff(gp.rng), dimnames(obj)[[1]]) } if(!is.na(label.groups)) text(lvl.rng[1]-label.groups*diff(lvl.rng), width[, "center"], dimnames(obj)[[2]]) } else{ plot(gp.rng, lvl.rng, type="n", xlab="", ylab="", bty="n", axes=FALSE, ...) for(i in 1:k){ for(j in 1:n){ if(obj[j,i]<0)next # Top of the "T" rect(width[i, "center"], at[j, "bottom"], width[i, "top"], at[j, "top"], density=(-1), col=col[i], lty="blank") if(obj[j,i]>0) rect(width[i, "bottom"],at.5[j, 1], width[i, "top"],at.5[j, 2], density=(-1), col=col[i], lty="blank") # Leg(s) of the "T" } # Bridge across the top in case of gaps lines(rep(width[i, "top"],2), range(at[obj[, i]>(-1), ]), col=col[i], lwd=lwd) } # Labels? dots <- list(...) cex <- (if(is.null(dots$cex.axis)) 1 else dots$cex.axis) if(!is.na(label.levels)){ text(gp.rng[1]-label.levels*diff(gp.rng), at[, "center"], dimnames(obj)[[1]], cex=cex) } if(!is.na(label.groups)) text(width[, "center"], lvl.rng[1]-label.groups*diff(lvl.rng), dimnames(obj)[[2]], cex=cex) } } "Done" } multcompView/R/extract_p.R0000644000176200001440000000335414414527331015273 0ustar liggesusers#' Extracts p-values #' #' For a given object it will look for the column named "p adj" or "difference" #' and extract its value mantaining its names #' #' #' @aliases extract_p extract_p.default extract_p.TukeyHSD extract_p.mc #' @param x A object that has p-values or logical values. #' @return A named vector with p-values or logical values. #' @author Luciano Selzer #' @seealso \code{\link{multcompLetters}} \code{\link{multcompTs}} #' @keywords manip array #' @export #' @examples #' #' experiment <- data.frame(treatments = gl(11, 20, labels = c("dtl", "ctrl", "treat1", #' "treat2", "treatA2", "treatB", "treatB2", #' "treatC", "treatD", "treatA1", "treatX")), #' y = c(rnorm(20, 10, 5), rnorm(20, 20, 5), rnorm(20, 22, 5), rnorm(20, 24, 5), #' rnorm(20, 35, 5), rnorm(20, 37, 5), rnorm(20, 40, 5), rnorm(20, 43, 5), #' rnorm(20, 45, 5), rnorm(20, 60, 5), rnorm(20, 60, 5))) #' exp_tukey <- TukeyHSD(exp_aov <- aov(y ~ treatments, data = experiment)) #' #' extract_p(exp_tukey) #' #' if(require(pgirmess)){ #' extract_p(kruskalmc(y ~ treatments, data = experiment)) #' } #' #' "extract_p" <- function(x) { UseMethod("extract_p") } #' @export #' @describeIn extract_p #' extract_p.default <- function(x){ ans <- x[ ,"p adj"] #To be sure that names are kept names(ans) <- rownames(x) ans } #' @export #' @describeIn extract_p extract p values from a TukeyHSD object extract_p.TukeyHSD <- function(x) { x <- lapply(x, extract_p.default) x } #' @export #' @describeIn extract_p #' extract_p.mc <- function(x){ ans <- x[["dif.com"]][, "stat.signif"] names(ans) <- rownames(x[["dif.com"]]) ans } multcompView/R/multcompLetters.R0000644000176200001440000003534114414525367016515 0ustar liggesusers#' Letter summary of similarities and differences #' #' Convert a logical vector or a vector of p-values or a correlation or #' distance matrix into a character-based display in which common characters #' identify levels or groups that are not significantly different. Designed #' for use with the output of functions like TukeyHSD, diststats, simint, #' simtest, csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. #' #' Produces a "Letter-Based Representation of All- Pairwise Comparisons" as #' described by Piepho (2004). (The present algorithm does NOT perform his #' "sweeping" step.) \code{multcompLettersx} are wrapper of multcompLetters #' that will reorder the levels of the data so that the letters appear in a #' descending order of the mean. \code{mulcompletters3} is similar to #' \code{multcompletters2} except that it uses vector names to separte and the #' later has an formula interface. \code{multcompLetters4} will take a aov or #' lm object and a comparison test and will produce all the letters for the #' terms and interactions. #' #' @aliases multcompLetters multcompLetters2 multcompLetters3 multcompLetters4 #' @param x One of the following: (1) A square, symmetric matrix with row #' names. (2) A vector with hyphenated names, which identify individual items #' or factor levels after "strsplit". (3) An object of class "dist". If x (or #' x[1]) is not already of class "logical", it is replaced with #' do.call(compare, list(x, threshold)), which by default converts numbers #' (typically p-values) less than 0.05 to TRUE and everything else to FALSE. #' If x is a matrix, its diagonal must be or must convert to FALSE. #' @param compare function or binary operator; not used if class(x) is #' "logical". #' @param threshold Second (reference) argument to "compare". #' @param Letters Vector of distinct characters (or character strings) used to #' connect levels that are not significantly different. They should be #' recogizable when concatonated. The last element of "Letters" is used as a #' prefix for a reuse of "Letters" if more are needed than are provided. For #' example, with the default "Letters", if 53 distinct connection colums are #' required, they will be "a", ..., "z", "A", ..., "Z", and ".a". If 54 are #' required, the last one will be ".b". If 105 are required, the last one will #' be "..a", etc. (If the algorithm generates that many distinct groups, the #' display may be too busy to be useful, but the algorithm shouldn't break.) #' @param reversed A logical value indicating whether the order of the letters #' should be reversed. Defaults to FALSE. #' @param formula The formula used to make the test (lm, aov, glm, etc.). Like #' y ~ x. #' @param data Data used to make the test. #' @param y Value of the response variable. #' @param z Categorical variables used in the test. #' @param object An object of class aov or lm for the time being. #' @param comp A object with multiple comparison or a function name to perform #' a multiple comparison. #' @param ... Extra arguments passed to multcompLetters. #' @return An object of class 'multcompLetters', which is a list with the #' following components: \item{Letters }{character vector with names = the #' names of the levels or groups compared and with values = character strings #' in which common values of the function argument "Letters" identify levels or #' groups that are not significantly different (or more precisely for which the #' corresponding element of "x" was FALSE or was converted to FALSE by #' "compare"). } \item{monospacedLetters }{ Same as "Letters" but with spaces #' so the individual grouping letters will line up with a monspaced type font. #' } \item{LetterMatrix }{Logical matrix with one row for each level compared #' and one column for each "Letter" in the "letter-based representation". The #' output component "Letters" is obtained by concatonating the column names of #' all columns with TRUE in that row. } multcompLetters4 will return a named #' list with the terms containing a object of class 'multcompLetters' as #' produced by \code{multcompLetters}. #' @author Spencer Graves, Hans-Peter Piepho and Luciano Selzer #' @seealso \code{\link{multcompBoxplot}} \code{\link{plot.multcompLetters}} #' \code{\link{print.multcompLetters}} \code{\link{multcompTs}} #' \code{\link{vec2mat}} #' @references Piepho, Hans-Peter (2004) "An Algorithm for a Letter-Based #' Representation of All-Pairwise Comparisons", Journal of Computational and #' Graphical Statistics, 13(2)456-466. #' @keywords dplot #' @export #' @examples #' #' ## #' ## 1. a logical vector indicating signficant differences #' ## #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("A-B", "A-C", "B-C") #' dif3L <- multcompLetters(dif3) #' dif3L #' print(dif3L) #' print(dif3L, TRUE) #' #' ## #' ## 2. numeric vector indicating statistical significance #' ## #' dif4 <- c(.01, .02, .03, 1) #' names(dif4) <- c("a-b", "a-c", "b-d", "a-d") #' (diff4.T <- multcompLetters(dif4)) #' #' (dif4.L1 <- multcompLetters(dif4, #' Letters=c("*", "."))) #' # "Letters" can be any character strings, #' # but they should be recognizable when #' # concatonated. #' #' ## #' ## 3. distance matrix #' ## #' dJudge <- dist(USJudgeRatings) #' dJl <- multcompLetters(dJudge, compare='>', threshold = median(dJudge)) #' # comparison of 43 judges; compact but undecipherable: #' dJl #' #' x <- array(1:9, dim=c(3,3), #' dimnames=list(LETTERS[1:3], NULL) ) #' d3 <- dist(x) #' dxLtrs <- multcompLetters(d3, compare=">", threshold=2) #' #' d3d <- dist(x, diag=TRUE) #' dxdLtrs <- multcompLetters(d3d, compare=">", threshold=2) #' #' \dontshow{stopifnot(} #' all.equal(dxLtrs, dxdLtrs) #' \dontshow{)} #' #' d3u <- dist(x, upper=TRUE) #' dxuLtrs <- multcompLetters(d3d, compare=">", threshold=2) #' #' \dontshow{stopifnot(} #' all.equal(dxLtrs, dxuLtrs) #' \dontshow{)} #' #' ## #' ## 4. cor matrix #' ## #' set.seed(4) #' x100 <- matrix(rnorm(100), ncol=5, #' dimnames=list(NULL, LETTERS[1:5]) ) #' cx <- cor(x100) #' cxLtrs <- multcompLetters(abs(cx), threshold=.3) #' #' #' ## #' ##5. reversed #' ## #' #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("A-B", "A-C", "B-C") #' dif3L <- multcompLetters(dif3) #' dif3L.R <- multcompLetters(dif3, rev = TRUE) #' dif3L #' dif3L.R #' #' #' ## #' ##6. multcompletters2 usage #' #' experiment <- data.frame(treatments = gl(11, 20, labels = c("dtl", "ctrl", "treat1", #' "treat2", "treatA2", "treatB", "treatB2", #' "treatC", "treatD", "treatA1", "treatX")), #' y = c(rnorm(20, 10, 5), rnorm(20, 20, 5), rnorm(20, 22, 5), rnorm(20, 24, 5), #' rnorm(20, 35, 5), rnorm(20, 37, 5), rnorm(20, 40, 5), rnorm(20, 43, 5), #' rnorm(20, 45, 5), rnorm(20, 60, 5), rnorm(20, 60, 5))) #' exp_tukey <- TukeyHSD(exp_aov <- aov(y ~ treatments, data = experiment)) #' exp_letters1 <- multcompLetters(exp_tukey$treatments[,4]) #' exp_letters1 #' #Notice lowest mean treatments gets a "e" #' #Ordered letters #' multcompLetters2(y ~ treatments, exp_tukey$treatments[,"p adj"], experiment) #' multcompLetters2(y ~ treatments, exp_tukey$treatments[,"p adj"], experiment, reversed = TRUE) #' #' ##7. multcompletters3 usage #' #' multcompLetters3("treatments", "y", exp_tukey$treatments[,"p adj"], experiment) #' #' ##8. multcompletters4 usage #' #' #' multcompLetters4(exp_aov, exp_tukey) #' #' "multcompLetters" <- function(x, compare="<", threshold=0.05, Letters=c(letters, LETTERS, "."), reversed = FALSE){ ## ## 1. Covert to logical ## x.is <- deparse(substitute(x)) if(any(class(x)=="dist"))x <- as.matrix(x) if(!is.logical(x)) x <- do.call(compare, list(x, threshold)) ## ## 2. Create array of distinct pairs ## dimx <- dim(x) { if((length(dimx)==2) && (dimx[1]==dimx[2])){ Lvls <- dimnames(x)[[1]] if(length(Lvls)!=dimx[1]) stop("Names requred for ", x.is) else{ # Create a matrix with 2 columns # with the names of all pairs x2. <- t(outer(Lvls, Lvls, paste, sep="")) x2.n <- outer(Lvls, Lvls, function(x1, x2)nchar(x2)) x2.2 <- x2.[lower.tri(x2.)] x2.2n <- x2.n[lower.tri(x2.n)] x2a <- substring(x2.2, 1, x2.2n) x2b <- substring(x2.2, x2.2n+1) x2 <- cbind(x2a, x2b) x <- x[lower.tri(x)] } } else{ namx <- names(x) if(length(namx)!=length(x)) stop("Names required for ", x.is) x2 <- vec2mat2(namx) Lvls <- unique(as.vector(x2)) } } ## ## 3. Find the names of the levels ## n <- length(Lvls) # Generate an initial column LetMat <- array(TRUE, dim=c(n, 1), dimnames=list(Lvls, NULL)) ## ## 4. How many distinct pairs? ## k2 <- sum(x) if(k2==0){ Ltrs <- rep(Letters[1], n) names(Ltrs) <- Lvls dimnames(LetMat)[[2]] <- Letters[1] return(list(Letters=Ltrs, LetterMatrix=LetMat)) } ## ## 4. At last 2 levels are different: ## insert & absorb ## distinct.pairs <- x2[x,,drop=FALSE] absorb <- function(A.){ # Do the work in a recursive function: # Delete any column for which the TRUE # connections are a subset of another column k. <- dim(A.)[2] if(k.>1){ #i. <- 1; j. <- 2 for(i. in 1:(k.-1))for(j. in (i.+1):k.){ if(all(A.[A.[, j.], i.])){ #### drop a redundant column and recurse ### A. <- A.[, -j., drop=FALSE] return(absorb(A.)) } else { if(all(A.[A.[, i.], j.])){ #### drop a redundant column and recurse ### A. <- A.[, -i., drop=FALSE] return(absorb(A.)) } } } } #### end internal function absorb ####### A. } # Now apply this function for(i in 1:k2){ # i <- 1+i # Process the distinct differences one at a time # Insert i <- 1+i # Are (distinct) levels Td2[i, 1] and Td2[i,2] # connected in any columns of A? dpi <- distinct.pairs[i,] ijCols <- (LetMat[dpi[1],] & LetMat[dpi[2], ]) if(any(ijCols)){ # "Insert": Break this connection A1 <- LetMat[, ijCols, drop=FALSE] A1[dpi[1],] <- FALSE LetMat[dpi[2], ijCols] <- FALSE LetMat <- cbind(LetMat, A1) # Absorb A. <- A LetMat <- absorb(LetMat) } } ## ## 5. Sort the columns for visual appeal ## sortCols <- function(B){ firstRow <- apply(B, 2, function(x)which(x)[1]) B <- B[, order(firstRow)] # If ties, sort submatrices firstRow <- apply(B, 2, function(x)which(x)[1]) reps <- (diff(firstRow)==0) if(any(reps)){ # Break ties nrep <- table(which(reps)) irep <- as.numeric(names(nrep)) k <- dim(B)[1] for(i in irep){ i. <- i:(i+nrep[as.character(i)]) j. <- (firstRow[i]+1):k B[j., i.] <- sortCols(B[j., i., drop=FALSE]) } } #### end internal function sortCols ####### B } LetMat. <- sortCols(LetMat) ### Should the letters go in the reversed order? if(reversed) LetMat. <- LetMat.[ ,rev(1:ncol(LetMat.))] # DON'T Sweep #... ## ## 6. Create "Letters" for column names ## k.ltrs <- dim(LetMat.)[2] makeLtrs <- function(kl, ltrs=Letters){ kL <- length(ltrs) if(kl 1)) { Lvls <- levels(interaction(data[,fm[[2]]], sep = ":"))[oz] } else { Lvls <- levels(data[,fm[[2]]])[oz] } value <- vec2mat(x) value <- value[Lvls, Lvls] multcompLetters(value, ...) } #' @export #' @describeIn multcompLetters create a compact letters display and order the #' letters "multcompLetters3" <- function (z, y , x, data, ...) { y.z <- tapply(data[, y], data[, z], function(x) do.call(mean, list(x=x))) oz <- order(y.z, decreasing= T ) #This is to handle interactions if (length(z > 1)) { Lvls <- levels(interaction(data[, z], sep = ":"))[oz] } else { Lvls <- levels(data[, z])[oz] } value <- vec2mat(x) value <- value[Lvls, Lvls] multcompLetters(value, ...) } #' @export #' @describeIn multcompLetters create a compact letters display using a aov object #' "multcompLetters4" <- function (object, comp, ...) { #Extract needed data from object formula <- terms(object) Terms <- colnames(attr(terms(object), "factors")) data <- model.frame(object) fm <- as.character(formula) fm <- fm[-1] fms <- list() for (i in 1:length(Terms)){ fms[[i]] <- formula(paste(fm[1], "~", Terms[i])) } names(fms) <- Terms if(is.character(comp) | is.symbol(comp)) { comp <- match.fun(comp) comp <- comp(object) } comp <- extract_p(comp) ans <- list() for(i in 1:length(Terms)){ ans[[i]] <- list(formula = fms[[i]], p = comp[[i]]) } names(ans) <- Terms lapply(ans, function(x) multcompLetters2(x$formula, x$p, data, ...)) } multcompView/R/multcompView-package.R0000644000176200001440000000364014414525367017373 0ustar liggesusers #' Summarize multiple paired comparisons #' #' Convert a logical vector or a vector of p-values or a difference or distance #' matrix into a display identifying the pairs for which the differences were #' not significantly different or for which the difference exceeded a #' threshold. #' #' \tabular{ll}{ Package: \tab multcompView\cr Type: \tab Package\cr Version: #' \tab 0.1-0\cr Date: \tab 2006-08-06\cr License: \tab GPL\cr } Convert a #' logical vector or a vector of p-values or a difference or distance matrix #' into either a letter-based display using "multcompLetters" or a graphic #' roughly like a "T" using "multcompTs" to identify factor levels or similar #' groupings that are or are not significantly different. Designed for use in #' conjunction with the output of functions like TukeyHSD, diststats, simint, #' simtest, csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. #' #' @name multcompView-package #' @aliases multcompView-package multcompView #' @docType package #' @author Spencer Graves and Hans-Peter Piepho with help from Sundar Dorai-Raj #' #' Maintainer: Spencer Graves #' @references Piepho, Hans-Peter (2004) "An Algorithm for a Letter-Based #' Representation of All-Pairwise Comparisons", Journal of Computational and #' Graphical Statistics, 13(2)456-466. #' #' John R. Donaghue (2004) "Implementing Shaffer's multiple comparison #' procedure for a large number of groups", pp. 1-23 in Benjamini, Bretz and #' Sarkar (eds) Recent Developments in Multiple Comparison Procedures #' (Institute of Mathematical Statistics Lecture Notes-Monograph Series vol. #' 47) #' @keywords package aplot dplot htest #' @examples #' #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("a-b", "a-c", "b-c") #' multcompTs(dif3) #' multcompLetters(dif3) #' #' library(MASS) #' multcompBoxplot(Postwt~Treat, data=anorexia) #' NULL multcompView/R/multcompLetters2.R0000644000176200001440000000130614414525367016571 0ustar liggesusers"multcompLetters2" <- function (formula, x, data, ...) { #Convert formula to character, get rid of "~" fm <- as.character(formula) fm <- fm[-1] #Split char vector with ":" as this points an #interaction and is not included in the data #per se fm <- strsplit(fm, ":", fixed = TRUE) y.z <- tapply(data[,fm[[1]]], data[,fm[[2]]], function(x) do.call(mean, list(x=x))) oz <- order(y.z, decreasing= T ) #This is to handle interactions if (length(fm[[2]] > 1)) { Lvls <- levels(interaction(data[,fm[[2]]], sep = ":"))[oz] } else { Lvls <- levels(data[,fm[[2]]])[oz] } value <- vec2mat(x) value <- value[Lvls, Lvls] multcompLetters(value, ...) } multcompView/R/vec2mat.R0000644000176200001440000000754514414525367014660 0ustar liggesusers#' Convert a vector with hyphenated names into a matrix. #' #' Convert a vector with hypehnated names into a symmetric matrix with names #' obtained from vect2mat2(names(x)). #' #' x must have names each of which contains exactly one hyphen; if not, vec2mat #' issues an error message. If the same comparison is present multiple times, #' the last value is used; no check is made for duplicates. #' #' @param x Either (1) a vector with hyphenated names indicating pairs of #' factor levels, groups or items that are and are not significantly different #' or (2) a matrix indicating same. If x is already a matrix, it is checked #' for symmetry. NAs are not allowed. #' @param sep "strsplit" character to apply to names(x). #' @return A symmetrix matrix of the same class as the input with names #' obtained from unique(strsplit(names(x))). All nonspecified elements will be #' 1 if class(x) is numeric, FALSE if logical and "" if character. Used by the #' functions 'multcompLetters' and 'multcompTs'. #' @author Spencer Graves #' @seealso \code{\link{multcompLetters}} \code{\link{multcompTs}} #' @keywords manip array #' @export #' @examples #' #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("a-b", "a-c", "b-c") #' vec2mat(dif3) #' #' dif3. <- 1:3 #' names(dif3.) <- c("a-b", "a-c", "b-c") #' vec2mat(dif3.) #' #' dif.ch <- c("this",'is','it') #' names(dif.ch) <- c("a-b", "a-c", "b-c") #' vec2mat(dif.ch) #' #' vec2mat(array(1, dim=c(2,2))) #' \dontshow{ #' try(vec2mat(array(1:24, dim=2:4)))# must be 2-d #' try(vec2mat(array(1:6, dim=2:3)))# must be square #' try(vec2mat(array(1:4, dim=c(2,2))))# must be symmetric #' try(vec2mat(array(1, dim=c(2,2)))) # diag should be 0 #' try(vec2mat(array(TRUE, dim=c(2,2)))) # diag should be FALSE #' try(vec2mat(array("a", dim=c(2,2)))) # diag should be "" #' #' try(vec2mat(c(1:3, NA))) # NAs not allowed #' try(vec2mat(1:3))# Error: No names #' #' errVec2 <- 1:3 #' names(errVec2) <- c("a", "b-a", "b-c") #' try(vec2mat(errVec2))# Error: missing hyphen (sep character) #' #' errVec3 <- 1:3 #' names(errVec3) <- c("a-c", "b-a", "b-c-d") #' try(vec2mat(errVec3)) #' # Error: multiple hyphens (sep characters) #' #' dif4 <- 1:4 #' names(dif4) <- c("a-b", "a-c", "b-c", "b-a") #' # Both "b-a" and "a-b" specified; #' # use the latest. #' vec2mat(dif4) #' } #' "vec2mat" <- function (x, sep = "-") { n.na <- sum(is.na(x)) x.is <- deparse(substitute(x)) if (n.na > 0) stop(n.na, " NAs not allowed, found in ", x.is) dimx <- dim(x) l.dimx <- length(dimx) clpse <- function(x, collapse = ", ") paste(x, collapse = collapse) x.not.sq <- ((l.dimx > 2) || ((l.dimx == 2) && (dimx[1] != dimx[2]))) if (x.not.sq) stop("Array of dim(", clpse(dimx), ") not allowed for ", x.is) if (l.dimx == 2) { if (any(x != t(x))) stop("Matrix not symmetric ", x.is) return(x) } namx <- names(x) if (length(namx) != length(x)) stop("Names required for ", deparse(substitute(x))) x.lvls <- vec2mat2(namx, sep) Lvls <- unique(as.vector(x.lvls)) n.lvls <- length(Lvls) x0 <- { if (is.numeric(x)) 1 else if (is.logical(x)) FALSE else if (is.character(x)) "" else stop("Must be class numeric, logical or ", "character; instead is ", class(x)) } X <- array(x0, dim = c(n.lvls, n.lvls), dimnames = list(Lvls, Lvls)) i.lvls <- 1:n.lvls names(i.lvls) <- Lvls ix.lvls <- array(i.lvls[x.lvls], dim = dim(x.lvls)) rev.ix <- (ix.lvls[, 1] > ix.lvls[, 2]) if (any(rev.ix)) ix.lvls[rev.ix, ] <- ix.lvls[rev.ix, 2:1] X[ix.lvls] <- x X[lower.tri(X)] <- t(X)[lower.tri(X)] X } multcompView/R/plot.multcompTs.R0000644000176200001440000002054614414525367016437 0ustar liggesusers#' plot multcomp graphics #' #' Plot graphic(s) for multcompTs or multcompLetters objects #' #' The requested graphic is either plotted by itself or added to an existing #' plot as specified by the arguments. The placement can be controlled by #' 'fig' and 'at'. #' #' The fontsize and fontface of a plot of a multcompLetters object with 'type = #' "Letters"' can be adjusted as describe on the \code{\link[grid]{gpar}} help #' page. #' #' @param x an object of class 'multcompTs' or 'multcompLetters'. #' @param horizontal A logical scalar indicating whether the list of items #' compared reads left to right (horizontal = TRUE) or top to bottom #' (horizontal = FALSE). If this multcomp graphic accompanies boxplots for #' different levels or groups compared, the 'boxplot' argument 'horizontal' is #' the negation of the multcomp plot 'horizontal' argument. #' @param col The color for each group of items or factor levels. The colors #' will cross the different items or factor levels and will therefore have the #' orientation specified via 'horizontal'. If the number of columns exceeds #' length(col), col is recycled. For alternative choices for col, see "Color #' Specification" in the \code{\link{par}} help page. #' @param type An alternative display for either multcompTs or multcompLetters #' is 'boxes' (or rectangles). If type="boxes" with "multcompTs", the #' "base(s)" of each "T" will be indicated by a triangle. #' @param orientation The "standard" orientation has the 'multcompTs' pointing #' towards the names of the items or factor levels; with the "reverse" #' orientation, the bases of the "Ts" point away. By default, the names are on #' the left or below unless the mean of the relevant 'fig' range is less than #' 0.5. #' @param add TRUE to add to an existing plot; FALSE to start a new plot. The #' names of the factor levels or items compared will be plotted only if #' add=FALSE. #' @param at A numeric vector or matrix or a list with components "at" and #' "width". If a list, both components must be either a numeric vector or #' matrix. The numeric vector "at" (whether the function argument or "at" #' component of the "at" list) must be either a numeric vector or matrix giving #' the locations where the "Ts" or "Letters" graphics should be drawn. #' length(at) is 1, 2 or 3 times the number of the number of factor levels or #' items compared. If length(at) is twice the number of levels or items #' compared, it gives the range of the display for that level; the base of a #' "T" will be at the midpoint. If length(at) is three times the number of #' items compared, the intermediate number will be the center of the base of #' the "T". #' @param width A numeric vector or matrix with as many rows as "Ts" or #' "groups" and with up to three columns. With one column, it will be the #' "center" of the plot range for that group. With two columns, they will #' delimit the range. With three, they will provide "bottom", "center", and #' "top" of the range for that set of grouping indicators. If "at" is a list, #' the argument "width" is ignored and is taken from the list "at". #' @param fig A numerical vector of the form 'c(x1, x2, y1, y2)' giving the #' coordinates of the figure region in the display region of the plot device, #' as described on the \code{\link{par}} help page. #' @param lwd width of line to connect elements of "T" graphics that might not #' otherwise be connected. #' @param label.levels NA for no labels or distance away from the plot for the #' labels as a proportion of the plot range. #' @param label.groups NA for no labels or distance away from the plot for the #' labels as a proportion of the plot range. #' @param T.base A numeric scalar giving the proportion of the available space #' devoted to the base of the Ts; used only when type="Ts". #' @param ... graphical parameters can be given as described on the #' \code{\link{plot}} help page or for plot.multcompLetters as describe on the #' \code{\link[grid]{gpar}} help page. #' @return A list with two components: \item{at }{ A matrix with three columns #' giving the middle and extremes of the display for each of the factor levels #' or items compared. } \item{width }{ A matrix with as many rows as "Ts" or #' comparitor levels and with two columns giving the plot range for that #' comparitor level. } #' @author Spencer Graves #' @seealso \code{\link{multcompTs}} \code{\link{multcompLetters}} #' \code{\link{multcompBoxplot}} \code{\link[grid]{gpar}} #' @keywords aplot #' @examples #' #' ## #' ## plot(multcompTs(...)) #' ## #' dif4 <- c(.1, .02, .03, 1) #' names(dif4) <- c("A-B", "A-C", "B-C", "A-D") #' (mcT4 <- multcompTs(dif4)) #' # Standard plot, base of "Ts" point left #' mcT4.1 <- plot(mcT4, label.groups=0.05) #' # Redo using "at" = list #' plot(mcT4, label.groups=0.05, at=mcT4.1) #' # Same plot with group labels closer to the figure #' plot(mcT4, label.groups=0.02) #' #' # Base of "Ts" point right #' plot(mcT4, label.groups=TRUE, orientation="r") #' # Base of "Ts" point down #' plot(mcT4, horizontal=TRUE, label.groups=0.05) #' # Base of "Ts" point up #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' orientation="r") #' #' # Same 4 plots but with boxes & triangles, not Ts #' plot(mcT4, label.groups=0.05, type="b") #' plot(mcT4, label.groups=0.05, orientation="r", #' type="b") #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' type="b") #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' orientation="r", type="b") #' #' ## #' ## plot(multcompLetters(...)) #' ## #' # ... using dif4 from above #' (mcL4 <- multcompLetters(dif4, Letters=LETTERS)) #' # Standard plot #' \dontrun{ #' # Requires (grid) #' mcL4.1 <- plot(mcL4, label.groups=0.05) #' # Redo using "at" = list #' plot(mcL4, label.groups=0.05, at=mcL4.1) #' #' # With bold face and larger font #' plot(mcL4, label.groups=0.05, #' fontsize=28, fontface="bold") #' #' # Horizontal rather than vertical #' plot(mcL4, horizontal=TRUE, label.groups=0.05) #' } #' #' # Same as boxes rather than letters #' plot(mcL4, label.groups=0.05, type="b") #' plot(mcL4, horizontal=TRUE, label.groups=0.05, #' type="b") #' @importFrom graphics par text lines polygon rect #' @export "plot.multcompTs" <- function(x, horizontal=FALSE, col=1:6, type=c("Ts", "boxes"), orientation=c("standard", "reverse"), add=FALSE, at, width, fig=c(0, 1, 0, 1), lwd=3, label.levels=if(add)NA else 0.05, label.groups=NA, T.base=0.4, ...){ ## ## 1. Get row and column names ## obj <- deparse(substitute(x)) lvls <- dimnames(x)[[1]] gps <- dimnames(x)[[2]] n <- length(lvls) k <- length(gps) if((n==0) | (k==0)) stop("dimnames required for ", obj) col <- rep(col, len=k) ## ## 2. Get plotting positions for lvls and gps ## At <- function(x, lvls, d){ N <- length(lvls) if(length(x)<=N) x <- t(outer(c(-0.4, 0, 0.4), x, "+")) else{ x <- apply(x, 2, sort) if(length(x)<(3*N)) x <- cbind(x[, 1], mean(x, 2, mean), x[, 2]) } dimnames(x) <- list(lvls, c("bottom", "center", "top")) x } # at.list <- FALSE missW <- missing(width) { if(missing(at)){ at <-{ if(horizontal) 1:n else n:1 } } else if(is.list(at)){ at.list <- TRUE if(is.null(names(at))) names(at) <- c("at", "width") width <- at$width at <- at$at } } # if(!at.list){ if(missW){ width <- { if(horizontal) k:1 else 1:k } } width <- At(width, gps) at <- At(at, lvls) } or. <- match.arg(orientation) ## ## 3. Set up the plot ## op <- { if(add)par(fig=fig, xpd=NA, new=TRUE) else par(fig=fig, xpd=NA) } on.exit(par(op)) # { if(match.arg(type)=="Ts") plotTs(obj=x, at=at, width=width, horizontal=horizontal, col=col, add=add, lwd=lwd, label.levels=label.levels, label.groups=label.groups, T.base=T.base, orientation=or., ...) else plotBoxes(obj=x, at=at, width=width, horizontal=horizontal, col=col, add=add, label.levels=label.levels, label.groups=label.groups, orientation=or., ...) } list(at=at, width=width) } multcompView/R/multcompLetters4.R0000644000176200001440000000137714414525367016603 0ustar liggesusers"multcompLetters4" <- function (object, comp, ...) { #Extract needed data from object formula <- terms(object) Terms <- colnames(attr(terms(object), "factors")) data <- model.frame(object) fm <- as.character(formula) fm <- fm[-1] fms <- list() for (i in 1:length(Terms)){ fms[[i]] <- formula(paste(fm[1], "~", Terms[i])) } names(fms) <- Terms if(is.character(comp) | is.symbol(comp)) { comp <- match.fun(comp) comp <- comp(object) } comp <- extract_p(comp) ans <- list() for(i in 1:length(Terms)){ ans[[i]] <- list(formula = fms[[i]], p = comp[[i]]) } names(ans) <- Terms lapply(ans, function(x) multcompLetters2(x$formula, x$p, data, ...)) } multcompView/R/multcompTs.R0000644000176200001440000001435514414525367015463 0ustar liggesusers#' "T" depiction of undiffentiated classes #' #' Convert a logical vector or a vector of p-values or a correlation or #' distance matrix into a matrix with an associated visual display to show #' whether the differences between items exceed a threshold. Designed for use #' with the output of functions like TukeyHSD, diststats, simint, simtest, #' csimint, csimtestmultcomp, friedmanmc, kruskalmcpgirmess. #' #' Produces a matrix of class "multcompTs", describing the "undifferentiated #' classes" that identify the other factor levels or items that are not #' distinct or not significantly different from the "base" of the "T"; if two #' or more levels have the same pattern of significant differences, the two are #' combined into one "T" with two "bases". The resulting T's are similar to #' the "undifferentiated classes" discussed by Donaghue (2004). #' #' @param x One of the following: (1) A square, symmetric matrix with row #' names. (2) A vector with hyphenated names, which identify individual items #' or factor levels after "strsplit(..., '-')". (3) An object of class "dist". #' #' If x (or x[1]) is not already of class "logical", it is replaced with #' do.call(compare, list(x, threshold)), which by default converts numbers #' (typically p-values) less than 0.05 to TRUE and everything else to FALSE. #' If x is a matrix, its diagonal must be or must convert to FALSE. #' @param compare function or binary operator; not used if class(x) is #' "logical". #' @param threshold Second (reference) argument to "compare". #' @param sep Concatonation character for names of objects with identical #' similarity / dissimilarity patterns. The output of multcompTs is matrix for #' which the number of rows = (number of columns + number of uses of the "sep" #' character). #' @return An object of class "multcompTs", which is a matrix of values -1, 0, #' 1, with one row for each level compared and one column for each "T", read as #' follows: 1 = base of the "T" represented by that column, 0 = level(s) not #' significantly different, and (-1) = leves(s) significantly different. If #' two or more levels have the same pattern of significant and insignificant #' differences, they are combined into a single column that can be represented #' by a "T" with multiple bases. The column name will be a character string #' concatonating all row names with "1" in that column separated by the "sep" #' character. Thus, the matrix should have as many 1's as it has rows. Also, #' the lower triangular portion should have as many "-1's" as there are "TRUE" #' (e.g., significant) differences among the comparisons. #' @author Spencer Graves and Hans-Peter Piepho #' @seealso \code{\link{multcompBoxplot}} \code{\link{multcompLetters}} #' \code{\link{plot.multcompTs}} \code{\link{vec2mat}} \code{\link{dist}} #' @references John R. Donaghue (2004) "Implementing Shaffer's multiple #' comparison procedure for a large number of groups", pp. 1-23 in Benjamini, #' Bretz and Sarkar (eds) Recent Developments in Multiple Comparison Procedures #' (Institute of Mathematical Statistics Lecture Notes-Monograph Series vol. #' 47) #' #' Spencer Graves and Hans-Peter Piepho (2006) "Simple Visualizations of Paired #' Comparisons", \href{../doc/VisualizingPairedComparisons.pdf}{\code{vignette("VisualizingPairedComparisons", package = "multcompView")}} #' #' @keywords dplot #' @export #' @examples #' #' ## #' ## 0. Conference presentation comparing Ts and Letters #' ## #' dir(system.file('doc', package='multcompView'), #' pattern='\\.pdf$', full.name=TRUE) #' #' ## #' ## 1. logical vector indicating different pairs #' ## #' dif3 <- c(FALSE, FALSE, TRUE) #' names(dif3) <- c("a-b", "a-c", "b-c") #' multcompTs(dif3) #' #' ## #' ## 2. numeric vector indicating statistical significance #' ## #' dif4 <- c(.01, .02, .03, 1) #' names(dif4) <- c("a-b", "a-c", "b-d", "a-d") #' (diff4.T <- multcompTs(dif4)) #' plot(diff4.T) #' #' ## #' ## 3. Distance matrix #' ## #' dJudge <- dist(USJudgeRatings) #' dJt <- multcompTs(dJudge, compare='>', threshold = median(dJudge)) #' # comparison of 43 judges; compact but undecipherable: #' plot(dJt, cex.axis=.5) #' #' x <- array(1:9, dim=c(3,3), #' dimnames=list(LETTERS[1:3], NULL) ) #' d3 <- dist(x) #' dxTs <- multcompTs(d3, compare=">", threshold=2) #' plot(dxTs) #' #' d3d <- dist(x, diag=TRUE) #' dxdTs <- multcompTs(d3d, compare=">", threshold=2) #' #' \dontshow{stopifnot(} #' all.equal(dxTs, dxdTs) #' \dontshow{)} #' #' d3u <- dist(x, upper=TRUE) #' dxuTs <- multcompTs(d3d, compare=">", threshold=2) #' #' \dontshow{stopifnot(} #' all.equal(dxTs, dxuTs) #' \dontshow{)} #' #' ## #' ## 4. cor matrix #' ## #' set.seed(4) #' x100 <- matrix(rnorm(100), ncol=5, #' dimnames=list(NULL, LETTERS[1:5]) ) #' cx <- cor(x100) #' cxTs <- multcompTs(abs(cx), threshold=.3) #' plot(cxTs) #' #' "multcompTs" <- function(x, compare="<", threshold=0.05, sep="."){ ## ## 1. Covert to logical ## if(any(class(x) == "dist"))x <- as.matrix(x) if(!is.logical(x)) x <- do.call(compare, list(x, threshold)) ## ## 2. Convert to a symmetric matrix ## x. <- vec2mat(x) if(any(diag(x.))) stop("Diag(x) must be or translate to FALSE;", " x = ", paste(x, collapse=", ")) ## ## 3. Code insignificance as 0 ## and significance as (-1) ## k <- dim(x.)[1] x1 <- (1+x.) Dif <- array(c(0, -1)[x1], dim=c(k,k), dimnames=dimnames(x.)) diag(Dif) <- 1 ## ## 4. To find recodes 0's as 1 ## then duplicate columns will ## have inner product = k ## dup.5 <- array(c(1, -1)[x1], dim=c(k,k), dimnames=dimnames(x.)) # Dup <- (crossprod(dup.5)==k) ## ## 5. Look for dups only in the upper triangle ## and drop all that are found ## Dup[lower.tri(Dup, diag=TRUE)] <- FALSE dup.i <- which(colSums(Dup)>0) if(length(dup.i)>0){ for(i in dup.i){ j.i <- which(Dup[,i])[1] Dif[i, j.i] <- 1 colNms <- dimnames(Dif)[[2]] j.i.Nm <- paste(colNms[c(j.i, i)], collapse=sep) dimnames(Dif)[[2]][j.i] <- j.i.Nm } Dif <- Dif[, -dup.i, drop=FALSE] } ## ## 6. Done ## class(Dif) <- "multcompTs" Dif } multcompView/R/plotLetters.R0000644000176200001440000002203414414525367015626 0ustar liggesusers#' plot multcomp displays #' #' Helper functions for plot.multcompTs and plot.multcompLetters. These not #' intended to be called directly and are hidden in a namespace. You can use #' 'getAnywhere' to see them. #' #' The requested graphic is either plotted by itself or added to an existing #' plot as specified by the arguments. #' #' "plotTs" and "plotBoxes" use traditional R graphics and will not be #' discussed further here. #' #' "plotLetters" uses 'grid' graphics, because it seems to provide more support #' for controlling the side-by-side placement of "Letters" of possibly #' different colors and widths. The "Letters" display will be positioned in #' the "plot region" defined by fig and mar, assuming the entire device region #' is 37 lines both wide and tall. Thus, the plot region is diff(fig[1:2])*37 #' lines wide and diff(fig(1:2])*37 lines high. If, for example, fig = c(0.9, #' 1, 0, 1), this makes the plot region 3.7 lines wide. With the default #' mar=c(5, 4, 4, 2)+0.1 lines, the "width" of the plot region is therefore 3.7 #' - (4.1+2.1) = (-2.5) lines. "plotLetters" initially ignores this #' contradictory negative width, and centers the plot at the midpoint of h0 = #' fig[1]+mar[2]/37, h1 = fig[2]-mar[4]/37, v0 = fig[3]+mar[1]/37, and v1 = #' fig[4]-mar[3]/37. The "Letters" for the different levels compared are #' rescaled from at[, "center"] to fit inside At.rng = if(horizontal) c(h0, h1) #' else c(v0, v1). With "n" levels compared and at.rng = range(at[, #' "center"]), at[, "center"] is expanded to (at.rng+/-0.5) and rescaled to #' match At.rng; if(diff(At.rng)<=0), an error message is issued. #' #' Meanwhile, the "Letters" are centered at the midpoint of W.rng = #' if(horizontal) c(v0, v1) else v(h0, h1) [the opposite of At.rng]; the #' argument "width" used by plotTs and plotBoxes is not used (and not even #' accepted) by plotLetters. If(label.levels), these are positioned in the #' midpoint of the right margin in the "W" direction. #' #' @aliases plotLetters #' @param obj a matrix describing which levels (rows) will be plotted with #' which groups (columns). For plotTs and plotBoxes, obj is a matrix of #' numbers from (-1, 0, 1). For plotLetters, obj is a logical matrix = TRUE if #' that "letter" (group or column of obj) is to be plotted with that level (row #' of obj). #' @param at an array with one row for each level and 3 columns giving low, #' middle and high levels for the display for that level. #' @param width an array with one row for each group of levels in the display #' and 3 columns giving low, middle and high levels for the display for that #' group. #' @param horizontal A logical scalar indicating whether the list of items #' compared reads left to right (horizontal = TRUE) or top to bottom #' (horizontal = FALSE). If this multcomp graphic accompanies boxplots for #' different levels or groups compared, the 'boxplot' argument 'horizontal' is #' the negation of the multcomp plot 'horizontal' argument. #' @param col The color for each group of items or factor levels. The colors #' will cross the different items or factor levels and will therefore have the #' orientation specified via 'horizontal'. If the number of columns exceeds #' length(col), col is recycled. For alternative choices for col, see "Color #' Specification" in the \code{\link{par}} help page. #' @param add TRUE to add to an existing plot; FALSE to start a new plot. The #' names of the factor levels or items compared will be plotted only if #' add=FALSE. #' @param lwd line width for the display outline. #' @param label.levels Distance from the plot region to print the names of the #' levels as a proportion of the plot range; NA for no level labels. #' @param label.groups Distance from the plot region to print the names of the #' groups as a proportion of the plot range; NA for no level labels. #' @param T.base A numeric scalar giving the proportion of the available space #' devoted to the base of the Ts. #' @param orientation If 'reversed', the base(s) of each "T" or traingle #' indicating the master level(s) of that "undifferentiated class" will point #' right or up (depending on horizontal) rather than down or left. #' @param font.family character string naming the font family used by #' "plotLetters". This function plots the different "Letters" in different #' colors by plotting one color at a time. It's currently not smart enough to #' align the letters properly except by assuming a mono-spaced font. #' @param fig figure region = (x0, x1, y0, y1) as a proportion of the device #' region. #' @param mar margin = (lower, left, upper, right) in lines. #' @param ... graphical parameters can be given as described on the #' \code{\link{plot}} help page or the \code{\link[grid]{gpar}} help page. #' @return "Done" #' @author Spencer Graves #' @seealso \code{\link{plot.multcompTs}} \code{\link{plot.multcompLetters}} #' \code{\link[grid]{gpar}} #' @keywords aplot internal #' @examples #' #' # Designed to be called from plot.multcompTs #' # or plot.multcompLetters, NOT directly by users. #' @importFrom grid grid.newpage viewport pushViewport unit textGrob gpar grobHeight #' @importFrom grid convertHeight grobWidth convertWidth grid.text popViewport #' @export "plotLetters" <- function(obj, at, horizontal, col, add, label.levels, font.family="mono", fig=par("fig"), mar=par("mar"), ...){ ## ## 1. Modify "par" ## if(!add) grid::grid.newpage() # op <- par(family=font.family) on.exit(par(op)) ## ## 2. Set up 'grid' graphics ## # Use 'grid' graphics for 2 reasons: # (1) I couldn't figure out how to get # consistent alignment with overlays # using 'text' # (2) 'grid' will compute the size # of characters, so I can use that # to determine plotting positions. vpFig <- grid::viewport(name="vp.fig") grid::pushViewport(vpFig) # angle <- 90*horizontal lvl.rng <- range(at[, "center"]) ## ## 3. Compute figure and plot regions ## n <- dim(obj)[1] k <- dim(obj)[2] # Figure region W.fig <- fig[(1:2)+2*horizontal] At.fig <- fig[(3:4)-2*horizontal] # Figure margins At.mar <- mar[c(1, 3)+horizontal] W.mar <- mar[c(2, 4)-horizontal] # Plot region At.rng <- (At.fig+c(1, -1)*At.mar/37) W.rng <- (W.fig+c(1, -1)*W.mar/37) ## ## 4. Rescale "at" to Grid's "npc" ## = "normalized parent coordinates" ## within fig and mar ## at.rng <- (range(at[, "center"])+c(-0.5, 0.5)) d.at <- diff(at.rng) d.At <- diff(At.rng) At <- (At.rng[1]+d.At*( at[, "center"]-at.rng[1])/d.at) # At.npc <- unit(At, "npc") # At.nat <- unit(At, "native") ## ## 5. Convert "Letters" to grobs = ## Grid "graphics objects" ## n <- dim(obj)[1] k <- dim(obj)[2] Ltrs <- dimnames(obj)[[2]] k1 <- k+1 LtrsM <- c(Ltrs, "M") LtrsM. <- c(Ltrs, "Ref.M.") gLtrs <- vector(k1, mode="list") names(gLtrs) <- LtrsM # npc0 <- unit(0, "npc") nat0 <- grid::unit(0, "native") for(j in 1:k1) gLtrs[[j]] <- grid::textGrob(LtrsM[j], rot=angle,x=nat0, y=nat0, name=LtrsM.[j], gp=grid::gpar(col=col[j], ...)) # name=LtrsM.[j], gp=gpar(...)) ## ## 6. Compute character widths ## wLtrs <- rep(NA, k1) names(wLtrs) <- LtrsM { if(horizontal) for(j in 1:k1){ gH.j <- grid::grobHeight(gLtrs[[j]]) wLtrs[j] <- grid::convertHeight(gH.j, "native", valueOnly=TRUE) } else for(j in 1:k1){ gW.j <- grid::grobWidth(gLtrs[[j]]) wLtrs[j] <- grid::convertWidth(gW.j, "npc", valueOnly=TRUE) } } ## ## 7. Rescale to W.rng ## # 7.1. maxX = max width including Ref.M. maxW <- max(wLtrs) # 7.2. w.Ltrs = adj. width excl. Ref.M. w.Ltrs <- 0.5*(wLtrs[-k1]+maxW) # 7.3. Convert to a scale in "npc" sumW <- cumsum(w.Ltrs) # 7.4. width(in "npc") = adjustment to W.rng w0 <- mean(W.rng) W <- (w0+sumW-mean(range(sumW))) # W.npc <- unit(W, "npc") # W.nat <- unit(W, "native") ## ## 8. Plot ## { if(horizontal) for(j in 1:k){ n.j <- sum(obj[, j]) Ltr.j <- rep(Ltrs[j], n.j) W.j <- rep(W[j], n.j) At.j <- At[obj[, j]] grid::grid.text(Ltr.j, At.j, W.j, rot=90, gp=grid::gpar(col=col[j], ...)) } else for(j in 1:k){ n.j <- sum(obj[, j]) Ltr.j <- rep(Ltrs[j], n.j) W.j <- rep(W[j], n.j) At.j <- At[obj[, j]] grid::grid.text(Ltr.j, W.j, At.j, gp=grid::gpar(col=col[j], ...)) } } ## ## 9. Label the levels? ## if(!is.na(label.levels)){ lvls <- dimnames(obj)[[1]] # W.mar = (W.rng[1]- 0.5*dW - label.levels) W.mar <- (W[1]-0.5*wLtrs[1]-label.levels) W.n <- rep(W.mar, n) if(horizontal){ grid::grid.text(lvls, At, W.n, rot=90) }else{ grid::grid.text(lvls, W.n, At) } } ## ## 10. Clean up and quit. ## grid::popViewport() # "Done" } multcompView/R/vec2mat2.R0000644000176200001440000000277214414525367014737 0ustar liggesusers#' Convert a vector of hyphenated names into a character matrix. #' #' Convert a vector of hyphenated names into a character matrix with 2 columns #' containing the names split in each row. #' #' If each element of x does not contain exactly 1 "sep" character, an error is #' issued. #' #' @param x Vector of hyphenated names #' @param sep "strsplit" character to apply to names(x). #' @return A character matrix with rownames = x and with the character string #' preceeding the "sep" character in the first column and the character string #' following the "sep" character in the second column. #' @author Spencer Graves #' @seealso \code{\link{vec2mat}} \code{\link{multcompLetters}} #' @keywords manip array #' @export #' @examples #' #' vec2mat2(c("a-b", "a-c", "b-c")) #' #' vec2mat2(c("a-b", "b-a")) #' #' \dontshow{ #' (tst3 <- substring(try( #' vec2mat2(c("a", "b-a", "b-c"))), 1, 20) #' =="Error in vec2mat2(c(") #' # Error: name without a sep character #' #' (tst4 <- substring(try( #' vec2mat2(c("a-c", "b-a", "b-c-d"))), 1, 20) #' =="Error in vec2mat2(c(") #' # Error: multiple hyphens (sep characters) #' #' } #' "vec2mat2" <- function (x, sep = "-") { splits <- strsplit(x, sep) n.spl <- sapply(splits, length) if (any(n.spl != 2)) stop("Names must contain exactly one '", sep, "' each; instead got ", paste(x, collapse = ", ")) x2 <- t(as.matrix(as.data.frame(splits))) dimnames(x2) <- list(x, NULL) x2 } multcompView/R/multcompLetters3.R0000644000176200001440000000066114414525367016575 0ustar liggesusers"multcompLetters3" <- function (z, y , x, data, ...) { y.z <- tapply(data[, y], data[, z], function(x) do.call(mean, list(x=x))) oz <- order(y.z, decreasing= T ) #This is to handle interactions if (length(z > 1)) { Lvls <- levels(interaction(data[, z], sep = ":"))[oz] } else { Lvls <- levels(data[, z])[oz] } value <- vec2mat(x) value <- value[Lvls, Lvls] multcompLetters(value, ...) }multcompView/R/multcompBoxplot.R0000644000176200001440000002263414414525367016523 0ustar liggesusers#' boxplot with multcomp graphics #' #' Create boxplots with multcompTs and / or multcompLetters #' #' For formula = y~z, if 'sortFn' is a function or the name of a function, #' 'multcompBoxplot' starts by applying sortFn to the subsets of y #' corresponding to each level of z, and then sorting those summaries in #' increasing or decreasing order, per 'decreasing'. If 'sortFn' is NULL or #' NA, this sort step is skipped. #' #' 'multcompBoxplot' then creates 'boxplot' as specified in 'plotList'. Next, #' 'compFn' is called to generate comparisons to feed to the functions #' (\code{\link{multcompTs}} and / or \code{\link{multcompLetters}}, whose #' output is then passed to (\code{\link{plot.multcomp}}) for plotting. #' Components of the relevant sublists of 'plotList' are made available to #' \code{\link{par}} or (for \code{\link{plot.multcompLetters}}) to #' \code{\link[grid]{gpar}}. #' #' @param formula a two sided formula like "y~z", where both "y" and "z" are #' columns of the data.frame "data", "y" is numeric, and "z" is a factor. This #' will be passed as the first argument for both 'boxplot' and 'compFn', and so #' must work in both contexts. NOTE: Any more complicated formula may produce #' errors or unanticipated results. #' @param data A data.frame for evaluating 'formula'. #' @param horizontal TRUE for horizontal boxplots and vertical multcompTs and / #' or multcompLetters; FALSE for the opposite. #' @param compFn a function whose output will serve as the the only non-default #' input to either 'multcompTs' or 'multcompLetters'. The default "TukeyHSD" #' actually translates to 'TukeyHSD(aov(formula, data))[[1]][, "p adj"]'. #' @param sortFn If sortFn is a function or a character string naming a #' function, it is used to summarize the subset of y corresponding to each #' level of z into a single number, which will then be used to sort the levels #' of z according to the argumment 'decreasing'. This step is skipped if #' sortFn is NULL or NA or if it is neither a function nor a character string #' that might name a function. If sortFn is a character string but a function #' by that name is not found in the search path, multcompBoxplot stops with, #' 'Error in do.call(sortFn, list(x = x)) : could not find function ...'. #' @param decreasing If the levels of z are to be sorted using the output of #' 'sortFn', this is uses as the 'decreasing' in 'order' to sort the levels of #' z for plotting. #' @param plotList A list with names in c("boxplot", "multcompTs", #' "multcompLetters"). Replicates are allowed. If present, they produce, #' e.g., multiple "multcompTs" side by side. This can be used to compare the #' visual effects of different arguments to "plot.multcompTs". Each component #' of 'plotList' is itself a list of arguments to pass to either "boxplot", #' "plot.multcompTs" or "plot.multcompLetters". Placement can be controlled #' via 'fig' arguments passed (indirectly) of the form 'c(x1, x2, y1, y2)'. #' If(horizontal==TRUE), fig gives the coordinates of the figure region in the #' display region of the plot device, as described on the \code{\link{par}} #' help page; if(horizontal==FALSE), fig[c(3,4,1,2)] gives c(x1, x2, y1, y2) #' for placement of that portion of the plot. #' @return This function invisibly returns a list with one component for each #' component of plotList containing the output of the appropriate #' "plot.multcomp" call plus the output of "compFn". #' @author Spencer Graves #' @seealso \code{\link{boxplot}} \code{\link{multcompTs}} #' \code{\link{multcompLetters}} \code{\link{plot.multcomp}} #' \code{\link{TukeyHSD}} \code{\link{par}} \code{\link[grid]{gpar}} #' @keywords aplot #' @importFrom stats TukeyHSD aov model.frame terms #' @importFrom graphics plot #' @examples #' #' # Example from help("TukeyHSD") #' multcompBoxplot(breaks~tension, data=warpbreaks) #' # 'sortFn' can be either a function or a function name #' # default order is 'decreasing=TRUE' #' multcompBoxplot(breaks~tension, data=warpbreaks, #' sortFn=median, decreasing=FALSE) #' #' ################## #' library(multcomp) #' data(recovery) #' # Horizontal boxplots with both #' # multcomp Ts and Letters on the right #' # Using recovery{multcomp} data set #' multcompBoxplot(minutes~blanket, recovery) #' #' # Plotting boxes rather than letters and Ts #' #' multcompBoxplot(minutes~blanket, recovery, #' plotList=list( #' boxplot=list(fig=c(0, 0.75, 0, 1), las=1, #' cex.axis=1.5), #' multcompTs=list(fig=c(0.7, 0.85, 0, 1), #' type='boxes'), #' multcompLetters=list( #' fig=c(0.87, 0.97, 0.03, 0.98), #' type='boxes') ) ) #' #' #################### #' #' # Vertical boxplots with both #' # multcomp Ts and Letters on the top #' multcompBoxplot(minutes~blanket, recovery, #' horizontal=FALSE) #' #' # Horizontal boxplots with 2 different #' # displays of the "Ts" on the left #' multcompBoxplot(minutes~blanket, recovery, #' plotList=list( #' boxplot=list(fig=c(0.3, 1, 0, 1)), #' multcompTs=list(fig=c(0, 0.15, 0, 1), #' orientation="reverse"), #' multcompTs=list(fig=c(0.15, 0.3, 0, 1), #' type="boxes", orientation="reverse", #' mar=c(5,2, 4, 0)+.1) ) ) #' #' library(MASS) #' anorx <- #' multcompBoxplot(Postwt~Treat, data=anorexia) #' #' \dontrun{ #' # Confirm than sortFn=NULL or NA #' # leaves the order unchanged #' library(multcomp) #' data(cholesterol) #' cholesterol$trt3 <- with(cholesterol, factor( #' as.character(trt), levels=levels(trt)[c(5:4,1:3)])) #' multcompBoxplot(response ~ trt3, cholesterol, #' sortFn=NULL) #' multcompBoxplot(response ~ trt3, cholesterol, #' sortFn=NA) #' } #' #' @export "multcompBoxplot" <- function(formula, data, horizontal=TRUE, compFn="TukeyHSD", sortFn="mean", decreasing=TRUE, plotList=list( boxplot=list(fig=c(0, 0.75, 0, 1)), multcompTs=list(fig=c(0.7, 0.85, 0, 1)), multcompLetters=list(fig=c(0.87, 0.97, 0.03, 0.98), fontsize=20, fontface="bold"))){ ## ## 1. if(!horizontal)swap plotList$...$fig... ## n.mc <- length(plotList) if(!horizontal) for(i in 1:n.mc) if("fig" %in% names(plotList[[i]])) plotList[[i]]$fig <- plotList[[i]]$fig[c(3,4,1,2)] ## ## 2. Sort the levels of 'z' in the formula ## if(!is.null(sortFn) && (is.function(sortFn) || ((!is.na(sortFn)) && is.character(sortFn)))){ fm <- as.character(formula) data <- data[, fm[-1]] y.z <- tapply(data[, fm[2]], data[, fm[3]], function(x)do.call(sortFn, list(x=x))) oz <- order(y.z, decreasing=decreasing) data[, fm[3]] <- factor(data[, fm[3]], levels=names(y.z)[oz]) } ## ## 3. Create the desired boxplots ## bpArgs <- plotList$boxplot if("fig" %in% names(bpArgs)){ op <- par(fig=bpArgs$fig) on.exit(par(op)) bpArgs$fig <- NULL } # bpArgNames <- names(bpArgs) nArgs.bp <- length(bpArgNames) bpArg <- vector(3+nArgs.bp, mode="list") names(bpArg) <- c("formula", "data", "horizontal", bpArgNames) bpArg[[1]] <- formula bpArg[[2]] <- data bpArg[[3]] <- horizontal if(nArgs.bp>0)for(i in 1:nArgs.bp) bpArg[[3+i]] <- bpArgs[[i]] bp <- do.call("boxplot", bpArg) # Create list "out" and save this. out <- vector(n.mc+1, mode="list") plotNames <- names(plotList) names(out) <- c(plotNames[1], "compFn", plotNames[-1]) out[[1]] <- bp par(op) ## ## 4. Call "compFn" for the other portions of the ## display. ## Fn <- compFn if(compFn=="TukeyHSD"){ TukeyHSD. <- function(formula, data){ TukeyHSD(aov(formula, data))[[1]][, "p adj"] } Fn <- "TukeyHSD." } if (compFn == "kruskalmc"){ kruskalmc. <- function(formula, data){ extract_p(pgirmess::kruskalmc(resp = formula, data = data)) } Fn <- "kruskalmc." } fnValue <- do.call(Fn, list(formula=formula, data=data)) Fn.v0 <- vec2mat(fnValue) Lvls <- bp$names if(horizontal)Lvls <- rev(Lvls) FnValue <- Fn.v0[Lvls, Lvls] out[["compFn"]] <- fnValue ## ## 5. Process the remaining components of plotList ## if(n.mc>1){ mar2 <- (horizontal*c(5, 0, 4, 0)+ (!horizontal)*c(0, 4, 0, 2)+0.1) mcNames <- plotNames[-1] # plotNms <- paste("plot", mcNames, sep=".") if("multcompTs" %in% mcNames) mcTs <- multcompTs(FnValue) if("multcompLetters" %in% mcNames) mcLtrs <- multcompLetters(FnValue) # Create the desired multcompViews for(i in 1:(n.mc-1)){ pL.i <- plotList[[i+1]] { if("mar" %in% names(pL.i)){ mar <- pL.i$mar pL.i$mar <- NULL } else mar <- mar2 } op.i <- par(mar=mar) on.exit(par(op.i)) names.i <- names(pL.i) nm.i <- length(names.i) args.i <- vector(3+nm.i, mode="list") names(args.i) <- c("x", "horizontal", "add", names.i) args.i[[1]] <- { if(mcNames[i]=="multcompTs") mcTs else mcLtrs } args.i[[2]] <- !horizontal args.i[[3]] <- TRUE if(nm.i>0)for(ji in 1:nm.i) args.i[[3+ji]] <- pL.i[[ji]] out[[2+i]] <- do.call(plot, args.i) par(op.i) } } invisible(out) } multcompView/R/plot.multcompLetters.R0000644000176200001440000002067214414525367017473 0ustar liggesusers#' plot multcomp graphics #' #' Plot graphic(s) for multcompTs or multcompLetters objects #' #' The requested graphic is either plotted by itself or added to an existing #' plot as specified by the arguments. The placement can be controlled by #' 'fig' and 'at'. #' #' The fontsize and fontface of a plot of a multcompLetters object with 'type = #' "Letters"' can be adjusted as describe on the \code{\link[grid]{gpar}} help #' page. #' #' @aliases plot.multcomp #' @param x an object of class 'multcompTs' or 'multcompLetters'. #' @param horizontal A logical scalar indicating whether the list of items #' compared reads left to right (horizontal = TRUE) or top to bottom #' (horizontal = FALSE). If this multcomp graphic accompanies boxplots for #' different levels or groups compared, the 'boxplot' argument 'horizontal' is #' the negation of the multcomp plot 'horizontal' argument. #' @param col The color for each group of items or factor levels. The colors #' will cross the different items or factor levels and will therefore have the #' orientation specified via 'horizontal'. If the number of columns exceeds #' length(col), col is recycled. For alternative choices for col, see "Color #' Specification" in the \code{\link{par}} help page. #' @param type An alternative display for either multcompTs or multcompLetters #' is 'boxes' (or rectangles). If type="boxes" with "multcompTs", the #' "base(s)" of each "T" will be indicated by a triangle. #' @param add TRUE to add to an existing plot; FALSE to start a new plot. The #' names of the factor levels or items compared will be plotted only if #' add=FALSE. #' @param at A numeric vector or matrix or a list with components "at" and #' "width". If a list, both components must be either a numeric vector or #' matrix. The numeric vector "at" (whether the function argument or "at" #' component of the "at" list) must be either a numeric vector or matrix giving #' the locations where the "Ts" or "Letters" graphics should be drawn. #' length(at) is 1, 2 or 3 times the number of the number of factor levels or #' items compared. If length(at) is twice the number of levels or items #' compared, it gives the range of the display for that level; the base of a #' "T" will be at the midpoint. If length(at) is three times the number of #' items compared, the intermediate number will be the center of the base of #' the "T". #' @param width A numeric vector or matrix with as many rows as "Ts" or #' "groups" and with up to three columns. With one column, it will be the #' "center" of the plot range for that group. With two columns, they will #' delimit the range. With three, they will provide "bottom", "center", and #' "top" of the range for that set of grouping indicators. If "at" is a list, #' the argument "width" is ignored and is taken from the list "at". #' @param fig A numerical vector of the form 'c(x1, x2, y1, y2)' giving the #' coordinates of the figure region in the display region of the plot device, #' as described on the \code{\link{par}} help page. #' @param label.levels NA for no labels or distance away from the plot for the #' labels as a proportion of the plot range. #' @param label.groups NA for no labels or distance away from the plot for the #' labels as a proportion of the plot range. #' @param ... graphical parameters can be given as described on the #' \code{\link{plot}} help page or for plot.multcompLetters as describe on the #' \code{\link[grid]{gpar}} help page. #' @return A list with two components: \item{at }{ A matrix with three columns #' giving the middle and extremes of the display for each of the factor levels #' or items compared. } \item{width }{ A matrix with as many rows as "Ts" or #' comparitor levels and with two columns giving the plot range for that #' comparitor level. } #' @author Spencer Graves #' @seealso \code{\link{multcompTs}} \code{\link{multcompLetters}} #' \code{\link{multcompBoxplot}} \code{\link[grid]{gpar}} #' @keywords aplot #' @examples #' #' ## #' ## plot(multcompTs(...)) #' ## #' dif4 <- c(.1, .02, .03, 1) #' names(dif4) <- c("A-B", "A-C", "B-C", "A-D") #' (mcT4 <- multcompTs(dif4)) #' # Standard plot, base of "Ts" point left #' mcT4.1 <- plot(mcT4, label.groups=0.05) #' # Redo using "at" = list #' plot(mcT4, label.groups=0.05, at=mcT4.1) #' # Same plot with group labels closer to the figure #' plot(mcT4, label.groups=0.02) #' #' # Base of "Ts" point right #' plot(mcT4, label.groups=TRUE, orientation="r") #' # Base of "Ts" point down #' plot(mcT4, horizontal=TRUE, label.groups=0.05) #' # Base of "Ts" point up #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' orientation="r") #' #' # Same 4 plots but with boxes & triangles, not Ts #' plot(mcT4, label.groups=0.05, type="b") #' plot(mcT4, label.groups=0.05, orientation="r", #' type="b") #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' type="b") #' plot(mcT4, horizontal=TRUE, label.groups=0.05, #' orientation="r", type="b") #' #' ## #' ## plot(multcompLetters(...)) #' ## #' # ... using dif4 from above #' (mcL4 <- multcompLetters(dif4, Letters=LETTERS)) #' # Standard plot #' \dontrun{ #' # Requires (grid) #' mcL4.1 <- plot(mcL4, label.groups=0.05) #' # Redo using "at" = list #' plot(mcL4, label.groups=0.05, at=mcL4.1) #' #' # With bold face and larger font #' plot(mcL4, label.groups=0.05, #' fontsize=28, fontface="bold") #' #' # Horizontal rather than vertical #' plot(mcL4, horizontal=TRUE, label.groups=0.05) #' } #' #' # Same as boxes rather than letters #' plot(mcL4, label.groups=0.05, type="b") #' plot(mcL4, horizontal=TRUE, label.groups=0.05, #' type="b") #' #' @export "plot.multcompLetters" <- function(x, horizontal=FALSE, col=1:6, type=c("Letters", "boxes"), add=FALSE, at, width, fig=c(0, 1, 0, 1), label.levels=if(add)NA else 0.05, label.groups=NA, ...){ ## ## 1. Get row and column names ## obj <- deparse(substitute(x)) objMat <- x$LetterMatrix lvls <- dimnames(objMat)[[1]] gps <- dimnames(objMat)[[2]] n <- length(lvls) k <- length(gps) if((n==0) | (k==0)) stop("dimnames required for ", obj) col <- rep(col, len=k) ## ## 2. Get plotting positions for lvls and gps ## At <- function(x, lvls, d){ N <- length(lvls) if(length(x)<=N) x <- t(outer(c(-0.4, 0, 0.4), x, "+")) else{ x <- apply(x, 2, sort) if(length(x)<(3*N)) x <- cbind(x[, 1], mean(x, 2, mean), x[, 2]) } dimnames(x) <- list(lvls, c("bottom", "center", "top")) x } # at.list <- FALSE missW <- missing(width) { if(missing(at)){ at <-{ if(horizontal) 1:n else n:1 } } else if(is.list(at)){ at.list <- TRUE if(is.null(names(at))) names(at) <- c("at", "width") width <- at$width at <- at$at } } # if(!at.list){ if(missW){ width <- { if(horizontal) k:1 else 1:k } } width <- At(width, gps) at <- At(at, lvls) } ## ## 3. Adjust par as required ## op. <- par() parList <- list(fig=fig, xpd=NA, new=add) if(add)parList$mar <- (c(5, 0, 4, 0)+0.1) # dots <- list(...) dNames <- names(dots) nDots <- length(dNames) if(nDots>0)for(i in 1:nDots) if(dNames[i] %in% names(op.)){ parList[[dNames[i]]] <- dots[[dNames[i]]] dots[[dNames[i]]] <- NULL } op <- do.call("par", parList) on.exit(par(op)) ## ## 4. organize plot args ## plotL <- (match.arg(type)=="Letters") pArgs <- names(dots) k.pArgs <- length(pArgs) stdArgs <- c("obj", "at", "width", "horizontal", "col", "add", "label.levels") ks <- length(stdArgs) argNames <- { if(plotL) c(stdArgs, pArgs) else c(stdArgs, "label.groups", pArgs) } plotArgs <- vector(length(argNames), mode="list") names(plotArgs) <- argNames plotArgs$obj <- { if(plotL) objMat else (objMat-1) } plotArgs$at <- at plotArgs$width <- width plotArgs$horizontal <- horizontal plotArgs$col <- col plotArgs$add <- add plotArgs$label.levels <- label.levels # if(!plotL) plotArgs$label.groups <- label.groups if(k.pArgs>0)for(i. in 1:k.pArgs) plotArgs[[pArgs[i.]]] <- dots[[i.]] ## ## 5. Plot ## do.call(c("plotBoxes", "plotLetters")[1+plotL], plotArgs) ## ## 6. Done ## list(at=at, width=width) } multcompView/MD50000644000176200001440000000322114414551362013260 0ustar liggesusers28046d69907eef7544e14b295140e39a *DESCRIPTION 8d38fc031a5468254212cf1db132ef17 *NAMESPACE 30d3faa66a8964b33cc29c911799782f *R/extract_p.R 7839b75a96f51f8e5fc0ab68a9469a2f *R/multcompBoxplot.R eb2dbbcd2c3434d24dd97d97451b2116 *R/multcompLetters.R f3ffb29139de0ed5b35da51b0e687c63 *R/multcompLetters2.R bf30220ebd681e3deb713bb4009e22ed *R/multcompLetters3.R dd820f0694cf2639612bc3497763cc7c *R/multcompLetters4.R 9fab5b5f01ce62015c5f26a83dd2495a *R/multcompTs.R 9f07fb4a79a01096315506947ed5ad67 *R/multcompView-package.R 48100771a2a07ec401182761e6ff5727 *R/plot.multcompLetters.R 281b0cc9d01a1d930814bb2af9e97766 *R/plot.multcompTs.R e95af63c10374210fc6f59221667f1b5 *R/plotBoxes.R 376e40a1c57a98ed8d3f7d2a33510db4 *R/plotLetters.R e8699f3c5c0fb7b9b93dbc724a4287dc *R/plotTs.R 7ea0b252fa539464a7cf6b40b12718ba *R/print.multcompLetters.R 086f28eec6c8ac73faaa8ae27b1fed0a *R/vec2mat.R 0ff72033af477590aabd8a7011d9d134 *R/vec2mat2.R 23161c7eb305fec411df18388de0d35c *README 47adef3f6a62d77f4fc3f2bc7ffaccfa *man/extract_p.Rd 42c4c83710125c49d475e6b085323074 *man/multcompBoxplot.Rd 0aae211ee23dabf8da53542132078ce4 *man/multcompLetters.Rd 33fb913ebf002a85b076cd5619c98ebb *man/multcompTs.Rd ffcb5477430e2351439c95d1b0d229db *man/multcompView-package.Rd 6e229f9d9a1b934e95e4e6821915d13c *man/plot.multcompLetters.Rd e565e6504d0e80877ebcb200883f1fc5 *man/plot.multcompTs.Rd d76861a7d9e07ca2e8d5b0b3a4b99b25 *man/plotBoxes.Rd 90ea6c7a46a46a1561c96e57c093e5a2 *man/plotLetters.Rd 7fc2f5c789d163386604e532eee8fb2d *man/plotTs.Rd 18565c85ccb345e977b157b0b926aae1 *man/print.multcompLetters.Rd 2799daae78a7d77f5850d52d37a9e5e6 *man/vec2mat.Rd 44b9895915c2627ad823b7d28b663c87 *man/vec2mat2.Rd