Title: | Statistical Analysis and Data Display: Heiberger and Holland |
---|---|
Description: | Support software for Statistical Analysis and Data Display (Second Edition, Springer, ISBN 978-1-4939-2121-8, 2015) and (First Edition, Springer, ISBN 0-387-40270-5, 2004) by Richard M. Heiberger and Burt Holland. This contemporary presentation of statistical methods features extensive use of graphical displays for exploring data and for displaying the analysis. The second edition includes redesigned graphics and additional chapters. The authors emphasize how to construct and interpret graphs, discuss principles of graphical design, and show how accompanying traditional tabular results are used to confirm the visual impressions derived directly from the graphs. Many of the graphical formats are novel and appear here for the first time in print. All chapters have exercises. All functions introduced in the book are in the package. R code for all examples, both graphs and tables, in the book is included in the scripts directory of the package. |
Authors: | Richard M. Heiberger |
Maintainer: | Richard M. Heiberger <[email protected]> |
License: | GPL (>= 2) |
Version: | 3.1-52 |
Built: | 2024-11-10 03:30:51 UTC |
Source: | https://github.com/cran/HH |
Support software for Statistical Analysis and Data Display (Second Edition, Springer, ISBN 978-1-4939-2121-8, 2015) and (First Edition, Springer, ISBN 0-387-40270-5, 2004) by Richard M. Heiberger and Burt Holland. This contemporary presentation of statistical methods features extensive use of graphical displays for exploring data and for displaying the analysis. The second edition includes redesigned graphics and additional chapters. The authors emphasize how to construct and interpret graphs, discuss principles of graphical design, and show how accompanying traditional tabular results are used to confirm the visual impressions derived directly from the graphs. Many of the graphical formats are novel and appear here for the first time in print. All chapters have exercises. All functions introduced in the book are in the package. R code for all examples, both graphs and tables, in the book is included in the scripts directory of the package.
The DESCRIPTION file:
Package: | HH |
Type: | Package |
Title: | Statistical Analysis and Data Display: Heiberger and Holland |
Version: | 3.1-52 |
Date: | 2024-02-10 |
Author: | Richard M. Heiberger |
Maintainer: | Richard M. Heiberger <[email protected]> |
Depends: | R (>= 3.0.2), lattice, stats, grid, latticeExtra, multcomp, gridExtra (>= 2.0.0), graphics |
Imports: | reshape2, leaps, vcd, colorspace, RColorBrewer, shiny (>= 0.13.1), Hmisc, abind, Rmpfr (>= 0.6.0), grDevices, methods |
Suggests: | mvtnorm, car, Rcmdr, RcmdrPlugin.HH, microplot |
Description: | Support software for Statistical Analysis and Data Display (Second Edition, Springer, ISBN 978-1-4939-2121-8, 2015) and (First Edition, Springer, ISBN 0-387-40270-5, 2004) by Richard M. Heiberger and Burt Holland. This contemporary presentation of statistical methods features extensive use of graphical displays for exploring data and for displaying the analysis. The second edition includes redesigned graphics and additional chapters. The authors emphasize how to construct and interpret graphs, discuss principles of graphical design, and show how accompanying traditional tabular results are used to confirm the visual impressions derived directly from the graphs. Many of the graphical formats are novel and appear here for the first time in print. All chapters have exercises. All functions introduced in the book are in the package. R code for all examples, both graphs and tables, in the book is included in the scripts directory of the package. |
License: | GPL (>= 2) |
NeedsCompilation: | no |
Packaged: | 2024-02-10 20:07:55 UTC; rmh |
Date/Publication: | 2024-02-11 00:00:02 UTC |
Config/pak/sysreqs: | libgmp3-dev make libicu-dev libjpeg-dev libpng-dev libmpfr-dev zlib1g-dev |
Repository: | https://rmheiberger.r-universe.dev |
RemoteUrl: | https://github.com/cran/HH |
RemoteRef: | HEAD |
RemoteSha: | dbcae2570dc57c07e1b7e709df23e4028ae8aca1 |
Index of help topics:
AEdotplot AE (Adverse Events) dotplot of incidence and relative risk AEdotplot.data.frame AE (Adverse Events) dotplot of incidence and relative risk, support functions CIplot Illustration of the meaning of confidence levels. Discrete4 Discrete with four levels color dataset. EmphasizeVerticalPanels Helper function for likertWeighted(). used for vertical spacing and horizontal borders of grouped panels. F.curve plot a chisquare or a F-curve. GSremove Remove selected GraphSheetPages in the S-Plus Windows GUI Graphsheet HH-package Statistical Analysis and Data Display: Heiberger and Holland HH.regsubsets Display tabular results for Best Subsets Regression. HHscriptnames Find absolute pathname of a script file for the HH book in the HH package. InsertVerticalPanels Expand a 3D array on the second dimension, inserting empty layers where the input vector has a '0' value. A 2D argument 'x' with 'dim(x)==c(r,c)' is first extended to 3D with 'dim(x)==c(1,r,c)', and then the result is collapsed back to 2D. LikertPercentCountColumns Display likert plots with percents in the first column of panels and counts in the second column of panels. NTplot Specify plots to illustrate Normal and t Hypothesis Tests or Confidence Intervals, including normal approximation to the binomial. NormalAndTPower Construct a power graph based on the NTplot. NormalAndTplot Specify plots to illustrate Normal and t Hypothesis Tests or Confidence Intervals. OddsRatio Calculate or plot the odds ratio for a 2x2 table of counts. OneWayVarPlot Displays a three-panel 'bwplot' of the data by group, of the group means, and of the entire dataset. This is an approximate visualization of the Mean Square lines from the ANOVA table for a one-way ANOVA model. ResizeEtc Display multiple independent trellis objects on the same coordinated scale. ResizeEtc.likertPlot Display multiple independent trellis objects, representing likert plots, on the same coordinated scale. ToBW.likert Change colors in a likert plot to shades of Black and White. X.residuals Residuals from the regression of each column of a data.frame against all the other columns. ae.dotplot AE (Adverse Events) dotplot of incidence and relative risk ancova Compute and plot oneway analysis of covariance ancova-class Class "ancova" Analysis of Covariance ancovaplot Analysis of Covariance Plots anova.ancovaplot ANOVA table for a c("ancovaplot","trellis") object. anovaMean ANOVA table from the group sample sizes, means, and standard deviations. aovSufficient Analysis of variance from sufficient statistics for groups. arima.diag.hh Repair design error in S-Plus arima.diag arma.loop Loop through a series of ARIMA models and display coordinated tables and diagnoastic graphs. as.likert Support functions for diverging stacked barcharts for Likert, semantic differential, and rating scale data. as.matrix.listOfNamedMatrices Convert a list of numeric matrices to a single matrix as.multicomp Support functions in R for MMC (mean-mean multiple comparisons) plots. as.rts Miscellaneous functions that I wish were in or consistent between S-Plus and R. as.vector.trellis Convert a two-dimensional trellis object into a one-dimensional trellis object. Change the order of panels in a trellis object. axis.i2wt specialized axis function for interaction2wt. bivariateNormal Plot the bivariate normal density using wireframe for specified rho. case case statistics for regression analysis ci.plot Plot confidence and prediction intervals for simple linear regression col.hh Initializing Trellis Displays col3x2 col3x2 color dataset combineLimits.trellisvector Combine limits on a one-dimensional trellis object. cp.calc Rearranges and improves the legibility of the output from the stepwise function in S-Plus. cplx Generate a sequence spanning the xlim of a lattice window. datasets Datasets for Statistical Analysis and Data Display, Heiberger and Holland dchisq.intermediate Intermediate f and chisq functions to simplify writing for both R and S-Plus. diag.maybe.null Returns a value for the diagonal of NA and NULL arguments. diagQQ QQ plot of regression residuals. diagplot5new Transpose of ECDF for centered fitted values and residuals from a linear model. do.formula.trellis.xysplom Interprets model formulas for xysplom and extended bwplots emptyMainLeftAxisLeftStripBottomLegend Remove main title, left axis tick labels, left strip, bottom legend from plot and keep the vertical spacing allocated to those items. export.eps Exports a graph to an EPS file. glhtWithMCP.993 Retain averaging behavior that was previously available in glht. gof.calculation Calculate Box-Ljung Goodness of Fit for ARIMA models in S-Plus. grid.yaxis.hh make x- and y-axis labels hhpdf R tools for writing HH2: hhpdf, hhdev.off, hhcapture, hhcode, hhpng, hhlatex hov Homogeneity of Variance hovBF Homogeneity of Variance: Brown-Forsyth method hovPlot Homogeneity of Variance Plot if.R Conditional Execution for R or S-Plus interaction.positioned interaction method for positioned factors. interaction2wt Plot all main effects and twoway interactions in a multifactor design interval Prediction and Confidence Intervals for glm Objects intxplot Interaction plot, with an option to print standard error bars. ladder Draw a "ladder of powers" plot, plotting each of several powers of y against the same powers of x. latex.array Generate the latex code for an '"array"' or '"table"' with 3, 4, or more dimensions. latticeresids Subroutine used by residual.plots.lattice legendGrob2wt place separate keys to the left of each row of a trellis likert Diverging stacked barcharts for Likert, semantic differential, rating scale data, and population pyramids. likertColor Selection of colors for Likert plots. likertMosaic Diverging stacked barcharts for Likert, semantic differential, rating scale data, and population pyramids based on mosaic as the plotting style. likertWeighted Special case wrapper for likert() when multiple columns are to have the same bar thicknesses. Uses formula with one or two conditioning variables. lm.regsubsets Evaluate lm model with highest adjusted $R^2$. lmatPairwise lmatPairwise lmatRows Find the row numbers in the lmat corresponding to the focus factor. lmplot Four types of residual plots for linear models. logit Logistic and odds functions and their inverses. matrix.trellis Convert a one-dimensional trellis object to a two-dimensional trellis object. This permits combineLimits and useOuterStrips to work. mcalinfct MCA multiple comparisons analysis (pairwise) mmc MMC (Mean-mean Multiple Comparisons) plots. mmc.mean MMC (Mean-mean Multiple Comparisons) plots from the sufficient statistics for a one-way design. mmcAspect Control aspect ratio in MMC plots to maintain isomeans grid as a square. mmcPruneIsomeans MMC plots in lattice-suppress isomeans grid lines for specified levels of the factor. mmcisomeans Functions used by mmcplot. mmcplot MMC (Mean-mean Multiple Comparisons) plots in lattice. multicomp.order Update a multicomp object by ordering its contrasts. multicomp.reverse Force all comparisons in a "multicomp" object to have the same sign. norm.curve plot a normal or a t-curve with both x and z axes. normalApproxBinomial Plots to illustrate Normal Approximation to the Binomial-hypothesis tests or confidence intervals. npar.arma Count the number of parameters in an ARIMA model specification. objip loop through all attached directories looking for pattern, possibly restricting to specified class or mode. orthog.complete Construct an orthogonal matrix which is an arbitrary completion of the column space of the input set of columns. panel.acf Panel functions for tsdiagplot. panel.axis.right Right-justify right-axis tick labels. panel.bwplot.intermediate.hh Panel functions for bwplot. panel.bwplot.superpose Panel function for bwplot that displays an entire box in the colors coded by groups. panel.bwplott Extension to S-Plus trellis to allow transposed plots. panel.cartesian trellis panel function, with labeled rows and columns and without strip labels. panel.ci.plot Default Panel Function for ci.plot panel.confintMMC Confidence interval panel for MMC tiebreaker plots, or confidence interval plot. panel.dotplot.tb Dotplot with evenly spaced tiebreakers. panel.interaction2wt Plot all main effects and twoway interactions in a multifactor design panel.isomeans isomeans grid for MMC plots. panel.likert Panel functions for likert that include a stackWidth argument panel.pairs.hh Function based on S-Plus panel.pairs to add the subpanel.scales and panel.cex arguments. panel.xysplom panel method for xysplom. partial.corr partial correlations pdf.latex Construct a pdf file from a "latex" file. See Hmisc::latex for concepts. pdiscunif Discrete Uniform Distribution perspPlane Helper functions for regr2.plot plot.mmc.multicomp MMC (Mean-mean Multiple Comparisons) plot. plot.multicomp Multiple comparisons plot that gives independent user control over the appearance of the significant and not significant comparisons. position Find or assign the implied position for graphing the levels of a factor. A new class "positioned", which inherits from "ordered" and "factor", is defined. positioned-class Class "positioned", extends "ordered" to specify the position for graphing the levels of a factor. print.NormalAndTplot Print method for Normal and t plots from NTplot. print.TwoTrellisColumns5 Print two conformable trellis plots in adjacent columns with user control of widths. print.latticeresids Print a 'latticeresids' object. print.tsdiagplot Print a "tsdiagplot" object. push.vp.hh push and pop a grid viewport, turn clipping off, change scale. pyramidLikert Print a Likert plot as a Population Triangle rbind.trellis Extend matrix reshaping functions to trellis objects. regr1.plot plot x and y, with optional straight line fit and display of squared residuals regr2.plot 3D plot of z against x and y, with regression plane fit and display of squared residuals. regrresidplot Draw a plot of y vs x from a linear model object, with residuals indicated by lines or squares. resid.squares plot squared residuals in inches to match the y-dimension residVSfitted Draw plots of resid ~ y.hat and sqrt(abs(resid)) ~ y.hat residual.plots Residual plots for a linear model. residual.plots.lattice Construct four sets of regression plots: Y against X, residuals against X, partial residuals against X, partial residuals against each X adjusted for all the other X columns. rowPcts Row and columns percents seqplot Time series plot. seqplotForecast seqplot with confidence bands for the forecast region. strip.background0 Turn off the coloring in the trellis strip labels. Color 0 is the background color. strip.useOuterStrips.first Functions based on strip.default for use with the useOuterScales function. strip.xysplom strip function that is able to place the correlation or regression coefficient into the strip label. sufficient Calculates the mean, standard deviation, and number of observations in each group of a data.frame that has one continuous variable and two factors. summary.arma.loop summary and print and subscript methods for tsdiagplot and related objects. toCQxR Reshape a 3-way array to a 2-way data.frame that can can be used with a trellis conditioning formula to get the three-way behavior. Used with likertWeighted(). tsacfplots Coordinated time series and ACF and PCF plots. tsdiagplot Times series diagnostic plots for a structured set of ARIMA models. useOuterScales Put scales for axes only on the bottom and left panels of a lattice display, and give fine control over the placement of strips useOuterStripsT2L1 Three-factor generalization of latticeExtra::useOuterStrips vif Calculate the Variance Inflation Factor xysplom scatterplot matrix with potentially different sets of variables on the rows and columns. z.test Z test for known population standard deviation
data display, scatterplot matrix, (MMC Mean–mean Multiple Comparison) plots, interaction plots, ANCOVA plots, regression diagnostics, time series, ARIMA models, boxplots
Richard M. Heiberger
Maintainer: Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2004). Statistical Analysis and Data Display: An Intermediate Course with Examples in S-Plus, R, and SAS, First Edition. Springer Texts in Statistics. Springer. https://link.springer.com/book/10.1007/978-1-4757-4284-8.
ancovaplot
,
ci.plot
,
interaction2wt
,
ladder
,
case.lm
,
NTplot
for Normal and plots,
hov
,
resid.squares
,
MMC
,
AEdotplot
,
likert
,
tsacfplots
,
tsdiagplot
demo(package="HH")
## In addition to the examples for each function, ## there are seven interactive shiny apps in the HH package: ## Not run: if (interactive()) NTplot(mean0=0, mean1=1, shiny=TRUE) if (interactive()) shiny::runApp(system.file("shiny/bivariateNormal", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/bivariateNormalScatterplot", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/PopulationPyramid", package="HH")) if (interactive()) shiny.CIplot(height = "auto") if (interactive()) shiny::runApp(system.file("shiny/AEdotplot", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/likert", package="HH")) ## End(Not run)
## In addition to the examples for each function, ## there are seven interactive shiny apps in the HH package: ## Not run: if (interactive()) NTplot(mean0=0, mean1=1, shiny=TRUE) if (interactive()) shiny::runApp(system.file("shiny/bivariateNormal", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/bivariateNormalScatterplot", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/PopulationPyramid", package="HH")) if (interactive()) shiny.CIplot(height = "auto") if (interactive()) shiny::runApp(system.file("shiny/AEdotplot", package="HH")) if (interactive()) shiny::runApp(system.file("shiny/likert", package="HH")) ## End(Not run)
A two-panel display of the most
frequently occurring AEs in the active arm of a clinical
study. The first panel displays their incidence by
treatment group, with different symbols for each
group. The second panel displays the relative risk
of an event on the active arm relative to the
placebo arm, with 95% confidence intervals for a table.
By default, the AEs are ordered by
relative risk so that events with the largest
increases in risk for the active treatment are
prominent at the top of the display. See the Details section for
information
on changing the sort order.
ae.dotplot(ae, ...) ae.dotplot.long(xr, A.name = levels(xr$RAND)[1], B.name = levels(xr$RAND)[2], col.AB = c("red","blue"), pch.AB = c(16, 17), main.title = paste("Most Frequent On-Therapy Adverse Events", "Sorted by Relative Risk"), main.cex = 1, cex.AB.points = NULL, cex.AB.y.scale = 0.6, position.left = c(0, 0, 0.7, 1), position.right = c(0.61, 0, 0.98, 1), key.y = -0.2, CI.percent=95) logrelrisk(ae, A.name, B.name, crit.value=1.96) panel.ae.leftplot(x, y, groups, col.AB, ...) panel.ae.rightplot(x, y, ..., lwd=6, lower, upper, cex=.7) panel.ae.dotplot(x, y, groups, ..., col.AB, pch.AB, lower, upper) ## R only aeReshapeToLong(aewide)
ae.dotplot(ae, ...) ae.dotplot.long(xr, A.name = levels(xr$RAND)[1], B.name = levels(xr$RAND)[2], col.AB = c("red","blue"), pch.AB = c(16, 17), main.title = paste("Most Frequent On-Therapy Adverse Events", "Sorted by Relative Risk"), main.cex = 1, cex.AB.points = NULL, cex.AB.y.scale = 0.6, position.left = c(0, 0, 0.7, 1), position.right = c(0.61, 0, 0.98, 1), key.y = -0.2, CI.percent=95) logrelrisk(ae, A.name, B.name, crit.value=1.96) panel.ae.leftplot(x, y, groups, col.AB, ...) panel.ae.rightplot(x, y, ..., lwd=6, lower, upper, cex=.7) panel.ae.dotplot(x, y, groups, ..., col.AB, pch.AB, lower, upper) ## R only aeReshapeToLong(aewide)
ae |
For |
... |
For For the other functions, just standard panel function arguments. |
xr |
|
aewide |
|
A.name , B.name
|
Names of treatment groups (in |
col.AB , pch.AB , cex.AB.points
|
color, plotting character and character expansion for the individual points on the left plot. |
cex.AB.y.scale |
Character expansion for the left tick labels (the symptom names). |
main.title , main.cex
|
Main title and character expansion for the
combined plot in |
cex |
The character expansion for the points in the left and right plots. |
position.left , position.right
|
|
key.y |
Position of the key (legend) in the combined plot. This
is the |
crit.value |
Critical value used to compute confidence intervals
on the log relative risk. Defaults to 1.96. User is responsible
for specifying both |
CI.percent |
Confidence percent associated with the
|
x , y , groups , lwd
|
standard panel function arguments. |
lower , upper
|
|
The second panel shows relative risk of an event on the active arm
(treatment B)
relative to the placebo arm (treatment A), with 95% confidence
intervals for a table. Confidence intervals on the log
relative risk are calculated using the asymptotic standard error
formula given as Equation 3.18 in Agresti A., Categorical Data
Analysis. Wiley: New York, 1990.
By default the ae.dotplot
function sorts the events by relative risk.
To change the sort order, you must redefine the ordering of the
ordered factor PREF
. See the examples below.
logrelrisk
takes an input data.frame of the form x
described in the argument list and returns a data.frame consisting of
the input argument with additional columns as described in the
argument xr
. The result column of symptom names PREF
is
an ordered factor, with the order specified by the relative risk.
ae.leftplot
returns a "trellis"
object containing a
horizontal dotplot of the percents against each of the symptom names.
ae.rightplot
returns a "trellis"
object containing a
horizontal plot on the log scale of the relative risk confidence
intervals against each of the symptom names.
ae.dotplot
calls both ae.leftplot
and ae.rightplot
and combines their plots into a single display with a single set of
left axis labels, a main title, and a key. The value returned
invisibly is a list of the full left trellis object and the right
trellis object with its left labels blanked out. Printing the value
will not usually be interesting as the main title and key are not
included.
It is better to call ae.dotplot
directly, perhaps with a change
in some of the positioning arguments.
Richard M. Heiberger <[email protected]>
Ohad Amit, Richard M. Heiberger, and Peter W. Lane. (2008) “Graphical Approaches to the Analysis of Safety Data from Clinical Trials”. Pharmaceutical Statistics, 7, 1, 20–35. https://onlinelibrary.wiley.com/doi/10.1002/pst.254
AEdotplot
for a three-panel version that also has
an associated shiny app.
## variable names in the input data.frame aeanonym ## RAND treatment as randomized ## PREF adverse event symptom name ## SN number of patients in treatment group ## SAE number of patients in each group for whom the event PREF was observed ## ## Input sort order is PREF/RAND data(aeanonym) head(aeanonym) ## Calculate log relative risk and confidence intervals (95% by default). ## logrelrisk sets the sort order for PREF to match the relative risk. aeanonymr <- logrelrisk(aeanonym) ## sorts by relative risk head(aeanonymr) ## construct and print plot on current graphics device ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)") ## export.eps(h2("stdt/figure/aerelrisk.eps")) ## This looks great on screen and exports badly to eps. ## We recommend drawing this plot directly to the postscript device: ## ## trellis.device(postscript, color=TRUE, horizontal=TRUE, ## colors=ps.colors.rgb[ ## c("black", "blue", "red", "green", ## "yellow", "cyan","magenta","brown"),], ## onefile=FALSE, print.it=FALSE, ## file=h2("stdt/figure/aerelrisk.ps")) ## ae.dotplot(aeanonymr, ## A.name="TREATMENT A (N=216)", ## B.name="TREATMENT B (N=431)") ## dev.off() ## To change the sort order, redefine the PREF factor. ## For this example, to plot alphabetically, use the statement aeanonymr$PREF <- ordered(aeanonymr$PREF, levels=sort(levels(aeanonymr$PREF))) ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)", main.title="change the main title to reflect the new sort order") ## Not run: ## to restore the order back to the default, use relrisk <- aeanonymr[seq(1, nrow(aeanonymr), 2), "relrisk"] PREF <- unique(aeanonymr$PREF) aeanonymr$PREF <- ordered(aeanonymr$PREF, levels=PREF[order(relrisk)]) ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)", main.title="back to the original sort order") ## smaller artifical example with the wide format aewide <- data.frame(Event=letters[1:6], N.A=c(50,50,50,50,50,50), N.B=c(90,90,90,90,90,90), AE.A=2*(1:6), AE.B=1:6) aewtol <- aeReshapeToLong(aewide) xr <- logrelrisk(aewtol) ae.dotplot(xr) ## End(Not run)
## variable names in the input data.frame aeanonym ## RAND treatment as randomized ## PREF adverse event symptom name ## SN number of patients in treatment group ## SAE number of patients in each group for whom the event PREF was observed ## ## Input sort order is PREF/RAND data(aeanonym) head(aeanonym) ## Calculate log relative risk and confidence intervals (95% by default). ## logrelrisk sets the sort order for PREF to match the relative risk. aeanonymr <- logrelrisk(aeanonym) ## sorts by relative risk head(aeanonymr) ## construct and print plot on current graphics device ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)") ## export.eps(h2("stdt/figure/aerelrisk.eps")) ## This looks great on screen and exports badly to eps. ## We recommend drawing this plot directly to the postscript device: ## ## trellis.device(postscript, color=TRUE, horizontal=TRUE, ## colors=ps.colors.rgb[ ## c("black", "blue", "red", "green", ## "yellow", "cyan","magenta","brown"),], ## onefile=FALSE, print.it=FALSE, ## file=h2("stdt/figure/aerelrisk.ps")) ## ae.dotplot(aeanonymr, ## A.name="TREATMENT A (N=216)", ## B.name="TREATMENT B (N=431)") ## dev.off() ## To change the sort order, redefine the PREF factor. ## For this example, to plot alphabetically, use the statement aeanonymr$PREF <- ordered(aeanonymr$PREF, levels=sort(levels(aeanonymr$PREF))) ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)", main.title="change the main title to reflect the new sort order") ## Not run: ## to restore the order back to the default, use relrisk <- aeanonymr[seq(1, nrow(aeanonymr), 2), "relrisk"] PREF <- unique(aeanonymr$PREF) aeanonymr$PREF <- ordered(aeanonymr$PREF, levels=PREF[order(relrisk)]) ae.dotplot(aeanonymr, A.name="TREATMENT A (N=216)", B.name="TREATMENT B (N=431)", main.title="back to the original sort order") ## smaller artifical example with the wide format aewide <- data.frame(Event=letters[1:6], N.A=c(50,50,50,50,50,50), N.B=c(90,90,90,90,90,90), AE.A=2*(1:6), AE.B=1:6) aewtol <- aeReshapeToLong(aewide) xr <- logrelrisk(aewtol) ae.dotplot(xr) ## End(Not run)
A three-panel display of the most
frequently occurring AEs in the active arm of a clinical
study. The first panel displays their incidence by
treatment group, with different symbols for each
group. The second panel displays the relative risk
of an event on the active arm relative to the
placebo arm, with 95% confidence intervals for a table.
By default, the AEs are ordered by
relative risk so that events with the largest
increases in risk for the active treatment are
prominent at the top of the display.
By setting the argument
sortbyRelativeRisk=FALSE
, the AEs retain
the order specified by the levels of the factor.
The third panel displays the numerical values of number of patients for
each treatment,
number of adverse events for each treatment, and relative risk.
The third panel can be suppressed by the print
method.
AEdotplot(xr, ...) ## S3 method for class 'formula' AEdotplot(xr, groups=NULL, data=NULL, sortbyRelativeRisk=TRUE, ..., sub=list(deparse(this.call[1:4], width.cutoff=500), cex=.7))
AEdotplot(xr, ...) ## S3 method for class 'formula' AEdotplot(xr, groups=NULL, data=NULL, sortbyRelativeRisk=TRUE, ..., sub=list(deparse(this.call[1:4], width.cutoff=500), cex=.7))
xr |
For the formula method, a formula of the form
|
groups |
Variable containing the treatment levels. |
data |
|
sortbyRelativeRisk |
logical. If |
sub |
Subtitle for the plot. The default value is the command that generates the plot. |
... |
Any of the arguments (such as the sorting options) listed in the
calling sequence for the methods documented in
|
The first panel is an ordinary dotplot of the percent of AE observed for each treatment by AE.
The second panel shows relative risk of an event on the Treatment B arm
(usually the active compound)
relative to the Treatment A arm (usually the placebo), with 95% confidence
intervals for a table. Confidence intervals on the log
relative risk are calculated using the asymptotic standard error
formula given as Equation 3.18 in Agresti A., Categorical Data
Analysis. Wiley: New York, 1990.
By default the AEdotplot
function sorts the events by relative risk.
To retain the sort order implied by the levels
of the AE
factor, specify the argument sortbyRelativeRisk=FALSE
.
To control the sort order, make the AE factor in the input dataset
an ordered
factor
and specify the levels in the order you want.
The third panel shows the numerical values of the number and percent
of observed events on each arm and the relative risk.
The display of third panel can be suppressed by specifying the
panel.widths
argument. See the discussion of the
panel.widths
in AEdotplot.data.frame
.
The primary interest is in the display of the plot.
The function returns
an AEdotplot
object which is a list of three trellis
objects,
one for the the Percent plot, one for the Relative Risk plot, and one
for
the Text plot containing the table of input values. The object has
attributes
main
and sub
hold the main and subtitles. Each must
be a list containing the text in the first component.
ae.key
is a key as described in
xyplot
.
n.events
is a vector containing the number of events in
each subpanel.
panel.widths
is a vector of relative widths of the three components
of
the graph. The numbers must sum to one. Zero values are permitted.
The first width includes the left axis and the Percent plot. The second
is the Relative Risk plot, and the third is the plot of the table
values.
AEtable
is a table containing the data plotted on its row.
Ann Liu-Ferrara was a beta tester for the shiny app.
Richard M. Heiberger <[email protected]>
Ohad Amit, Richard M. Heiberger, and Peter W. Lane. (2008) “Graphical Approaches to the Analysis of Safety Data from Clinical Trials”. Pharmaceutical Statistics, 7, 1, 20–35. https://onlinelibrary.wiley.com/doi/10.1002/pst.254
## formula method. See ?AEdotplot.data.frame for other methods. data(AEdata) head(AEdata) AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata) ## sort by Relative Risk AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata) ## conditioned on Organ System ## Not run: AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyVar="PCT") ## PCT A AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyVar="PCT", sortbyVarBegin=2) ## PCT B AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyRelativeRisk=FALSE) ## levels(AE) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata, sortbyVar="ase.logrelrisk") ## End(Not run) ## Not run: AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata[c(AEdata$OrgSys %in% c("GI","Resp")),]) ## test sortbyRelativeRisk=FALSE ABCD.12345 <- AEdata[1:12,] head(ABCD.12345) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups=TRT, data=ABCD.12345) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups=TRT, data=ABCD.12345, sort=FALSE) ## suppress third panel tmp <- AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata) print(tmp, AEtable=FALSE) ## End(Not run) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/AEdotplot", package="HH")) ## End(Not run)
## formula method. See ?AEdotplot.data.frame for other methods. data(AEdata) head(AEdata) AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata) ## sort by Relative Risk AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata) ## conditioned on Organ System ## Not run: AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyVar="PCT") ## PCT A AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyVar="PCT", sortbyVarBegin=2) ## PCT B AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata, sortbyRelativeRisk=FALSE) ## levels(AE) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata, sortbyVar="ase.logrelrisk") ## End(Not run) ## Not run: AEdotplot(AE ~ nAE/nTRT | OrgSys, groups = TRT, data = AEdata[c(AEdata$OrgSys %in% c("GI","Resp")),]) ## test sortbyRelativeRisk=FALSE ABCD.12345 <- AEdata[1:12,] head(ABCD.12345) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups=TRT, data=ABCD.12345) AEdotplot(AE ~ nAE/nTRT | OrgSys, groups=TRT, data=ABCD.12345, sort=FALSE) ## suppress third panel tmp <- AEdotplot(AE ~ nAE/nTRT, groups = TRT, data = AEdata) print(tmp, AEtable=FALSE) ## End(Not run) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/AEdotplot", package="HH")) ## End(Not run)
Support functions for the AEdotplot
.
## S3 method for class 'data.frame' AEdotplot(xr, ..., conditionVariable=NULL, conditionName=deparse(substitute(xr)), useCondition=!is.null(conditionVariable), sub=list(conditionName, cex=.7)) ## S3 method for class 'AElogrelrisk' AEdotplot(xr, A.name=paste(levels(xr$RAND)[1], " (n=", xr$SN[1], ")", sep=""), B.name=paste(levels(xr$RAND)[2], " (n=", xr$SN[2], ")", sep=""), col.AB=c("red","blue"), pch.AB=c(16,17), main=if (sortbyRelativeRisk) list("Most Frequent On-Therapy Adverse Events Sorted by Relative Risk", cex=1) else list("Most Frequent On-Therapy Adverse Events", cex=1), cex.AB.points=NULL, cex.AB.y.scale=.6, cex.x.scale=.6, panel.widths=c(.55, .22, .23), key.y=-.2, CI.percent=95, conditionName=deparse(substitute(xr)), sortbyRelativeRisk=TRUE, ..., sub=list(conditionName, cex=.7), par.strip.text=list(cex=.7)) ## S3 method for class 'AEtable' AEdotplot(xr, ..., useCondition=TRUE, sub="sub for AEsecond") ## S3 method for class 'AEdotplot' print(x, ..., main=attr(x, "main"), sub=attr(x,"sub"), ae.key=attr(x, "ae.key"), panel.widths=attr(x,"panel.widths"), AEtable=TRUE) ## S3 method for class 'AEdotplot' c(..., panel.widths=attr(aedp[[1]], "panel.widths"), par.strip.text=list(cex=.7)) AElogrelrisk(ae, A.name=levels(ae$RAND)[1], B.name=levels(ae$RAND)[2], crit.value=1.96, sortbyRelativeRisk=TRUE, ..., sortbyVar=c("PREF", ## Event name "PCT", ## Percent "SN", ## Number of Patients "SAE", ## Number of Observed Events "relrisk", ## Relative Risk (RR) "ase.logrelrisk", ## Asymptotic Standard Error(log(RR)) "relriskCI.lower", ## Confidence Interval Bounds "relriskCI.upper"), sortbyVarBegin=1) ## 1 for A treatment, 2 for B treatment AEmatchSortorder(AEstandard, AEsecond, AEsecond.AEtable=attr(AEsecond, "AEtable"), levels.order= lapply(attr(AEstandard,"AEtable"), function(AEsubtable) levels(AEsubtable$PREF)), main.second=list(paste("Most Frequent On-Therapy Adverse Events", "Sorted to Match First Table"), cex=1)) ## S3 method for class 'AEdotplot' update(object, ...)
## S3 method for class 'data.frame' AEdotplot(xr, ..., conditionVariable=NULL, conditionName=deparse(substitute(xr)), useCondition=!is.null(conditionVariable), sub=list(conditionName, cex=.7)) ## S3 method for class 'AElogrelrisk' AEdotplot(xr, A.name=paste(levels(xr$RAND)[1], " (n=", xr$SN[1], ")", sep=""), B.name=paste(levels(xr$RAND)[2], " (n=", xr$SN[2], ")", sep=""), col.AB=c("red","blue"), pch.AB=c(16,17), main=if (sortbyRelativeRisk) list("Most Frequent On-Therapy Adverse Events Sorted by Relative Risk", cex=1) else list("Most Frequent On-Therapy Adverse Events", cex=1), cex.AB.points=NULL, cex.AB.y.scale=.6, cex.x.scale=.6, panel.widths=c(.55, .22, .23), key.y=-.2, CI.percent=95, conditionName=deparse(substitute(xr)), sortbyRelativeRisk=TRUE, ..., sub=list(conditionName, cex=.7), par.strip.text=list(cex=.7)) ## S3 method for class 'AEtable' AEdotplot(xr, ..., useCondition=TRUE, sub="sub for AEsecond") ## S3 method for class 'AEdotplot' print(x, ..., main=attr(x, "main"), sub=attr(x,"sub"), ae.key=attr(x, "ae.key"), panel.widths=attr(x,"panel.widths"), AEtable=TRUE) ## S3 method for class 'AEdotplot' c(..., panel.widths=attr(aedp[[1]], "panel.widths"), par.strip.text=list(cex=.7)) AElogrelrisk(ae, A.name=levels(ae$RAND)[1], B.name=levels(ae$RAND)[2], crit.value=1.96, sortbyRelativeRisk=TRUE, ..., sortbyVar=c("PREF", ## Event name "PCT", ## Percent "SN", ## Number of Patients "SAE", ## Number of Observed Events "relrisk", ## Relative Risk (RR) "ase.logrelrisk", ## Asymptotic Standard Error(log(RR)) "relriskCI.lower", ## Confidence Interval Bounds "relriskCI.upper"), sortbyVarBegin=1) ## 1 for A treatment, 2 for B treatment AEmatchSortorder(AEstandard, AEsecond, AEsecond.AEtable=attr(AEsecond, "AEtable"), levels.order= lapply(attr(AEstandard,"AEtable"), function(AEsubtable) levels(AEsubtable$PREF)), main.second=list(paste("Most Frequent On-Therapy Adverse Events", "Sorted to Match First Table"), cex=1)) ## S3 method for class 'AEdotplot' update(object, ...)
ae |
For |
xr |
For the formula method documented in
For the other methods, If the |
sortbyRelativeRisk |
logical. If |
conditionVariable |
Vector of same length as number of rows in
|
conditionName |
Character. Name to be used in |
useCondition |
logical. If |
x |
object to be printed. |
panel.widths |
Vector of three non-negative numerics that sum to 1. These are the widths of each of the three panels in the output plot. The left panel contains the AE names as y-tick labels and the Percent plot. The middle panel contains the Relative Risk plot. The right panel contains a table of the numerical values of number of patients for each treatment, number of adverse events for each treatment, and relative risk. Setting the third value to 0 suppresses the table of numerical values from the display. |
AEtable |
logical. For the |
main , sub
|
Main title and subtitle for the combined plot
in |
main.second |
Main title for second plot whose sort order has been changed to match the first plot. |
A.name , B.name
|
Names of treatment groups (in |
col.AB , pch.AB , cex.AB.points
|
color, plotting character and character expansion for the individual points on the left plot. |
cex.AB.y.scale |
Character expansion for the left tick labels (the Adverse Effects names). |
cex.x.scale |
Character expansion for the x-axis tick labels. |
key.y |
Position of the key (legend) in the combined plot. This
is the |
.
ae.key |
is a key as described in |
AEstandard , AEsecond , AEsecond.AEtable , levels.order
|
Arguments
that force the Adverse Events in the panels of |
crit.value |
Critical value used to compute confidence intervals
on the log relative risk. Defaults to 1.96. User is responsible
for specifying both |
CI.percent |
Confidence percent associated with the
|
... |
For |
sortbyVar |
Specify which variable will be used to provide the sort order in the plot. The names are the internal names for the variables. |
sortbyVarBegin |
1 for A treatment, 2 for B treatment. |
object |
An |
par.strip.text |
Default value for strip labels. See
|
The first panel is an ordinary dotplot of the percent of AE observed for each treatment by AE.
The second panel shows relative risk of an event on the Treatment B arm
(usually the active compound)
relative to the Treatment A arm (usually the placebo), with 95% confidence
intervals for a table. Confidence intervals on the log
relative risk are calculated using the asymptotic standard error
formula given as Equation 3.18 in Agresti A., Categorical Data
Analysis. Wiley: New York, 1990.
By default the AEdotplot
function sorts the events by relative risk.
To retain the sort order implied by the levels
of the AE
factor, specify the argument sortbyRelativeRisk=FALSE
.
To control the sort order, make the AE factor in the input dataset
an ordered
factor
and specify the levels in the order you want.
The third panel shows the numerical values of the number and percent
of observed events on each arm and the relative risk.
The display of third panel can be suppressed by specifying the
panel.widths
argument.
The primary interest is in the display of the plot.
The function returns
an AEdotplot
object which is a list of three trellis
objects,
one for the the Percent plot, one for the Relative Risk plot, and one
for
the Text plot containing the table of input values. The object has
attributes
main
and sub
hold the main and subtitles. Each must
be a list containing the text in the first component.
ae.key
is a key as described in
xyplot
.
n.events
is a vector containing the number of events in
each subpanel.
panel.widths
is a vector of relative widths of the three components
of
the graph. The numbers must sum to one. Zero values are permitted.
The first width includes the left axis and the Percent plot. The second
is the Relative Risk plot, and the third is the plot of the table
values.
AEtable
is a table containing the data plotted on its row.
Richard M. Heiberger <[email protected]>
Ohad Amit, Richard M. Heiberger, and Peter W. Lane. (2008) “Graphical Approaches to the Analysis of Safety Data from Clinical Trials”. Pharmaceutical Statistics, 7, 1, 20–35. https://onlinelibrary.wiley.com/doi/10.1002/pst.254
## Not run: ## variable names in the input data.frame aeanonym ## RAND treatment as randomized ## PREF adverse event symptom name ## SN number of patients in treatment group ## SAE number of patients in each group for whom the event PREF was observed ## OrgSys Organ System ## ## Input sort order is PREF/RAND data(aeanonym) head(aeanonym) ## variable names are hard-wired in the program ## names(aeanonym) <- c("RAND", "PREF", "SAE", "SN", "OrgSys") ## Calculate log relative risk and confidence intervals (95 ## AElogrelrisk sets the sort order for PREF to match the relative risk. aeanonymr <- AElogrelrisk(aeanonym) ## PREF sorted by relative risk head(aeanonymr) class(aeanonymr$PREF) levels(aeanonymr$PREF) AEdotplot(aeanonym) AEdotplot(aeanonym, sort=FALSE) AEdotplot(aeanonym, conditionVariable=aeanonym$OrgSys) aefake <- rbind(cbind(aeanonym, group="ABC"), cbind(aeanonym, group="DEF")) aefake$SAE[67:132] <- sample(aefake$SAE[67:132]) aefake$OrgSys.group <- with(aefake, interaction(OrgSys, group)) ## fake 2 KEEP <- aefake$OrgSys %in% c("GI","Resp") AEfakeGR <- AEdotplot(aefake[KEEP,], conditionVariable=aefake$OrgSys.group[KEEP], sub=list("ABC and DEF have different sort orders for PREF", cex=.7)) AEfakeGR ## ABC and DEF have different sort orders for PREF AEfakeGR1 <- AEdotplot(aefake[KEEP & (1:132) <= 66,], conditionVariable=aefake$OrgSys.group[KEEP & (1:132) <= 66]) AEfakeGR2 <- AEdotplot(aefake[KEEP & (1:132) >= 67,], conditionVariable=aefake$OrgSys.group[KEEP & (1:132) >= 67]) AEfakeGR1 AEfakeGR2 AEfakeMatched <- AEmatchSortorder(AEfakeGR1, AEfakeGR2) update(do.call(c, AEfakeMatched), main="ABC sorted by Relative Risk; DEF matches ABC order") ## End(Not run) ## Please see ?AEdotplot for examples using the formula method ## ## Many more examples are in demo("AEdotplotManyExamples")
## Not run: ## variable names in the input data.frame aeanonym ## RAND treatment as randomized ## PREF adverse event symptom name ## SN number of patients in treatment group ## SAE number of patients in each group for whom the event PREF was observed ## OrgSys Organ System ## ## Input sort order is PREF/RAND data(aeanonym) head(aeanonym) ## variable names are hard-wired in the program ## names(aeanonym) <- c("RAND", "PREF", "SAE", "SN", "OrgSys") ## Calculate log relative risk and confidence intervals (95 ## AElogrelrisk sets the sort order for PREF to match the relative risk. aeanonymr <- AElogrelrisk(aeanonym) ## PREF sorted by relative risk head(aeanonymr) class(aeanonymr$PREF) levels(aeanonymr$PREF) AEdotplot(aeanonym) AEdotplot(aeanonym, sort=FALSE) AEdotplot(aeanonym, conditionVariable=aeanonym$OrgSys) aefake <- rbind(cbind(aeanonym, group="ABC"), cbind(aeanonym, group="DEF")) aefake$SAE[67:132] <- sample(aefake$SAE[67:132]) aefake$OrgSys.group <- with(aefake, interaction(OrgSys, group)) ## fake 2 KEEP <- aefake$OrgSys %in% c("GI","Resp") AEfakeGR <- AEdotplot(aefake[KEEP,], conditionVariable=aefake$OrgSys.group[KEEP], sub=list("ABC and DEF have different sort orders for PREF", cex=.7)) AEfakeGR ## ABC and DEF have different sort orders for PREF AEfakeGR1 <- AEdotplot(aefake[KEEP & (1:132) <= 66,], conditionVariable=aefake$OrgSys.group[KEEP & (1:132) <= 66]) AEfakeGR2 <- AEdotplot(aefake[KEEP & (1:132) >= 67,], conditionVariable=aefake$OrgSys.group[KEEP & (1:132) >= 67]) AEfakeGR1 AEfakeGR2 AEfakeMatched <- AEmatchSortorder(AEfakeGR1, AEfakeGR2) update(do.call(c, AEfakeMatched), main="ABC sorted by Relative Risk; DEF matches ABC order") ## End(Not run) ## Please see ?AEdotplot for examples using the formula method ## ## Many more examples are in demo("AEdotplotManyExamples")
Compute and plot oneway analysis of covariance.
The result object is an ancova
object which consists of
an ordinary aov
object with an additional trellis
attribute. The
trellis
attribute is a trellis
object consisting of
a series of plots of y ~ x
. The left set of panels is
conditioned on the levels of the factor groups
. The right
panel is a superpose of all the groups.
ancova(formula, data.in = NULL, ..., x, groups, transpose = FALSE, display.plot.command = FALSE, superpose.level.name = "superpose", ignore.groups = FALSE, ignore.groups.name = "ignore.groups", blocks, blocks.pch = letters[seq(levels(blocks))], layout, between, main, pch=trellis.par.get()$superpose.symbol$pch) panel.ancova(x, y, subscripts, groups, transpose = FALSE, ..., coef, contrasts, classes, ignore.groups, blocks, blocks.pch, blocks.cex, pch) ## The following are ancova methods for generic functions. ## S3 method for class 'ancova' anova(object, ...) ## S3 method for class 'ancova' predict(object, ...) ## S3 method for class 'ancova' print(x, ...) ## prints the anova(x) and the trellis attribute ## S3 method for class 'ancova' model.frame(formula, ...) ## S3 method for class 'ancova' summary(object, ...) ## S3 method for class 'ancova' plot(x, y, ...) ## standard lm plot. y is always ignored. ## S3 method for class 'ancova' coef(object, ...)
ancova(formula, data.in = NULL, ..., x, groups, transpose = FALSE, display.plot.command = FALSE, superpose.level.name = "superpose", ignore.groups = FALSE, ignore.groups.name = "ignore.groups", blocks, blocks.pch = letters[seq(levels(blocks))], layout, between, main, pch=trellis.par.get()$superpose.symbol$pch) panel.ancova(x, y, subscripts, groups, transpose = FALSE, ..., coef, contrasts, classes, ignore.groups, blocks, blocks.pch, blocks.cex, pch) ## The following are ancova methods for generic functions. ## S3 method for class 'ancova' anova(object, ...) ## S3 method for class 'ancova' predict(object, ...) ## S3 method for class 'ancova' print(x, ...) ## prints the anova(x) and the trellis attribute ## S3 method for class 'ancova' model.frame(formula, ...) ## S3 method for class 'ancova' summary(object, ...) ## S3 method for class 'ancova' plot(x, y, ...) ## standard lm plot. y is always ignored. ## S3 method for class 'ancova' coef(object, ...)
formula |
A formula specifying the model. |
data.in |
A data frame in which the variables specified in the formula will be found. If missing, the variables are searched for in the standard way. |
... |
Arguments to be passed to |
x |
Covariate in |
groups |
Factor. Needed for plotting when the formula does not
include |
transpose |
S-Plus: The axes in each panel of the plot are transposed. The analysis is identical, just the axes displaying it have been interchanged. R: no effect. |
display.plot.command |
The default setting is usually what the user
wants. The alternate value |
superpose.level.name |
Name used in strip label for superposed panel. |
ignore.groups |
When |
ignore.groups.name |
Name used in strip label for
|
pch |
Plotting character for groups. |
blocks |
Additional factor used to label points in the panels. |
blocks.pch |
Alternate set of labels used when a |
blocks.cex |
Alternate set of |
layout |
The layout of multiple panels. The default is a single row. See details. |
between |
Space between the panels for the individual group levels and the superpose panel including all groups. |
main |
Character with a main header title to be done on the top of each page. |
y , subscripts
|
In |
object |
An |
object. The functions using this argument are methods for the similarly named generic functions.
coef , contrasts , classes
|
Internal variables used to communicate between
|
The ancova
function does two things. It passes its
arguments directly to the aov
function and returns the entire
aov
object. It also rearranges the data and formula in its
argument and passes that to the xyplot
function. The
trellis
attribute is a trellis
object consisting of
a series of plots of y ~ x
. The left set of panels is
conditioned on the levels of the factor groups
. The right
panel is a superpose of all the groups.
The result object is an ancova
object which consists of
an ordinary aov
object with an additional trellis
attribute. The default print method is to print both the anova
of the object and the trellis
attribute.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
ancova-class
aov
xyplot
.
See ancovaplot
for a newer set of functions that keep the
graph and the aov
object separate.
data(hotdog) ## y ~ x ## constant line across all groups ancova(Sodium ~ Calories, data=hotdog, groups=Type) ## y ~ a ## different horizontal line in each group ancova(Sodium ~ Type, data=hotdog, x=Calories) ## This is the usual usage ## y ~ x + a or y ~ a + x ## constant slope, different intercepts ancova(Sodium ~ Calories + Type, data=hotdog) ancova(Sodium ~ Type + Calories, data=hotdog) ## y ~ x * a or y ~ a * x ## different slopes, and different intercepts ancova(Sodium ~ Calories * Type, data=hotdog) ancova(Sodium ~ Type * Calories, data=hotdog) ## y ~ a * x ## save the object and print the trellis graph hotdog.ancova <- ancova(Sodium ~ Type * Calories, data=hotdog) attr(hotdog.ancova, "trellis") ## label points in the panels by the value of the block factor data(apple) ancova(yield ~ treat + pre, data=apple, blocks=block) ## Please see ## demo("ancova") ## for a composite graph illustrating the four models listed above.
data(hotdog) ## y ~ x ## constant line across all groups ancova(Sodium ~ Calories, data=hotdog, groups=Type) ## y ~ a ## different horizontal line in each group ancova(Sodium ~ Type, data=hotdog, x=Calories) ## This is the usual usage ## y ~ x + a or y ~ a + x ## constant slope, different intercepts ancova(Sodium ~ Calories + Type, data=hotdog) ancova(Sodium ~ Type + Calories, data=hotdog) ## y ~ x * a or y ~ a * x ## different slopes, and different intercepts ancova(Sodium ~ Calories * Type, data=hotdog) ancova(Sodium ~ Type * Calories, data=hotdog) ## y ~ a * x ## save the object and print the trellis graph hotdog.ancova <- ancova(Sodium ~ Type * Calories, data=hotdog) attr(hotdog.ancova, "trellis") ## label points in the panels by the value of the block factor data(apple) ancova(yield ~ treat + pre, data=apple, blocks=block) ## Please see ## demo("ancova") ## for a composite graph illustrating the four models listed above.
Analysis of Covariance. The class is an extension of "aov"
and "lm". It is identical to the "aov" for a single factor and a single
covariate plus an attribute which contains a "trellis"
object.
Four different models are included in the class. See ancova
for the examples.
A virtual Class: No objects may be created from it.
Class "aov"
, directly.
Class "lm"
, by class "aov", distance 2.
Class "mlm"
, by class "aov", distance 2, with explicit test and coerce.
Class "oldClass"
, by class "aov", distance 3.
Class "oldClass"
, by class "aov", distance 4, with explicit test and coerce.
No methods defined with class "ancova" in the signature.
S3-type methods are
"anova.ancova"
, "coef.ancova"
,
"coefficients.ancova"
, "model.frame.ancova"
,
"plot.ancova"
, "predict.ancova"
,
"print.ancova"
, "summary.ancova"
.
"plot.ancova(x)"
plots a standard lm plot of x
.
"print.ancova(x)"
prints the anova(x)
and the trellis attribute.
The remaining methods use NextMethod
.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Analysis of Covariance Plots. Any of the ancova modelsy ~ x * t
y ~ t * x
y ~ x + t
y ~ t + x
y ~ x , groups=t
y ~ t, x=x
y ~ x * t, groups=b
y ~ t * x, groups=b
y ~ x + t, groups=b
y ~ t + x, groups=b
ancovaplot(object, ...) ## S3 method for class 'formula' ancovaplot(object, data, groups=NULL, x=NULL, ..., formula=object, col=rep(tpg$col, length=length(levels(as.factor(groups)))), pch=rep(c(15,19,17,18,16,20, 0:14), length=length(levels(as.factor(groups)))), slope, intercept, layout=c(length(levels(cc)), 1), col.line=col, lty=1, superpose.panel=TRUE, between=if (superpose.panel) list(x=c(rep(0, length(levels(cc))-1), 1)) else list(x=0), col.by.groups=FALSE ## ignored unless groups= is specified ) panel.ancova.superpose(x, y, subscripts, groups, slope, intercept, col, pch, ..., col.line, lty, superpose.panel, col.by.groups, condition.factor, groups.cc.incompatible, plot.resids=FALSE, print.resids=FALSE, mean.x.line=FALSE, col.mean.x.line="gray80")
ancovaplot(object, ...) ## S3 method for class 'formula' ancovaplot(object, data, groups=NULL, x=NULL, ..., formula=object, col=rep(tpg$col, length=length(levels(as.factor(groups)))), pch=rep(c(15,19,17,18,16,20, 0:14), length=length(levels(as.factor(groups)))), slope, intercept, layout=c(length(levels(cc)), 1), col.line=col, lty=1, superpose.panel=TRUE, between=if (superpose.panel) list(x=c(rep(0, length(levels(cc))-1), 1)) else list(x=0), col.by.groups=FALSE ## ignored unless groups= is specified ) panel.ancova.superpose(x, y, subscripts, groups, slope, intercept, col, pch, ..., col.line, lty, superpose.panel, col.by.groups, condition.factor, groups.cc.incompatible, plot.resids=FALSE, print.resids=FALSE, mean.x.line=FALSE, col.mean.x.line="gray80")
formula , object
|
|
data |
|
groups |
If the treatment factor is included in the |
x |
Covariate. Required by For |
... |
Other arguments to be passed to |
col , pch
|
Standard lattice arguments. |
slope , intercept
|
Vector, the length of the number of treatment levels, containing slope
and intercept of the |
layout , between
|
Standard lattice arguments. |
col.line , lty
|
Standard lattice arguments. By default, they follow the value of the
treatment factor in the |
y , subscripts
|
See |
superpose.panel |
logical. if |
col.by.groups |
logical. See the discussion in argument |
condition.factor , groups.cc.incompatible
|
These are both internal variables. |
plot.resids , print.resids , mean.x.line , col.mean.x.line
|
logical, logical, logical or numeric, color name.
When |
ancova=aov specification
|
xyplot specification |
abline |
|
y ~ x * t
|
y ~ x | t, groups=t |
lm(y[t] ~ x[t]) |
## separate lines |
y ~ t * x
|
y ~ x | t, groups=t |
lm(y[t] ~ x[t]) |
## separate lines |
y ~ x + t
|
y ~ x | t, groups=t |
lm(y ~ x + t) |
## parallel lines |
y ~ t + x
|
y ~ x | t, groups=t |
lm(y ~ x + t) |
## parallel lines |
y ~ x , groups=t
|
y ~ x | t, groups=t |
lm(y ~ x) |
## single regression line |
y ~ t, x=x
|
y ~ x | t, groups=t |
mean(t) |
## separate horizontal lines |
y ~ x * t, groups=b
|
y ~ x | t, groups=b |
lm(y[t] ~ x[t]) |
## sep lines, pch&col follow b |
y ~ t * x, groups=b
|
y ~ x | t, groups=b |
lm(y[t] ~ x[t]) |
## sep lines, pch&col follow b |
y ~ x + t, groups=b
|
y ~ x | t, groups=b |
lm(y ~ x + t) |
## par lines, pch&col follow b |
y ~ t + x, groups=b
|
y ~ x | t, groups=b |
lm(y ~ x + t) |
## par lines, pch&col follow b
|
ancovaplot
returns a c("ancova","trellis")
object.
panel.ancova.superpose
is an ordinary lattice panel
function.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
See the older ancova
.
data(hotdog, package="HH") ancovaplot(Sodium ~ Calories + Type, data=hotdog) ancovaplot(Sodium ~ Calories * Type, data=hotdog) ancovaplot(Sodium ~ Calories, groups=Type, data=hotdog) ancovaplot(Sodium ~ Type, x=Calories, data=hotdog) ## Please see demo("ancova", package="HH") to coordinate placement ## of all four of these plots on the same page. ancovaplot(Sodium ~ Calories + Type, data=hotdog, plot.resids=TRUE)
data(hotdog, package="HH") ancovaplot(Sodium ~ Calories + Type, data=hotdog) ancovaplot(Sodium ~ Calories * Type, data=hotdog) ancovaplot(Sodium ~ Calories, groups=Type, data=hotdog) ancovaplot(Sodium ~ Type, x=Calories, data=hotdog) ## Please see demo("ancova", package="HH") to coordinate placement ## of all four of these plots on the same page. ancovaplot(Sodium ~ Calories + Type, data=hotdog, plot.resids=TRUE)
ANOVA table for a c("ancovaplot","trellis") object.
## S3 method for class 'ancovaplot' anova(object, ...) aov.ancovaplot(object, warn=TRUE) aovStatement(object, ...) ## S3 method for class 'ancovaplot' aovStatement(object, ...) aovStatementAndAnova(object, ...) ## S3 method for class 'ancovaplot' aovStatementAndAnova(object, ...) ## S3 method for class 'ancovaplot' model.tables(x, ...)
## S3 method for class 'ancovaplot' anova(object, ...) aov.ancovaplot(object, warn=TRUE) aovStatement(object, ...) ## S3 method for class 'ancovaplot' aovStatement(object, ...) aovStatementAndAnova(object, ...) ## S3 method for class 'ancovaplot' aovStatementAndAnova(object, ...) ## S3 method for class 'ancovaplot' model.tables(x, ...)
object , x
|
|
warn , ...
|
|
The aov.ancovaplot
modifies the call
item into an
aov
call with the same formula and data. If there are
groups
in the call specified as a name, the groups
factor is included in the constructed aov
call only if there
are both a factor and a covariate in the right-hand-side of the
formula. In that case they the groups
will be interpreted as a
block factor and will be placed first. If the groups
are
specified as a vector of values in the call, the groups
are
ignored with a warning. If there is only one term in the
right-hand-side, then the groups
factor will not be placed
into the aov
formula. In this case, there will be a warning if
the argument warn
is TRUE
, and no warning if the warn
argument is FALSE
.
Richard M. Heiberger <[email protected]>
Oneway ANOVA table from the summary information consisting of group sample sizes, means, and standard deviations. The full dataset is not needed.
anovaMean(object, n, ybar, s, ..., ylabel = "ylabel")
anovaMean(object, n, ybar, s, ..., ylabel = "ylabel")
object |
level names |
n |
sample size for each level |
ybar |
sample mean for each level |
s |
sample standard deviation for each level |
... |
other arguments (not used) |
ylabel |
name of response variable |
Analysis of variance table, identical to the ANOVA table
that would have been produced by anova.lm
if the original data, rather than the summary data, had been available.
Richard M. Heiberger <[email protected]>
## pulmonary data used in Hsu and Peruggia paper defining the mean-mean plot ## See ?plot.mmc.multicomp for details on the dataset. data(pulmonary) anovaMean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary")
## pulmonary data used in Hsu and Peruggia paper defining the mean-mean plot ## See ?plot.mmc.multicomp for details on the dataset. data(pulmonary) anovaMean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary")
Analysis of variance from sufficient statistics for groups.
For each group, we need the factor level, the response mean, the
within-group standard deviation, and the sample size.
The correct ANOVA table is produced. The residuals are fake.
The generic vcov
and summary.lm
don't work for the
variance of the regression coefficients in this case.
Use vcovSufficient
.
aovSufficient(formula, data = NULL, projections = FALSE, qr = TRUE, contrasts = NULL, weights = data$n, sd = data$s, ...) vcovSufficient(object, ...)
aovSufficient(formula, data = NULL, projections = FALSE, qr = TRUE, contrasts = NULL, weights = data$n, sd = data$s, ...) vcovSufficient(object, ...)
formula , data , projections , qr , contrasts , ...
|
See
|
weights |
See
|
sd |
vector of within-group standard deviations. |
object |
|
For aovSufficient
, an object of class c("aov", "lm").
For vcovSufficient
, a function that returns the covariance
matrix of the regression coefficients.
The residuals are fake. They are all identical and equal to the MLE
standard error (sqrt(SumSq.res/df.tot)
). They give the right
ANOVA table. They may cause confusion or warnings in other programs.
The standard errors and t-tests of the coefficients are not calculated
by summary.lm
.
Using the aov
object from aovSufficient
in glht
requires the vcov.
and df
arguments.
Richard M. Heiberger <[email protected]>
## This example is from Hsu and Peruggia ## This is the R version ## See ?mmc.mean for S-Plus if.R(s={}, r={ data(pulmonary) pulmonary pulmonary.aov <- aovSufficient(FVC ~ smoker, data=pulmonary) summary(pulmonary.aov) ## Not run: pulmonary.mmc <- mmc(pulmonary.aov, linfct=mcp(smoker="Tukey"), df=pulmonary.aov$df.residual, vcov.=vcovSufficient) mmcplot(pulmonary.mmc, style="both") ## orthogonal contrasts pulm.lmat <- cbind("npnl-mh"=c( 1, 1, 1, 1,-2,-2), ## not.much vs lots "n-pnl" =c( 3,-1,-1,-1, 0, 0), ## none vs light "p-nl" =c( 0, 2,-1,-1, 0, 0), ## {} arbitrary 2 df "n-l" =c( 0, 0, 1,-1, 0, 0), ## {} for 3 types of light "m-h" =c( 0, 0, 0, 0, 1,-1)) ## moderate vs heavy dimnames(pulm.lmat)[[1]] <- row.names(pulmonary) pulm.lmat pulmonary.mmc <- mmc(pulmonary.aov, linfct=mcp(smoker="Tukey"), df=pulmonary.aov$df.residual, vcov.=vcovSufficient, focus.lmat=pulm.lmat) mmcplot(pulmonary.mmc, style="both", type="lmat") ## End(Not run) })
## This example is from Hsu and Peruggia ## This is the R version ## See ?mmc.mean for S-Plus if.R(s={}, r={ data(pulmonary) pulmonary pulmonary.aov <- aovSufficient(FVC ~ smoker, data=pulmonary) summary(pulmonary.aov) ## Not run: pulmonary.mmc <- mmc(pulmonary.aov, linfct=mcp(smoker="Tukey"), df=pulmonary.aov$df.residual, vcov.=vcovSufficient) mmcplot(pulmonary.mmc, style="both") ## orthogonal contrasts pulm.lmat <- cbind("npnl-mh"=c( 1, 1, 1, 1,-2,-2), ## not.much vs lots "n-pnl" =c( 3,-1,-1,-1, 0, 0), ## none vs light "p-nl" =c( 0, 2,-1,-1, 0, 0), ## {} arbitrary 2 df "n-l" =c( 0, 0, 1,-1, 0, 0), ## {} for 3 types of light "m-h" =c( 0, 0, 0, 0, 1,-1)) ## moderate vs heavy dimnames(pulm.lmat)[[1]] <- row.names(pulmonary) pulm.lmat pulmonary.mmc <- mmc(pulmonary.aov, linfct=mcp(smoker="Tukey"), df=pulmonary.aov$df.residual, vcov.=vcovSufficient, focus.lmat=pulm.lmat) mmcplot(pulmonary.mmc, style="both", type="lmat") ## End(Not run) })
Repair design error in S-Plus arima.diag
.
arima.diag.hh(z, acf.resid = TRUE, lag.max = round(max(gof.lag + n.parms + 1, 10 * log10(n))), gof.lag = 15, resid = FALSE, std.resid = TRUE, plot = TRUE, type = "h", ..., x=eval(parse(text = series.name)))
arima.diag.hh(z, acf.resid = TRUE, lag.max = round(max(gof.lag + n.parms + 1, 10 * log10(n))), gof.lag = 15, resid = FALSE, std.resid = TRUE, plot = TRUE, type = "h", ..., x=eval(parse(text = series.name)))
z , acf.resid , lag.max , gof.lag , resid , std.resid , plot , type , ...
|
This function is a no-op in R. The arguments are not used. |
x |
The time series. This must be specified when arima.diag is called from inside another function. |
Repairs design flaw in S-Plus arima.diag
. The location of the time
series is hardwired one level up, so it can't be found when
arima.diag
is not one level down from the top.
This function is a no-op in R.
This function is a no-op in R. It returns NA
.
Richard M. Heiberger <[email protected]>
tsdiagplot
in both systems and
arima.diag
in S-Plus.
Loop through a series of ARIMA models and display coordinated tables and diagnostic graphs. The complete example from the Heiberger and Teles article, also included in the Heiberger and Holland book, is illustrated.
arma.loop(x, model, ## S-Plus order, seasonal, ## R series=deparse(substitute(x)), ...) diag.arma.loop(z, x=stop("The time series x is needed in S-Plus when p=q=0."), lag.max = 36, gof.lag = lag.max) rearrange.diag.arma.loop(z)
arma.loop(x, model, ## S-Plus order, seasonal, ## R series=deparse(substitute(x)), ...) diag.arma.loop(z, x=stop("The time series x is needed in S-Plus when p=q=0."), lag.max = 36, gof.lag = lag.max) rearrange.diag.arma.loop(z)
x |
Time series vector. In S-Plus, |
model |
A valid S-Plus |
order , seasonal
|
A valid R |
series |
Character string describing the time series. |
... |
Additional arguments for |
z |
For |
lag.max |
Maximum lag for the acf and pacf plots. |
gof.lag |
Maximum lag for the gof plots. |
S-Plus and R have different functions, with different input argument names and different components in their value.
arma.loop
: "arma.loop"
object which is a matrix of
lists, each containing an arima model.
diag.arma.loop
: "diag.arma.loop"
object which is a
matrix of lists, each containing the standard diagnostics for one
arima model.
rearrange.diag.arma.loop
: List of matrices, each containing
all the values for a specific diagnostic measure collected from the
set of arima models.
Richard M. Heiberger ([email protected])
"Displays for Direct Comparison of ARIMA Models" The American Statistician, May 2002, Vol. 56, No. 2, pp. 131-138. Richard M. Heiberger, Temple University, and Paulo Teles, Faculdade de Economia do Porto.
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
## see tsdiagplot for the example
## see tsdiagplot for the example
Constructs class="likert" objects to be used by the plot.likert methods.
is.likert(x) as.likert(x, ...) ## Default S3 method: as.likert(x, ...) ## S3 method for class 'data.frame' as.likert(x, ...) ## S3 method for class 'formula' as.likert(x, ...) ## doesn't work yet ## S3 method for class 'ftable' as.likert(x, ...) ## S3 method for class 'table' as.likert(x, ...) ## S3 method for class 'matrix' as.likert(x, ReferenceZero=NULL, ..., rowlabel=NULL, collabel=NULL, xlimEqualLeftRight=FALSE, xTickLabelsPositive=TRUE, padding=FALSE, reverse.left=TRUE) ## S3 method for class 'listOfNamedMatrices' as.likert(x, ...) ## S3 method for class 'array' as.likert(x, ...) ## S3 method for class 'likert' rev(x) is.likertCapable(x, ...)
is.likert(x) as.likert(x, ...) ## Default S3 method: as.likert(x, ...) ## S3 method for class 'data.frame' as.likert(x, ...) ## S3 method for class 'formula' as.likert(x, ...) ## doesn't work yet ## S3 method for class 'ftable' as.likert(x, ...) ## S3 method for class 'table' as.likert(x, ...) ## S3 method for class 'matrix' as.likert(x, ReferenceZero=NULL, ..., rowlabel=NULL, collabel=NULL, xlimEqualLeftRight=FALSE, xTickLabelsPositive=TRUE, padding=FALSE, reverse.left=TRUE) ## S3 method for class 'listOfNamedMatrices' as.likert(x, ...) ## S3 method for class 'array' as.likert(x, ...) ## S3 method for class 'likert' rev(x) is.likertCapable(x, ...)
x |
For the |
rowlabel , collabel
|
|
... |
other arguments. They will be ignored by
the |
ReferenceZero |
Please see discussion of this argument
in |
xlimEqualLeftRight |
Logical. The default is |
xTickLabelsPositive |
Logical. The default is |
padding , reverse.left
|
|
Please see likert
for information on the plot for which
as.likert
prepares the data.
For the as.likert
methods, a likert
object, which is
a matrix with additional attributes that are needed to make the
barchart
method used by the plot.likert
methods
work with the data. Columns for respondents who
disagree have negated values.
Any NA
values in the argument x
are changed to 0
.
The column of the original data for respondents who
neither agree nor disagree is split into two columns, each containing
halved values—one positive and one negative.
Negative columns come first in the sequence of "No Opinion"(negative)–"Strongly
Disagree",
followed by "No Opinion"(positive)–"Strongly Agree".
There are four
attributes:
"even.col"
indicating whether there were originally an even
number of columns, "n.levels"
the original number of levels,
"levels"
the original levels in the original order, "positive.order"
The sequence in which to display the rows in order to make the right
hand sides progress with high values on top.
is.likert
returns a TRUE
or FALSE
value.
is.likertCapable
returns a TRUE
or FALSE
value
if the argument can used as an argument to one of the plot.likert
methods.
Richard M. Heiberger <[email protected]>
Richard M. Heiberger, Naomi B. Robbins (2014)., "Design of Diverging Stacked Bar Charts for Likert Scales and Other Applications", Journal of Statistical Software, 57(5), 1–32, doi:10.18637/jss.v057.i05.
Naomi Robbins <[email protected]>, "Visualizing Data: Challenges to Presentation of Quality Graphics—and Solutions", Amstat News, September 2011, 28–30.
Naomi B. Robbins and Richard M. Heiberger (2011). Plotting Likert and Other Rating Scales. In JSM Proceedings, Section on Survey Research Methods. Alexandria, VA: American Statistical Association.
Luo, Amy and Tim Keyes (2005). "Second Set of Results in from the Career Track Member Survey," Amstat News. Arlington, VA: American Statistical Association.
## Please see ?likert to see these functions used in context. tmp2 <- array(1:12, dim=c(3,4), dimnames=list(B=LETTERS[3:5], C=letters[6:9])) as.likert(tmp2) ## even number of levels. is.likert(tmp2) is.likert(as.likert(tmp2))
## Please see ?likert to see these functions used in context. tmp2 <- array(1:12, dim=c(3,4), dimnames=list(B=LETTERS[3:5], C=letters[6:9])) as.likert(tmp2) ## even number of levels. is.likert(tmp2) is.likert(as.likert(tmp2))
Convert a list of numeric matrices to a single matrix. This function is used
to improve legibility of the printed object. The
as.matrix.listOfNamedMatrices
display is easier to read when the rownames
are very long, as in the example illustrated here. Because the
default print of the matrix repeats the rownames several times, with
only a few columns of the data shown in each repetition, the actual
matrix structure of the data values is obscured.
## S3 method for class 'listOfNamedMatrices' as.matrix(x, abbreviate = TRUE, minlength = 4, ...) is.listOfNamedMatrices(x, xName=deparse(substitute(x))) ## S3 method for class 'listOfNamedMatrices' as.data.frame(x, ...) as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'listOfNamedMatrices' x[...] ## S3 method for class 'array' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'list' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'MatrixList' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'listOfNamedMatrices' print(x, ...) as.MatrixList(x) ## S3 method for class 'array' as.MatrixList(x) ## S3 method for class 'MatrixList' print(x, ...) as.likertDataFrame(x, xName=deparse(substitute(x))) ## S3 method for class 'listOfNamedMatrices' as.likertDataFrame(x, xName=deparse(substitute(x))) ## S3 method for class 'array' as.likertDataFrame(x, xName=deparse(substitute(x)))
## S3 method for class 'listOfNamedMatrices' as.matrix(x, abbreviate = TRUE, minlength = 4, ...) is.listOfNamedMatrices(x, xName=deparse(substitute(x))) ## S3 method for class 'listOfNamedMatrices' as.data.frame(x, ...) as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'listOfNamedMatrices' x[...] ## S3 method for class 'array' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'list' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'MatrixList' as.listOfNamedMatrices(x, xName=deparse(substitute(x)), ...) ## S3 method for class 'listOfNamedMatrices' print(x, ...) as.MatrixList(x) ## S3 method for class 'array' as.MatrixList(x) ## S3 method for class 'MatrixList' print(x, ...) as.likertDataFrame(x, xName=deparse(substitute(x))) ## S3 method for class 'listOfNamedMatrices' as.likertDataFrame(x, xName=deparse(substitute(x))) ## S3 method for class 'array' as.likertDataFrame(x, xName=deparse(substitute(x)))
x |
Named list of numeric matrices. All matrices in the list
should have the same number of columns and the same column names.
The names of the list items will normally be long; NA, as
introduced by the |
... |
Other arguments. Not used. |
abbreviate |
Logical. If |
minlength |
the minimum length of the abbreviations. |
xName |
Name of the argument in its original environment. |
The result of as.listOfNamedMatrices
is a list with
class=c("listOfNamedMatrices", "list")
.
The result of as.matrix.listOfNamedMatrices
is an rbind
of
the individual matrices in the argument list x
. The rownames of
the result matrix are constructed by pasting the abbreviation of the
list item names with the abbreviation of the individual matrix rownames.
The original names are retained as the "Subtables.Rows"
attribute.
The result of is.listOfNamedMatrices
is logical value.
print.listOfNamedMatrices
prints
as.matrix.listOfNamedMatrices
of its argument and returns the
original argument.
as.data.frame.listOfNamedMatrices(x, ...)
is an unfortunate
kluge. The result is the original x
that has NOT been
transformed to a data.frame
. A warning
message is
generated that states that the conversion has not taken place. This
kluge is needed to use "listOfNamedMatrices"
objects with the
Commander
package because Rcmdr
follows
its calls to the R data
function with an attempt,
futile in this case, to force the resulting object to be a data.frame
.
The as.MatrixList
methods construct a list of matrices from an
array. Each matrix has the first two dimensions of the array. The
result list is itself an array defined by all but the first two
dimensions of the argument array.
Richard M. Heiberger <[email protected]>
data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question ProfChal.list <- split.data.frame(tmp, ProfChal$Subtable) ## Original list of matrices is difficult to read because ## it is displayed on too many lines. ProfChal.list[2:3] ## Single matrix with long list item names and long row names ## of argument list retained as an attribute. as.listOfNamedMatrices(ProfChal.list[2:3], minlength=6) ## Not run: ## NA as a dimname value tmp <- structure(c(0, 0, 0, 6293, 18200, 2122, 0, 0, 0, 2462, 7015, 5589, 6908, 5337, 842, 0, 0, 0), .Dim = c(3L, 2L, 3L), .Dimnames = list(c("A", "B", "C"), c("D", "E"), c("F", "G", NA))) tmp as.MatrixList(tmp) ## End(Not run) ## Not run: sapply(as.MatrixList(tmp3), as.likert, simplify=FALSE) ## odd number of levels. data(NZScienceTeaching) likert(Question ~ ., NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching, layout=c(1,2), scales=list(y=list(relation="free"))) ## End(Not run)
data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question ProfChal.list <- split.data.frame(tmp, ProfChal$Subtable) ## Original list of matrices is difficult to read because ## it is displayed on too many lines. ProfChal.list[2:3] ## Single matrix with long list item names and long row names ## of argument list retained as an attribute. as.listOfNamedMatrices(ProfChal.list[2:3], minlength=6) ## Not run: ## NA as a dimname value tmp <- structure(c(0, 0, 0, 6293, 18200, 2122, 0, 0, 0, 2462, 7015, 5589, 6908, 5337, 842, 0, 0, 0), .Dim = c(3L, 2L, 3L), .Dimnames = list(c("A", "B", "C"), c("D", "E"), c("F", "G", NA))) tmp as.MatrixList(tmp) ## End(Not run) ## Not run: sapply(as.MatrixList(tmp3), as.likert, simplify=FALSE) ## odd number of levels. data(NZScienceTeaching) likert(Question ~ ., NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching, layout=c(1,2), scales=list(y=list(relation="free"))) ## End(Not run)
MMC plots: In R, functions used to interface the glht
in R to the MMC
functions designed with S-Plus multicomp
notation. These are
all internal functions that the user doesn't see.
## S3 method for class 'mmc.multicomp' print(x, ..., width.cutoff=options()$width-5) ## S3 method for class 'multicomp' print(x, ...) ## print.multicomp.hh(x, digits = 4, ..., height=T) ## S-Plus only ## S3 method for class 'multicomp.hh' print(x, ...) ## R only as.multicomp(x, ...) ## S3 method for class 'glht' as.multicomp(x, ## glht object focus=x$focus, ylabel=deparse(terms(x$model)[[2]]), means=model.tables(x$model, type="means", cterm=focus)$tables[[focus]], height=rev(1:nrow(x$linfct)), lmat=t(x$linfct), lmat.rows=lmatRows(x, focus), lmat.scale.abs2=TRUE, estimate.sign=1, order.contrasts=TRUE, contrasts.none=FALSE, level=0.95, calpha=NULL, method=x$type, df, vcov., ... ) as.glht(x, ...) ## S3 method for class 'multicomp' as.glht(x, ...)
## S3 method for class 'mmc.multicomp' print(x, ..., width.cutoff=options()$width-5) ## S3 method for class 'multicomp' print(x, ...) ## print.multicomp.hh(x, digits = 4, ..., height=T) ## S-Plus only ## S3 method for class 'multicomp.hh' print(x, ...) ## R only as.multicomp(x, ...) ## S3 method for class 'glht' as.multicomp(x, ## glht object focus=x$focus, ylabel=deparse(terms(x$model)[[2]]), means=model.tables(x$model, type="means", cterm=focus)$tables[[focus]], height=rev(1:nrow(x$linfct)), lmat=t(x$linfct), lmat.rows=lmatRows(x, focus), lmat.scale.abs2=TRUE, estimate.sign=1, order.contrasts=TRUE, contrasts.none=FALSE, level=0.95, calpha=NULL, method=x$type, df, vcov., ... ) as.glht(x, ...) ## S3 method for class 'multicomp' as.glht(x, ...)
x |
|
... |
other arguments. |
focus |
name of focus factor. |
ylabel |
response variable name on the graph. |
means |
means of the response variable on the |
lmat , lmat.rows
|
|
lmat.scale.abs2 |
logical, almost always |
estimate.sign |
numeric. 1: force all contrasts to be positive by
reversing negative contrasts. $-1$: force all contrasts to be negative by
reversing positive contrasts. Leave contrasts as they are constructed
by |
order.contrasts , height
|
logical. If |
contrasts.none |
logical. This is an internal detail. The
“contrasts” for the group means are not real contrasts in the
sense they don't compare anything. |
level |
Confidence level. Defaults to 0.95. |
calpha |
R only. User-specified critical point.
See
|
df , vcov.
|
R only. Arguments forwarded through |
method |
R only. See |
width.cutoff |
See |
The mmc.multicomp
print
method displays the confidence intervals and heights on the
MMC plot for each component of the mmc.multicomp
object.
print.multicomp
displays the confidence intervals and heights for
a single component.
as.multicomp
is a generic function to change its argument to a
"multicomp"
object.
as.multicomp.glht
changes an "glht"
object to a
"multicomp"
object. If the model component of the argument "x"
is an "aov"
object then the standard error is taken from the
anova(x$model)
table, otherwise from the summary(x)
.
With a large number of levels for the focus factor, the
summary(x)
function is exceedingly slow (80 minutes for 30 levels on 1.5GHz Windows
XP).
For the same example, the anova(x$model)
takes a fraction of
a second.
The multiple comparisons calculations in R and S-Plus use
completely different functions.
MMC plots in R are based on
glht
.
MMC plots in S-Plus are based on
multicomp
.
The MMC plot is the same in both systems. The details of gettting the plot differ.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
as.vector.trellis
converts a two-dimensional trellis object into
a one-dimensional trellis object.
reorder.trellis
changes the order of the panel.args
component in a trellis object.
These are are mostly used as utilities by matrix.trellis
.
## S3 method for class 'trellis' as.vector(x, mode = "any") ## S3 method for class 'trellis' reorder(x, X, ...)
## S3 method for class 'trellis' as.vector(x, mode = "any") ## S3 method for class 'trellis' reorder(x, X, ...)
x |
|
mode |
We are hijacking the |
... |
Other arguments are ignored. |
X |
Subscript vector specifying the new order of the panels. |
trellis object with length(dim(x)) == 1
.
as.vector
retains the original order of the
panels. reorder
changes the order to the one specified by using
the X
argument as a subscript.
Richard M. Heiberger <[email protected]>
tmp <- data.frame(a=letters[c(1:3,1:3,1:3)], b=1:9, d=1:9, e=LETTERS[c(4,4,4,5,5,5,6,6,6)]) tmp a6 <- xyplot(b ~ d | a*e, data=tmp, pch=19) a6 dim(a6) a62 <- as.vector(a6) a62 dim(a62) a63 <- reorder(a6, c(1,4,7, 2,5,8, 3,6,9)) a63 dim(a63) a64 <- matrix.trellis(a63, nrow=3, ncol=3, dimnames=dimnames(a6), byrow=TRUE) a64 dim(a64)
tmp <- data.frame(a=letters[c(1:3,1:3,1:3)], b=1:9, d=1:9, e=LETTERS[c(4,4,4,5,5,5,6,6,6)]) tmp a6 <- xyplot(b ~ d | a*e, data=tmp, pch=19) a6 dim(a6) a62 <- as.vector(a6) a62 dim(a62) a63 <- reorder(a6, c(1,4,7, 2,5,8, 3,6,9)) a63 dim(a63) a64 <- matrix.trellis(a63, nrow=3, ncol=3, dimnames=dimnames(a6), byrow=TRUE) a64 dim(a64)
Labels the bottom axis with the x-factor name for each column. Labels the right axis with the response variable name in all rows.
axis.i2wt(side, scales, ...)
axis.i2wt(side, scales, ...)
side , scales , ...
|
See |
Richard M. Heiberger, with asssistance from Deepayan Sarkar.
Plot the bivariate normal density using wireframe for specified rho. There is a shiny app that allows this to be done dynamically.
bivariateNormal(rho = 0, layout = c(3, 3), lwd = 0.2, angle = c(22.5, 67.5, 112.5, 337.5, 157.5, 292.5, 247.5, 202.5), col.regions = trellis.par.get("regions")$col, ...)
bivariateNormal(rho = 0, layout = c(3, 3), lwd = 0.2, angle = c(22.5, 67.5, 112.5, 337.5, 157.5, 292.5, 247.5, 202.5), col.regions = trellis.par.get("regions")$col, ...)
rho |
Correlation between $x$ and $y$. |
layout , lwd
|
Standard lattice arguments. |
angle |
This is used as the |
col.regions , ...
|
See |
The default setting shows the view as seen from a series of eight angles. To see just a single view, see the example.
"trellis"
object.
Based on the galaxy
example on pages 204–205 in
S & S-PLUS Trellis Graphics User's Manual,
Richard A. Becker and William S. Cleveland (1996),
https://www.stat.auckland.ac.nz/~ihaka/courses/120/trellis.user.pdf
Richard M. Heiberger ([email protected])
bv8 <- bivariateNormal(.7) ## all views on one page bv8 update(bv8[3], layout=c(1,1)) ## one panel ## Not run: if (interactive()) shiny::runApp(file.path(system.file(package="HH"), "shiny/bivariateNormal")) ## 3D if (interactive()) shiny::runApp(system.file("shiny/bivariateNormalScatterplot", package="HH")) ## scatterplot ## End(Not run)
bv8 <- bivariateNormal(.7) ## all views on one page bv8 update(bv8[3], layout=c(1,1)) ## one panel ## Not run: if (interactive()) shiny::runApp(file.path(system.file(package="HH"), "shiny/bivariateNormal")) ## 3D if (interactive()) shiny::runApp(system.file("shiny/bivariateNormalScatterplot", package="HH")) ## scatterplot ## End(Not run)
The data, the least squares line, the confidence interval lines, and the
prediction interval lines for a simple
linear regression (lm(y ~ x)
) are displayed. Tick marks are
placed at the location of xbar, the x-value of the narrowest interval.
ci.plot(lm.object, ...) ## S3 method for class 'lm' ci.plot(lm.object, xlim=range(data[, x.name]), newdata, conf.level=.95, data=model.frame(lm.object), newfit, ylim, pch=19, lty=c(1,3,4,2), lwd=2, main.cex=1, main=list(paste(100*conf.level, "% confidence and prediction intervals for ", substitute(lm.object), sep=""), cex=main.cex), ... )
ci.plot(lm.object, ...) ## S3 method for class 'lm' ci.plot(lm.object, xlim=range(data[, x.name]), newdata, conf.level=.95, data=model.frame(lm.object), newfit, ylim, pch=19, lty=c(1,3,4,2), lwd=2, main.cex=1, main=list(paste(100*conf.level, "% confidence and prediction intervals for ", substitute(lm.object), sep=""), cex=main.cex), ... )
lm.object |
Linear model for one |
xlim |
|
newdata |
|
conf.level |
Confidence level for intervals, defaults to |
data |
|
newfit |
Constructed |
ylim |
|
pch |
Plotting character for observed points. |
lty , lwd
|
Line types and line width for fit and intervals. |
main.cex |
Font size for main title. |
main |
Main title for plot |
... |
Additional arguments to be passed to panel function. |
"trellis"
object containing the plot.
The predict.lm
functions in S-Plus and R differ.
The S-Plus function can produce both confidence and prediction
intervals with a single call. The R function produces only one
of them in a single call. Therefore the default calculation of
newfit
within the function depends on the system.
Richard M. Heiberger <[email protected]>
tmp <- data.frame(x=rnorm(20), y=rnorm(20)) tmp.lm <- lm(y ~ x, data=tmp) ci.plot(tmp.lm)
tmp <- data.frame(x=rnorm(20), y=rnorm(20)) tmp.lm <- lm(y ~ x, data=tmp) ci.plot(tmp.lm)
Illustration of the meaning of confidence levels. Generate sets of confidence intervals for independent randomly generated sets of normally distributed numbers. Low confidence levels give narrow intervals that are less likely to bracket the true value. Higher confidence levels increase the probability of bracketing the true value, and are also much wider and therefore less precise. The shiny app can animate how the increase in confidence level and width leads to a consequent decrease in precision.
CIplot(n.intervals = 100, n.per.row = 40, pop.mean = 0, pop.sd = 1, conf.level = 0.95, ...) confintervaldata(n.intervals = 100, n.per.row = 40, pop.mean = 0, pop.sd = 1, conf.level = 0.95, seed, ...) confinterval.matrix(x, conf.level = attr(x, "conf.level"), ...) confintervalplot(x.ci, n.intervals = nrow(x.ci), pop.mean = attr(x.ci, "pop.mean"), pop.sd = attr(x.ci, "pop.sd"), n.per.row = attr(x.ci, "n.per.row"), xlim, ylim, ...) shiny.CIplot(height = "auto")
CIplot(n.intervals = 100, n.per.row = 40, pop.mean = 0, pop.sd = 1, conf.level = 0.95, ...) confintervaldata(n.intervals = 100, n.per.row = 40, pop.mean = 0, pop.sd = 1, conf.level = 0.95, seed, ...) confinterval.matrix(x, conf.level = attr(x, "conf.level"), ...) confintervalplot(x.ci, n.intervals = nrow(x.ci), pop.mean = attr(x.ci, "pop.mean"), pop.sd = attr(x.ci, "pop.sd"), n.per.row = attr(x.ci, "n.per.row"), xlim, ylim, ...) shiny.CIplot(height = "auto")
n.intervals |
Number of sets of observations to generate. Each set leads to one confidence interval on the plot. |
n.per.row |
Number of observations in each set. |
pop.mean , pop.sd
|
Population mean and standard deviation for generated set of
|
conf.level |
Confidence level of each of the |
seed |
Standard argument to |
x |
Output matrix from |
x.ci |
Output |
xlim , ylim
|
Standard |
height |
Height of graph on web page in pixels. |
... |
Additional arguments. For |
The shiny app has sliders for the n.intervals
, n.per.row
,
pop.mean
, pop.sd
, and conf.level
.
Changes in the conf.level
slider, either manually by animation,
use the same set of generated data to show how increasing the confidence
level increases the width of the confidence interval and consequently
decreases the precision of the interval estimator.
CIplot
and confintervalplot
return a "trellis"
plot containing a plot of Confidence Intervals.
confintervaldata
returns a matrix of n.intervals
rows by
n.per.row
columns of independent normally distributed random
numbers.
The matrix has a set of attributes recording the arguments to the
function.
confinterval.matrix
returns a data.frame
of n.intervals
with three columns containing the lower bound, center, and upper bound
of the confidence interval for each row of its input matrix.
The data.frame
has a set of attributes recording the arguments to the
function.
shiny.CIplot
returns a shiny app object which, when printed,
runs a shiny app displaying the Confidence Interval plot and several
slider controls.
Richard M. Heiberger <[email protected]>
## A. from the console ## example 1 CIplot() ## example 2 ## Not run: CIplot(n.intervals=100, n.per.row=40, pop.mean=0, pop.sd=1, conf.level=.95) ## End(Not run) ## example 3 ## Not run: tmp.data <- confintervaldata() tmp.ci <- confinterval.matrix(tmp.data) confintervalplot(tmp.ci) ## End(Not run) ## example 4 ## Not run: tmp.data <- confintervaldata(n.intervals=100, n.per.row=40, pop.mean=0, pop.sd=1, conf.level=.95) tmp.ci <- confinterval.matrix(tmp.data) confintervalplot(tmp.ci) ## End(Not run) ## B. shiny, initiated from the console ## example 5 ## Not run: if (interactive()) shiny.CIplot() ## End(Not run) ## example 6 ## Not run: if (interactive()) shiny.CIplot(height=800) ## px ## take control of the height of the graph in the web page ## End(Not run)
## A. from the console ## example 1 CIplot() ## example 2 ## Not run: CIplot(n.intervals=100, n.per.row=40, pop.mean=0, pop.sd=1, conf.level=.95) ## End(Not run) ## example 3 ## Not run: tmp.data <- confintervaldata() tmp.ci <- confinterval.matrix(tmp.data) confintervalplot(tmp.ci) ## End(Not run) ## example 4 ## Not run: tmp.data <- confintervaldata(n.intervals=100, n.per.row=40, pop.mean=0, pop.sd=1, conf.level=.95) tmp.ci <- confinterval.matrix(tmp.data) confintervalplot(tmp.ci) ## End(Not run) ## B. shiny, initiated from the console ## example 5 ## Not run: if (interactive()) shiny.CIplot() ## End(Not run) ## example 6 ## Not run: if (interactive()) shiny.CIplot(height=800) ## px ## take control of the height of the graph in the web page ## End(Not run)
Initialization of an R display device with the graphical parameters that rmh prefers.
col.hh()
col.hh()
List of graphical parameters to be used in the theme
argument
to the trellis.device
or trellis.par.set
functions.
Richard M. Heiberger <[email protected]>
trellis.device
, trellis.par.get
## Not run: trellis.device(theme="col.hh") ## Open a device with the theme trellis.device(theme=col.hh()) ## Open a device with the theme trellis.par.set(theme=col.hh())## Add theme to already open device ## End(Not run)
## Not run: trellis.device(theme="col.hh") ## Open a device with the theme trellis.device(theme=col.hh()) ## Open a device with the theme trellis.par.set(theme=col.hh())## Add theme to already open device ## End(Not run)
col3x2 color dataset.
data("col3x2")
data("col3x2")
The format is: chr [1:6] "#1B9E77" "#D95F02" "#7570B3" "#66C2A5" "#FC8D62" "#8DA0CB"
3x2 color scheme. These colors look like a 3x2 color array when run through the vischeck simulator to see how they look for the three most common color vision deficiencies: Deuteranope, Protanope, Tritanope.
About 10% of the population have color deficient vision.
Your job is make your graphs legible to everyone.
Download ImageJ
from https://imagej.net/Downloads
and
VischeckJ
from
http://vischeck.com and follow the instructions in those sites.
This program will allow you to simulate color deficient vision on your computer.
On my Mac, I need to doubleclick ij.jar to open the program. Then open the "Vischeck Panel" on the Plugins menu and navigate to a png file with the "File Open" menu. Click on each of the three types of color deficiency.
data(col3x2) col3x2 ## Not run: library(RColorBrewer) library(lattice) col3x2 <- c(brewer.pal(n=3, "Dark2"), brewer.pal(n=3, "Set2")) col3x2 ## save(col3x2, file="col3x2.rda") ## data(col3x2, package="HH") ## End(Not run) ## Not run: barchart(~ 1:6, col=col3x2, lwd=0, origin=0, horizontal=FALSE, scales=list(x=list(at=1:6, labels=col3x2))) tmp <- array(c(1, rep(0,6)), c(1,3,2,6), dimnames=list("", c("green","orange","blue"), c("Dark2","Set2"), col3x2)) useOuterStrips(barchart(tmp, col=col3x2, between=list(x=1, y=1), scales=list(x=list(at=-1)), main="col3x2", xlab="")) + layer(panel.text(x=.5, y=1.45, labels=col3x2[panel.number()])) ## End(Not run)
data(col3x2) col3x2 ## Not run: library(RColorBrewer) library(lattice) col3x2 <- c(brewer.pal(n=3, "Dark2"), brewer.pal(n=3, "Set2")) col3x2 ## save(col3x2, file="col3x2.rda") ## data(col3x2, package="HH") ## End(Not run) ## Not run: barchart(~ 1:6, col=col3x2, lwd=0, origin=0, horizontal=FALSE, scales=list(x=list(at=1:6, labels=col3x2))) tmp <- array(c(1, rep(0,6)), c(1,3,2,6), dimnames=list("", c("green","orange","blue"), c("Dark2","Set2"), col3x2)) useOuterStrips(barchart(tmp, col=col3x2, between=list(x=1, y=1), scales=list(x=list(at=-1)), main="col3x2", xlab="")) + layer(panel.text(x=.5, y=1.45, labels=col3x2[panel.number()])) ## End(Not run)
Combine limits on a one-dimensional trellis object.
combineLimits.trellisvector(x, margin.x = 1:2, margin.y = 1:2, layout = x$layout, ncol=x$layout[1], nrow=x$layout[2], condlevels = x$condlevels[[1]], ...)
combineLimits.trellisvector(x, margin.x = 1:2, margin.y = 1:2, layout = x$layout, ncol=x$layout[1], nrow=x$layout[2], condlevels = x$condlevels[[1]], ...)
x |
|
margin.x , margin.y
|
See |
layout |
See |
condlevels |
Character. Names of each panel of the result. Defaults to the names of the panels of the argument. |
... |
Other arguments are ignored. |
nrow , ncol
|
See |
The one-dimensional object is converted to a two-dimensional object
which
is forwarded to the standard combineLimits
function. The result
is converted back to a one-dimensional object.
One-dimensional trellis object with combined xlim and ylim values across all panels.
Richard M. Heiberger <[email protected]>
tmp <- data.frame(a=1:3, b=c(4,5,7), c=5:7, d=c(8, 9, 12), e=9:11) tmp a2 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, scales=list(relation="free"), main="a2") a2 dim(a2) combineLimits.trellisvector(a2) a21 <- combineLimits.trellisvector(update(a2, layout=c(3,2))) a21 dim(a21)
tmp <- data.frame(a=1:3, b=c(4,5,7), c=5:7, d=c(8, 9, 12), e=9:11) tmp a2 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, scales=list(relation="free"), main="a2") a2 dim(a2) combineLimits.trellisvector(a2) a21 <- combineLimits.trellisvector(update(a2, layout=c(3,2))) a21 dim(a21)
Rearranges and improves the legibility of the output from
the
stepwise
function in S-Plus.
The output can be used for the Cp plot.
cp.calc
works only in S-Plus.
Use
regsubsets
in R. The example below works in both languages.
cp.calc(sw, data, y.name) ## S3 method for class 'cp.object' print(x, ...) ## S3 method for class 'cp.object' x[..., drop = TRUE]
cp.calc(sw, data, y.name) ## S3 method for class 'cp.object' print(x, ...) ## S3 method for class 'cp.object' x[..., drop = TRUE]
sw |
Output from the S-Plus
function. |
data |
Dataset name from which |
y.name |
Name of response variable for which |
x |
Object of class |
... |
Additional arguments to |
drop |
Argument to the |
"cp.object"
, which is a data.frame containing information
about each model that was attempted with additional
attributes:
tss
total sum of squares,
n
number of observations,
y.name
response variable,
full.i
row name of full model. The columns are
p |
number of parameters in the model |
cp |
Cp statistic |
aic |
AIC statistic |
rss |
Residual sum of squares |
r2 |
|
r2.adj |
Adjusted |
xvars |
X variables |
sw.names |
Model name produced by |
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
## This example is from Section 9.15 of Heiberger and Holland (2004). data(usair) if.R(s={usair <- usair}, r={}) splom(~usair, main="U.S. Air Pollution Data with SO2 response", cex=.5) ## export.eps(hh("regb/figure/regb.f1.usair.eps")) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair[1:3,] ## lnSO2 is in position 8, SO2 is in position 1 ## lnmfg is in position 9, lnpopn is in position 10 splom(~usair[, c(8,2,9,10,5:7)], main="U.S. Air Pollution Data with 3 log-transformed variables", cex=.5) ## export.eps(hh("regb/figure/regb.f2.usair.eps")) if.R(s={ usair.step <- stepwise(y=usair$lnSO2, x=usair[, c(2,9,10,5:7)], method="exhaustive", plot=FALSE, nbest=2) ## print for pedagogical purposes only. The plot of cp ~ p is more useful. ## The line with rss=1e35 is a stepwise() bug, that we reported to S-Plus. print(usair.step, digits=4) usair.cp <- cp.calc(usair.step, usair, "lnSO2") ## print for pedagogical purposes only. The plot of cp ~ p is more useful. usair.cp tmp <- (usair.cp$cp <= 10) usair.cp[tmp,] old.par <- par(mar=par()$mar+c(0,1,0,0)) tmp <- (usair.cp$cp <= 10) plot(cp ~ p, data=usair.cp[tmp,], ylim=c(0,10), type="n", cex=1.3) abline(b=1) text(x=usair.cp$p[tmp], y=usair.cp$cp[tmp], row.names(usair.cp)[tmp], cex=1.3) title(main="Cp plot for usair.dat, Cp<10") par(old.par) ## export.eps(hh("regb/figure/regb.f3.usair.eps")) },r={ usair.regsubset <- leaps::regsubsets(lnSO2~lnmfg+lnpopn+precip+raindays+temp+wind, data=usair, nbest=2) usair.subsets.Summary <- summaryHH(usair.regsubset) tmp <- (usair.subsets.Summary$cp <= 10) usair.subsets.Summary[tmp,] plot(usair.subsets.Summary[tmp,], statistic='cp', legend=FALSE) usair.lm7 <- lm.regsubsets(usair.regsubset, 7) anova(usair.lm7) summary(usair.lm7) }) vif(lnSO2 ~ temp + lnmfg + lnpopn + wind + precip + raindays, data=usair) vif(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) anova(usair.lm) summary(usair.lm, corr=FALSE)
## This example is from Section 9.15 of Heiberger and Holland (2004). data(usair) if.R(s={usair <- usair}, r={}) splom(~usair, main="U.S. Air Pollution Data with SO2 response", cex=.5) ## export.eps(hh("regb/figure/regb.f1.usair.eps")) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair[1:3,] ## lnSO2 is in position 8, SO2 is in position 1 ## lnmfg is in position 9, lnpopn is in position 10 splom(~usair[, c(8,2,9,10,5:7)], main="U.S. Air Pollution Data with 3 log-transformed variables", cex=.5) ## export.eps(hh("regb/figure/regb.f2.usair.eps")) if.R(s={ usair.step <- stepwise(y=usair$lnSO2, x=usair[, c(2,9,10,5:7)], method="exhaustive", plot=FALSE, nbest=2) ## print for pedagogical purposes only. The plot of cp ~ p is more useful. ## The line with rss=1e35 is a stepwise() bug, that we reported to S-Plus. print(usair.step, digits=4) usair.cp <- cp.calc(usair.step, usair, "lnSO2") ## print for pedagogical purposes only. The plot of cp ~ p is more useful. usair.cp tmp <- (usair.cp$cp <= 10) usair.cp[tmp,] old.par <- par(mar=par()$mar+c(0,1,0,0)) tmp <- (usair.cp$cp <= 10) plot(cp ~ p, data=usair.cp[tmp,], ylim=c(0,10), type="n", cex=1.3) abline(b=1) text(x=usair.cp$p[tmp], y=usair.cp$cp[tmp], row.names(usair.cp)[tmp], cex=1.3) title(main="Cp plot for usair.dat, Cp<10") par(old.par) ## export.eps(hh("regb/figure/regb.f3.usair.eps")) },r={ usair.regsubset <- leaps::regsubsets(lnSO2~lnmfg+lnpopn+precip+raindays+temp+wind, data=usair, nbest=2) usair.subsets.Summary <- summaryHH(usair.regsubset) tmp <- (usair.subsets.Summary$cp <= 10) usair.subsets.Summary[tmp,] plot(usair.subsets.Summary[tmp,], statistic='cp', legend=FALSE) usair.lm7 <- lm.regsubsets(usair.regsubset, 7) anova(usair.lm7) summary(usair.lm7) }) vif(lnSO2 ~ temp + lnmfg + lnpopn + wind + precip + raindays, data=usair) vif(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) anova(usair.lm) summary(usair.lm, corr=FALSE)
Generate a sequence of length
points spanning the
current.panel.limits()$xlim
of a lattice window.
cplx(length)
cplx(length)
length |
Integer number of points. |
One-column matrix containing length
rows.
The first value is the x-value at the left side of the window. The
last value is the x-value at the right side of the window.
The in between points are evenly spaced.
Richard M. Heiberger <[email protected]>
cplx(11)
cplx(11)
Most of the datasets are described in the book Statistical Analysis and Data Display.
For ProfChal
, see plot.likert
.
AudiencePercent
is from personal communication by the market
researcher who did the study.
SFF8121
is student evaluations of my class compared to the
average of all graduate classes in the Spring 2010 semester.
Personal communication from the Temple University
Office of the Provost to me.
ProfDiv
is "Profit-and-Dividend Status of 348 Corportations in
the United States for the period from 1929 to 1935" from
Brinton WC (1939),
Graphic Presentation.
Brinton Associates.
http://www.archive.org/details/graphicpresentat00brinrich.
NZScienceTeaching
is from
New Zealand Ministry of Research Science and Technology(2006),
“Staying in Science."
This URL is no longer valid.
http://www.morst.govt.nz/Documents/publications/researchreports/Staying-in-Science-summary.pdf
.
PoorChildren
is from
“Poor Children, Working Parents",
Analysis of data from the CensusBureau's American Community Survey.
Comparison of Census areas of 100,000 or more people,
based on samples from 2005 to 2009.
Source: Data from the U.S. Census Bureau's American Community Survey; analysis by Andrew A. Beveridge, QueensCollege. Copyright 2011 The New York Times Company
https://archive.nytimes.com/www.nytimes.com/imagepages/2011/12/03/opinion/03blow-ch.html?ref=opinion
https://www.nytimes.com/2011/12/03/opinion/blow-newts-war-on-poor-children.html?_r=1
Naomi Robbins and I discuss the PoorChildren example in the Forbes online column:
https://www.forbes.com/sites/naomirobbins/2011/12/20/alternative-to-charles-blows-figure-in-newts-war-on-poor-children-2/
demo(PoorChildren, package="HH")
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Intermediate f and chisq functions to simplify writing for both R and S-Plus.
dchisq.intermediate(x, df, ncp=0, log=FALSE) pchisq.intermediate(q, df, ncp=0, lower.tail=TRUE, log.p=FALSE) qchisq.intermediate(p, df, ncp=0, lower.tail=TRUE, log.p=FALSE) df.intermediate(x, df1, df2, ncp=0, log=FALSE) pf.intermediate(q, df1, df2, ncp=0, lower.tail=TRUE, log.p=FALSE) qf.intermediate(p, df1, df2, ncp=0, lower.tail=TRUE, log.p=FALSE)
dchisq.intermediate(x, df, ncp=0, log=FALSE) pchisq.intermediate(q, df, ncp=0, lower.tail=TRUE, log.p=FALSE) qchisq.intermediate(p, df, ncp=0, lower.tail=TRUE, log.p=FALSE) df.intermediate(x, df1, df2, ncp=0, log=FALSE) pf.intermediate(q, df1, df2, ncp=0, lower.tail=TRUE, log.p=FALSE) qf.intermediate(p, df1, df2, ncp=0, lower.tail=TRUE, log.p=FALSE)
x , p , q , df , df1 , df2 , ncp , log , log.p , lower.tail
|
See
|
Richard M. Heiberger <[email protected]>
Returns the argument for the diagonal of NA and NULL arguments.
For all other arguments, it calls the regular diag
function.
diag.maybe.null(x, ...)
diag.maybe.null(x, ...)
x |
matrix, vector, NA, |
... |
Other arguments to |
Richard M. Heiberger ([email protected])
diag
.
diag.maybe.null(NULL) diag.maybe.null(NA) diag.maybe.null(1:5)
diag.maybe.null(NULL) diag.maybe.null(NA) diag.maybe.null(1:5)
Transpose of ECDF (Empirical CDF) for centered fitted values and residuals from a linear model.
diagplot5new(linearmodel, ..., pch = 19)
diagplot5new(linearmodel, ..., pch = 19)
linearmodel |
|
pch , ...
|
Arguments to |
This is an implementation in xyplot
of the "r-f spread" plot.
"trellis"
object.
Richard M. Heiberger <[email protected]>
William Cleveland (1993), Visualizing Data, Hobart Press.
## See ?residVSfitted ## Not run: data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) diagplot5new(fat.lm) ## End(Not run)
## See ?residVSfitted ## Not run: data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) diagplot5new(fat.lm) ## End(Not run)
QQ plot of regression residuals. The panel.qqmathline
is displayed.
diagQQ(lm.object, ...)
diagQQ(lm.object, ...)
lm.object |
|
... |
Additional arguments to |
"trellis"
object.
Richard M. Heiberger <[email protected]>
## See ?residVSfitted ## Not run: data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) diagQQ(fat.lm) ## End(Not run)
## See ?residVSfitted ## Not run: data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) diagQQ(fat.lm) ## End(Not run)
Discrete with four levels color dataset. These colors look like four distinct colors when run through the vischeck simulator to see how they look for the three most common color vision deficiencies: Deuteranope, Protanope, Tritanope.
data("Discrete4")
data("Discrete4")
The format is: chr [1:4] "#E31A1C" "#1F78B4" "#FB9A99" "#A6CEE3"
4x1 color scheme
data(Discrete4) ## Not run: library(RColorBrewer) library(lattice) Discrete4 <- brewer.pal(n=12, "Paired")[c(6,2,5,1)] Discrete4 ## save(Discrete4, file="Discrete4.rda") ## data(Discrete4, package="HH") ## barchart(~ 1:4, col=Discrete4, lwd=0, origin=0, horizontal=FALSE, xlab="Colors", scales=list(x=list(labels=Discrete4), y=list(labels=NULL)), main=paste("These colors look like four distinct colors when run through", "the vischeck simulator to see how they look for the three most", "common color vision deficiencies: Deuteranope, Protanope, Tritanope.", sep="\n")) ## End(Not run)
data(Discrete4) ## Not run: library(RColorBrewer) library(lattice) Discrete4 <- brewer.pal(n=12, "Paired")[c(6,2,5,1)] Discrete4 ## save(Discrete4, file="Discrete4.rda") ## data(Discrete4, package="HH") ## barchart(~ 1:4, col=Discrete4, lwd=0, origin=0, horizontal=FALSE, xlab="Colors", scales=list(x=list(labels=Discrete4), y=list(labels=NULL)), main=paste("These colors look like four distinct colors when run through", "the vischeck simulator to see how they look for the three most", "common color vision deficiencies: Deuteranope, Protanope, Tritanope.", sep="\n")) ## End(Not run)
Interprets a model formula in the context of its data.frame.
do.formula.trellis.xysplom(formula, data, na.action = na.pass)
do.formula.trellis.xysplom(formula, data, na.action = na.pass)
formula |
model formula |
data |
data.frame |
na.action |
see |
A list containing three data.frames and three formula, one for each.
x |
|
y |
|
g |
|
x.formula |
|
y.formula |
|
g.formula |
|
Richard M. Heiberger <[email protected]>
tmp <- data.frame(y=1, x=2, z=3, g=4) do.formula.trellis.xysplom( y ~ x + z | g, data=tmp)
tmp <- data.frame(y=1, x=2, z=3, g=4) do.formula.trellis.xysplom( y ~ x + z | g, data=tmp)
Helper function for likertWeighted()
used for vertical spacing and
horizontal borders of grouped panels. Horizontal rules between panels
are suppressed by default by likertWeighted
unless y.between
is
non-zero.
See examples.
EmphasizeVerticalPanels(x, y.between)
EmphasizeVerticalPanels(x, y.between)
x |
|
y.between |
The |
Revised trellis
object.
Richard M. Heiberger <[email protected]>
tmp1 <- array(1:60, c(5, 4, 3), list(letters[1:5],letters[6:9],letters[10:12])) tmp2 <- toCQxR(tmp1) colnames(tmp2) likertWeighted(~ . | group + row, tmp2) likertWeighted(~ . | group + row, tmp2, h.resize.panels=1:5, between=list(y=c(0,0,3,0)), h.resizePanels=1:5, ylab=c("Bottom","Top"), xlab.top=c("First","Second","Third"), auto.key.title="Response Level", main="Three Questions by Five Levels of Classification") likertObject <- likertWeighted(~ . | group + row, tmp2) likertObject EmphasizeVerticalPanels(likertObject, y.between=c(0,0,1,0))
tmp1 <- array(1:60, c(5, 4, 3), list(letters[1:5],letters[6:9],letters[10:12])) tmp2 <- toCQxR(tmp1) colnames(tmp2) likertWeighted(~ . | group + row, tmp2) likertWeighted(~ . | group + row, tmp2, h.resize.panels=1:5, between=list(y=c(0,0,3,0)), h.resizePanels=1:5, ylab=c("Bottom","Top"), xlab.top=c("First","Second","Third"), auto.key.title="Response Level", main="Three Questions by Five Levels of Classification") likertObject <- likertWeighted(~ . | group + row, tmp2) likertObject EmphasizeVerticalPanels(likertObject, y.between=c(0,0,1,0))
Remove main title, left axis tick labels, left strip, bottom legend from
plot and keep the vertical spacing allocated to those items. This
function is used to prepare a trellis object to be placed next to
another trellis object. The current object will have much of its
annotation
removed with the intent of sharing annotation with the other object.
This is motivated by the ProfChal
example in plot.likert
.
emptyMainLeftAxisLeftStripBottomLegend(x)
emptyMainLeftAxisLeftStripBottomLegend(x)
x |
A |
We manipulate the items inside the trellis object.
A "trellis"
object with the stated items replaced by non-printing
values. The vertical spacing of the original object is retained.
Richard M. Heiberger <[email protected]>
The manipulations are similar to those in the
c.trellis
and related functions in the
latticeExtra
package.
## This is a small example. ## See ?plot.likert for the complete example including motivation. ## require(grid) require(lattice) require(latticeExtra) require(HH) data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question ProfChal.list <- split.data.frame(tmp, ProfChal$Subtable) Empl <- ProfChal.list[[2]] pct <- likert(Empl, as.percent="noRightAxis", xlab="Percent") pct count <- likert(Empl, rightAxis=TRUE, xlab="Count", ylab.right="Row Count Totals", scales=list(x=list(at=c(0, 100, 200)))) count countEmptied <- HH:::emptyMainLeftAxisLeftStripBottomLegend(count) countEmptied tmp <- update(resizePanels(c(pct, countEmptied, y.same=TRUE, layout=c(2,1)), w=c(.8, .2)), scales=list(y=list(alternating=3, limits=count$y.limits), x=list(at=list(pct$x.scales$at, count$x.scales$at), labels=list(pct$x.scales$labels, count$x.scales$labels))), xlab=c(" ", pct$xlab, " ", count$xlab), between=list(x=1)) tmp
## This is a small example. ## See ?plot.likert for the complete example including motivation. ## require(grid) require(lattice) require(latticeExtra) require(HH) data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question ProfChal.list <- split.data.frame(tmp, ProfChal$Subtable) Empl <- ProfChal.list[[2]] pct <- likert(Empl, as.percent="noRightAxis", xlab="Percent") pct count <- likert(Empl, rightAxis=TRUE, xlab="Count", ylab.right="Row Count Totals", scales=list(x=list(at=c(0, 100, 200)))) count countEmptied <- HH:::emptyMainLeftAxisLeftStripBottomLegend(count) countEmptied tmp <- update(resizePanels(c(pct, countEmptied, y.same=TRUE, layout=c(2,1)), w=c(.8, .2)), scales=list(y=list(alternating=3, limits=count$y.limits), x=list(at=list(pct$x.scales$at, count$x.scales$at), labels=list(pct$x.scales$labels, count$x.scales$labels))), xlab=c(" ", pct$xlab, " ", count$xlab), between=list(x=1)) tmp
Exports a graph from the current device in R,
or the graphsheet
in S-Plus, to an EPS
file.
export.eps(FileName.in, Name.in="GSD2", ...)
export.eps(FileName.in, Name.in="GSD2", ...)
FileName.in |
name of file to be created. |
Name.in |
Name of graphsheet in S-Plus, ignored in R. |
... |
other arguments in R, ignored in S-Plus. |
Richard M. Heiberger <[email protected]>
dev2
.
## Not run: if (interactive()) { trellis.device() plot(1:10) export.eps("abcd.eps") } ## End(Not run)
## Not run: if (interactive()) { trellis.device() plot(1:10) export.eps("abcd.eps") } ## End(Not run)
Miscellaneous functions that I wish were in or consistent between S-Plus and R.
as.rts(x, ...) title.trellis(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, line = NA, outer = FALSE, axes=NULL, ...) title.grob(main=NULL, y=.99, gp=gpar(cex=1.5)) ## S3 method for class 'arima.model' as.character(x, ...) arima.model(x) coefArimaHH(object, ...) .arima.info.names.not.ordered (model)
as.rts(x, ...) title.trellis(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, line = NA, outer = FALSE, axes=NULL, ...) title.grob(main=NULL, y=.99, gp=gpar(cex=1.5)) ## S3 method for class 'arima.model' as.character(x, ...) arima.model(x) coefArimaHH(object, ...) .arima.info.names.not.ordered (model)
x |
vector or time series |
... |
Additional arguments. |
main , sub , xlab , ylab , line , outer , axes
|
See |
model |
A time series model specification in the S-Plus notation. |
object |
|
y , gp
|
See |
The result object of arima.model
has class "arima.model"
Richard M. Heiberger ([email protected])
Plot a chisquare or a F-curve. Shade a region for
rejection region or do-not-reject region. F.observed
and
chisq.observed
plots a vertical line with arrowhead markers at
the location of the observed xbar and outlines the area corresponding
to the -value.
F.setup(df1=1, df2=Inf, ncp=0, log.p=FALSE, xlim.in=c(0, 5), ylim.in=range(c(0, 1.1*df.intermediate(x=seq(.5,1.5,.01), df1=df1, df2=df2, ncp=ncp, log=log.p))), main.in=main.calc, ylab.in="F density", ...) F.curve(df1=1, df2=Inf, ncp=0, log.p=FALSE, alpha=.05, critical.values=f.alpha, f=seq(0, par()$usr[2], length=109), shade="right", col=par("col"), axis.name="f", ...) F.observed(f.obs, col="green", df1=1, df2=Inf, ncp=0, log.p=FALSE, axis.name="f", shade="right", shaded.area=0, display.obs=TRUE) chisq.setup(df=1, ncp=0, log.p=FALSE, xlim.in=c(0, qchisq.intermediate(p=1-.01, df=df, ncp=ncp, log.p=log.p)), ylim.in=range(c(0, 1.1*dchisq.intermediate(x=seq(max(0.5,df-2),df+2,.01), df=df, ncp=ncp, log=log.p))), main.in=main.calc, ylab.in="Chisq density", ...) chisq.curve(df=1, ncp=0, log.p=FALSE, alpha=.05, critical.values=chisq.alpha, chisq=seq(0, par()$usr[2], length=109), shade="right", col=par("col"), axis.name="chisq", ...) chisq.observed(chisq.obs, col="green", df=1, ncp=0, log.p=FALSE, axis.name="chisq", shade="right", shaded.area=0, display.obs=TRUE)
F.setup(df1=1, df2=Inf, ncp=0, log.p=FALSE, xlim.in=c(0, 5), ylim.in=range(c(0, 1.1*df.intermediate(x=seq(.5,1.5,.01), df1=df1, df2=df2, ncp=ncp, log=log.p))), main.in=main.calc, ylab.in="F density", ...) F.curve(df1=1, df2=Inf, ncp=0, log.p=FALSE, alpha=.05, critical.values=f.alpha, f=seq(0, par()$usr[2], length=109), shade="right", col=par("col"), axis.name="f", ...) F.observed(f.obs, col="green", df1=1, df2=Inf, ncp=0, log.p=FALSE, axis.name="f", shade="right", shaded.area=0, display.obs=TRUE) chisq.setup(df=1, ncp=0, log.p=FALSE, xlim.in=c(0, qchisq.intermediate(p=1-.01, df=df, ncp=ncp, log.p=log.p)), ylim.in=range(c(0, 1.1*dchisq.intermediate(x=seq(max(0.5,df-2),df+2,.01), df=df, ncp=ncp, log=log.p))), main.in=main.calc, ylab.in="Chisq density", ...) chisq.curve(df=1, ncp=0, log.p=FALSE, alpha=.05, critical.values=chisq.alpha, chisq=seq(0, par()$usr[2], length=109), shade="right", col=par("col"), axis.name="chisq", ...) chisq.observed(chisq.obs, col="green", df=1, ncp=0, log.p=FALSE, axis.name="chisq", shade="right", shaded.area=0, display.obs=TRUE)
xlim.in , ylim.in
|
Initial settings for |
df , df1 , df2 , ncp , log.p
|
Degrees of freedom,
non-centrality parameter, probabilities are given as log(p).
See |
alpha |
Probability of a Type I error. |
critical.values |
Critical values. Initial values correspond
to the specified |
main.in , ylab.in
|
Main title, default ylab. |
shade |
Valid values for shade are "right", "left", "inside", "outside", "none". Default is "right" for one-sided critical.values and "outside" for two-sided critical values. |
col |
color of the shaded region and the area of the shaded region. |
shaded.area |
Numerical value of the area. This value may
be cumulated over two calls to the function (one call for left, one
call for right).
The |
display.obs |
Logical. If |
f , chisq
|
Values used to draw curve. Replace them if more resolution is needed. |
f.obs , chisq.obs
|
Observed values of statistic. |
axis.name |
Axis name. |
... |
Other arguments which are ignored. |
Richard M. Heiberger <[email protected]>
old.omd <- par(omd=c(.05,.88, .05,1)) chisq.setup(df=12) chisq.curve(df=12, col='blue') chisq.observed(22, df=12) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) chisq.setup(df=12) chisq.curve(df=12, col='blue', alpha=c(.05, .05)) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) F.setup(df1=5, df2=30) F.curve(df1=5, df2=30, col='blue') F.observed(3, df1=5, df2=30) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) F.setup(df1=5, df2=30) F.curve(df1=5, df2=30, col='blue', alpha=c(.05, .05)) par(old.omd)
old.omd <- par(omd=c(.05,.88, .05,1)) chisq.setup(df=12) chisq.curve(df=12, col='blue') chisq.observed(22, df=12) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) chisq.setup(df=12) chisq.curve(df=12, col='blue', alpha=c(.05, .05)) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) F.setup(df1=5, df2=30) F.curve(df1=5, df2=30, col='blue') F.observed(3, df1=5, df2=30) par(old.omd) old.omd <- par(omd=c(.05,.88, .05,1)) F.setup(df1=5, df2=30) F.curve(df1=5, df2=30, col='blue', alpha=c(.05, .05)) par(old.omd)
For some ANOVA models with two or more factors, we need to average over interaction terms. These functions use an older version of glht.mcp and mcp2matrix to do that averaging.
glhtWithMCP.993(model, linfct, ...) mcp2matrix.993(model, linfct)
glhtWithMCP.993(model, linfct, ...) mcp2matrix.993(model, linfct)
model , linfct , ...
|
See |
mcp2matrix
is taken from from multcomp_0.993-2.tar.gz/R/mcp.R
.
glhtWithMCP.993
is based on glht.mcp
in
multcomp_1.0-0/R/glht.R
with the call to mcp2matrix
replaced by a call to mcp2matrix.993
.
See glht
Richard M. Heiberger <[email protected]>
Calculate Box–Ljung Goodness of Fit for ARIMA models in S-Plus.
In R we use the Box.test
function.
gof.calculation(acf.list, gof.lag, n, n.parms)
gof.calculation(acf.list, gof.lag, n, n.parms)
acf.list |
An |
gof.lag |
The number of model parameters is the number of lags to use for computing the Portmanteau goodness of fit statistic |
n |
Number of residuals in model. |
n.parms |
Number of AR and MA parameters in the model. |
This function is isolated from the S-Plus arima.diag
function.
It is used only in S-Plus.
See the gof
value described in
arima.diag
in S-Plus.
Richard M. Heiberger ([email protected])
arima.diag
in S-Plus.
if.R(s={ co2.arima <- arima.mle(co2, list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) co2.acf <- acf(resid(co2.arima), plot=FALSE, lag=40) co2.gof <- gof.calculation(co2.acf, 36, length(co2), 2) xyplot(p.value ~ lag, data=co2.gof, panel=panel.gof, ylim=range(0, co2.gof$p.value)) },r={})
if.R(s={ co2.arima <- arima.mle(co2, list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) co2.acf <- acf(resid(co2.arima), plot=FALSE, lag=40) co2.gof <- gof.calculation(co2.acf, 36, length(co2), 2) xyplot(p.value ~ lag, data=co2.gof, panel=panel.gof, ylim=range(0, co2.gof$p.value)) },r={})
uses modified older version of grid functions. Includes optional specification of the axis labels.
grid.yaxis.hh(at = NULL, label = TRUE, main = TRUE, gp = gpar(), draw = TRUE, vp = NULL, labels) make.yaxis.hh.labels(at, main, labels = at) grid.xaxis.hh(at = NULL, label = TRUE, main = TRUE, gp = gpar(), draw = TRUE, vp = NULL, labels) make.xaxis.hh.labels(at, main, labels = at)
grid.yaxis.hh(at = NULL, label = TRUE, main = TRUE, gp = gpar(), draw = TRUE, vp = NULL, labels) make.yaxis.hh.labels(at, main, labels = at) grid.xaxis.hh(at = NULL, label = TRUE, main = TRUE, gp = gpar(), draw = TRUE, vp = NULL, labels) make.xaxis.hh.labels(at, main, labels = at)
at , label , main , gp , draw , vp
|
See |
labels |
label values if you don't want the defaults |
See link[grid]{grid.xaxis}
.
Richard M. Heiberger <[email protected]>
link[grid]{grid.xaxis}
Remove selected GraphSheetPages in the S-Plus Windows GUI Graphsheet. This does the same task as right-click/delete on the tabs of the GraphSheet.
GSremove(pages, sheet = "GSD2$Page")
GSremove(pages, sheet = "GSD2$Page")
pages |
Page numbers in the tabs at the bottom of the Graphsheet. |
sheet |
Defaults to |
Richard M. Heiberger <[email protected]>
graphsheet
in S-Plus.
## Not run: trellis.device() plot(1:10); plot(11:20); plot(21:30) GSremove(c(1,3)) ## End(Not run)
## Not run: trellis.device() plot(1:10); plot(11:20); plot(21:30) GSremove(c(1,3)) ## End(Not run)
Print a tabular display of the results of Best Subsets Regression.
This is an alternate display for the object from the regsubsets
function. This function is based on regsubsets
.
The functions described here are designed for the HH package in R and
use the leaps package in R.
The leaps package is not in S-Plus, hence these functions
do not work in the HH package for S-Plus.
`summaryHH`(object, ...) ## S3 method for class 'regsubsets' summaryHH(object, names = abbreviate(dimnames(incidence)[[2]], minlength = abbrev), abbrev = 1, min.size = 1, max.size = dim(sumry$which)[2], statistic = c("bic", "cp", "adjr2", "rsq", "rss", "stderr"), las = par("las"), cex.subsets = 1, ..., main=statistic) ## S3 method for class 'summaryHH.regsubsets' plot(x, ..., statistic="adjr2", legend=FALSE, col="darkgray", cex=1, pch=16, col.text="black", cex.text=1, col.abline="darkgray")
`summaryHH`(object, ...) ## S3 method for class 'regsubsets' summaryHH(object, names = abbreviate(dimnames(incidence)[[2]], minlength = abbrev), abbrev = 1, min.size = 1, max.size = dim(sumry$which)[2], statistic = c("bic", "cp", "adjr2", "rsq", "rss", "stderr"), las = par("las"), cex.subsets = 1, ..., main=statistic) ## S3 method for class 'summaryHH.regsubsets' plot(x, ..., statistic="adjr2", legend=FALSE, col="darkgray", cex=1, pch=16, col.text="black", cex.text=1, col.abline="darkgray")
object |
An object of class |
x |
An object of class |
statistic |
Name of statistic to be plotted for each model. |
... |
Other arguments to be passed down to
|
names |
Abbreviations of variable names. |
abbrev |
minimum number of letters in each abbreviation. |
min.size |
minimum size subset to plot; default is 1. |
max.size |
maximum size subset to plot; default is number of predictors. |
legend |
logical variable, |
las |
Orientation for model names on graph. |
cex.subsets |
can be used to change the relative size of the characters used to
plot the regression subsets; default is |
main |
|
col , cex , pch
|
|
col.text , cex.text
|
|
col.abline |
|
summaryHH
produces a table of models, with
p, rsq, rss, adjr2, cp, bic, stderr
for each.
plot.summaryHH.regsubsets
plots the specified statistic
from the summary.
All the others are support functions.
Richard M. Heiberger <[email protected]>
R tools for writing HH2: hhpdf, hhdev.off, hhcapture, hhcode, hhpng, hhlatex.
These functions in the HH package are placeholders used by
the scripts
files. See details.
hhpdf(file, ...) hhdev.off(...) hhcapture(file, text, echo=TRUE, print.eval=TRUE) hhcode(file, text) hhpng(file, ...) hhlatex(file="", ...)
hhpdf(file, ...) hhdev.off(...) hhcapture(file, text, echo=TRUE, print.eval=TRUE) hhcode(file, text) hhpng(file, ...) hhlatex(file="", ...)
file |
Output file name. Ignored. |
text |
Multi-line character string. It will be
displayed on the console by |
... |
Ignored. |
echo , print.eval
|
See |
The files in HHscriptnames
()
contain R code for all examples and figures in the book.
The examples can all be directly executed by the user.
The code examples all use these functions.
The versions of these functions here are essentially placeholders.
Functions hhpdf
, hhpng
, and hhdev.off
are no-ops and return NULL
.
As a consequence, the code between them will execute and display on
the default graphics device.
Function hhcapture
sources its text argument and prints the
output to the console.
Function hhcode
prints its text argument to the console.
Function hhlatex
prints the latex source to the
console and returns NULL
.
While writing the book, these placeholder functions are replaced by more elaborate functions with the same names that write the graphs onto pdf or png files, the console output to text files, and the latex code to a file.
Richard M. Heiberger <[email protected]>
Find absolute pathname of a script file for the HH book in the HH package.
HHscriptnames(chapternumbers=NULL, edition=2) WindowsPath(x, display=TRUE)
HHscriptnames(chapternumbers=NULL, edition=2) WindowsPath(x, display=TRUE)
chapternumbers |
A number or letter name for a chapter in the HH
book. For the Second edition, the valid values are from the set
|
edition |
Either 2 or 1, for the second or first edition of the book Statistical Analysis and Data Display. |
x |
A vector or matrix of pathnames as generated by R, with |
display |
Logical. With the default |
For HHscriptnames
, matrix of full pathnames to script files in the HH
package.
For WindowsPath
, a vector or matrix of full pathnames with all "/"
characters
changed to "\\"
(which displays as \
by the
cat
function). When display
is TRUE
the
function also prints at the console the pathnames with a single
\
character suitable for copy and paste into a Windows program.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
## Not run: ## All Operating Systems ## Second Edition HHscriptnames() HHscriptnames(6) HHscriptnames("6") HHscriptnames("oway") HHscriptnames("H") HHscriptnames("RApx") HHscriptnames(c(1:18, LETTERS[1:15])) ## with Windows pathname separators WindowsPath(HHscriptnames()) WindowsPath(HHscriptnames(6)) WindowsPath(HHscriptnames(6), display=FALSE) WindowsPath(HHscriptnames(6:8)) WindowsPath(HHscriptnames(6:8), display=FALSE) ## First Edition HHscriptnames(6, edition=1) ## End(Not run)
## Not run: ## All Operating Systems ## Second Edition HHscriptnames() HHscriptnames(6) HHscriptnames("6") HHscriptnames("oway") HHscriptnames("H") HHscriptnames("RApx") HHscriptnames(c(1:18, LETTERS[1:15])) ## with Windows pathname separators WindowsPath(HHscriptnames()) WindowsPath(HHscriptnames(6)) WindowsPath(HHscriptnames(6), display=FALSE) WindowsPath(HHscriptnames(6:8)) WindowsPath(HHscriptnames(6:8), display=FALSE) ## First Edition HHscriptnames(6, edition=1) ## End(Not run)
Oneway analysis of variance makes the assumption that the variances of
the groups are equal.
Brown and Forsyth, 1974 present the recommended test of this assumption.
The Brown and Forsyth test statistic is the statistic resulting
from an ordinary one-way analysis of variance on the
absolute deviations from the median.
hov(x, data=NULL, method = "bf") ## x is a formula ## users will normally use the formula above and will not call the ## method directly. hov.bf(x, group, ## x is the response variable y.name = deparse(substitute(x)), group.name = deparse(substitute(group)))
hov(x, data=NULL, method = "bf") ## x is a formula ## users will normally use the formula above and will not call the ## method directly. hov.bf(x, group, ## x is the response variable y.name = deparse(substitute(x)), group.name = deparse(substitute(group)))
x |
Formula appropriate for oneway anova in |
data |
data.frame |
method |
Character string defining method. At this time the only
recognized method is |
group |
factor. |
y.name |
name of response variable, defaults to variable name in formula. |
group.name |
name of factor, defaults to variable name in formula. |
"htest"
object for the hov test.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Brown, M.~B. and Forsyth, A.~B. (1974). Robust tests for equality of variances. Journal of the American Statistical Association, 69:364–367.
data(turkey) hov(wt.gain ~ diet, data=turkey) hovPlot(wt.gain ~ diet, data=turkey)
data(turkey) hov(wt.gain ~ diet, data=turkey) hovPlot(wt.gain ~ diet, data=turkey)
Homogeneity of Variance: Brown–Forsyth method
hovBF(x, data=NULL, ..., na.rm = TRUE) hovplotBF(x, data, ..., na.rm = TRUE, main = "Brown-Forsyth Homogeneity of Variance", plotmath = TRUE)
hovBF(x, data=NULL, ..., na.rm = TRUE) hovplotBF(x, data, ..., na.rm = TRUE, main = "Brown-Forsyth Homogeneity of Variance", plotmath = TRUE)
x |
Model formula with one response variable and one factor. |
data |
|
... |
Other arguments. |
na.rm |
A logical value indicating whether 'NA' values should be
stripped before the computation proceeds. See |
main |
|
plotmath |
Logical. When |
hovplotBF
returns a three-panel trellis
object.
hovBF
returns an htest
object.
Richard M. Heiberger <[email protected]>
Brown, M.~B. and Forsyth, A.~B. (1974). “Robust tests for equality of variances.” Journal of the American Statistical Association, 69:364–367.
data(batch) batch1.aov <- aov(Calcium ~ Batch, data=batch) anova(batch1.aov) hovBF(Calcium ~ Batch, data=batch) hovplotBF(Calcium ~ Batch, data=batch)
data(batch) batch1.aov <- aov(Calcium ~ Batch, data=batch) anova(batch1.aov) hovBF(Calcium ~ Batch, data=batch) hovplotBF(Calcium ~ Batch, data=batch)
if.R
uses the is.R
function to determine whether to
execute the expression in the r
argument or the expression
in the s
argument. is.R
, copied from the now defunct
base R function, returns TRUE
if running under R and returns
FALSE
otherwise (initially designed for S/S-PLUS).
if.R(r, s) is.R()
if.R(r, s) is.R()
r |
Any R expression, including a group of expressions nested in braces. Assignments made in this expression are available to the enclosing function. |
s |
Any S-Plus expression, including a group of expressions nested in braces. Assignments made in this expression are available to the enclosing function. |
Not all functions are in both implementations of the S language. In
particular, panel functions for lattice
in R (based on
grid
graphics) are very different from panel functions for
trellis
(based on the older graphics technology) in S-Plus.
is.R
is copied from the now defunct base R function of the same name.
For if.R
the result of the executed expression.
is.R
returns TRUE
if we are using R and FALSE
otherwise.
Richard M. Heiberger <[email protected]>
R.Version
if.R(r={"This is R."}, s={"This is S-Plus"}) is.R()
if.R(r={"This is R."}, s={"This is S-Plus"}) is.R()
0
value. A 2D argument x
with dim(x)==c(r,c)
is
first extended to 3D with dim(x)==c(1,r,c)
, and then the result is
collapsed back to 2D.
Expand a 3D array on the second dimension, inserting empty layers where
the input vector has a 0
value. A 2D argument x
with dim(x)==c(r,c)
is
first extended to 3D with dim(x)==c(1,r,c)
, and then the result is
collapsed back to 2D.
InsertVerticalPanels(x, expansion, newRowheights=5, newValue=NA)
InsertVerticalPanels(x, expansion, newRowheights=5, newValue=NA)
x |
Three-dimensional array, for example, one defined as a set of matrices
for the |
expansion |
Vector of |
newRowheights |
Value to be used for inserted row by |
newValue |
Value to be inserted in all positions of inserted layer. |
Array similarly structured to the input array x
, but with more
layers on the second dimension. The "rowheights"
attribute
gives the rowheights
used by EmphasizeVerticalPanels
. The
newRows
gives the row (second dimension) numbers in the result that are the
generated values. All data items in the newRows
will have
value in the newValue
argument.
Richard M. Heiberger <[email protected]>
EmphasizeVerticalPanels
x <- array(1:24, c(3, 4, 2), dimnames = list(letters[1:3], LETTERS[4:7], letters[8:9])) x expansion <- c(1, 1, 0, 1, 0, 1) result <- InsertVerticalPanels(x, expansion) result Pop.labels1 <- result[1,, ] Pop.labels1[ attr(result, "newRows"),] <- " " Pop.labels2 <- result[2,, ] Pop.labels2[ attr(result, "newRows"),] <- " " Pct.labels1 <- format(round(HH::rowPcts(result[1,, ]))) Pct.labels1[ attr(result, "newRows"),] <- " " Pct.labels2 <- format(round(HH::rowPcts(result[2,, ]))) Pct.labels2[ attr(result, "newRows"),] <- " "
x <- array(1:24, c(3, 4, 2), dimnames = list(letters[1:3], LETTERS[4:7], letters[8:9])) x expansion <- c(1, 1, 0, 1, 0, 1) result <- InsertVerticalPanels(x, expansion) result Pop.labels1 <- result[1,, ] Pop.labels1[ attr(result, "newRows"),] <- " " Pop.labels2 <- result[2,, ] Pop.labels2[ attr(result, "newRows"),] <- " " Pct.labels1 <- format(round(HH::rowPcts(result[1,, ]))) Pct.labels1[ attr(result, "newRows"),] <- " " Pct.labels2 <- format(round(HH::rowPcts(result[2,, ]))) Pct.labels2[ attr(result, "newRows"),] <- " "
This is intended to be a method for interaction
for positioned
factors. Since interaction
is not currently implemented as
a generic, interaction.positioned
is a standalone function.
The result is assigned a position
. The position for each interaction
level is the position of the corresponding a
factor plus a
scaled level of the b
factor. The default scale is .1.
interaction.positioned(..., ## exactly two factors drop = FALSE, sep = ".", b.offset=0, b.scale=.1)
interaction.positioned(..., ## exactly two factors drop = FALSE, sep = ".", b.offset=0, b.scale=.1)
... |
exactly two factors. The first
factor |
b.offset |
amount added to |
b.scale |
scale to relate units of |
drop , sep
|
See |
"positioned"
object containing the ordinary interaction with a
"position"
attribute.
Richard M. Heiberger <[email protected]>
a <- positioned(letters[c(1,2,3,1,2,3)], value=c(1,4,9)) b <- positioned(LETTERS[c(4,4,4,5,5,5)], value=c(1,2)) a.b <- interaction.positioned(a, b) a.b.2 <- interaction.positioned(a, b, b.scale=.2) b.a <- interaction.positioned(b, a)
a <- positioned(letters[c(1,2,3,1,2,3)], value=c(1,4,9)) b <- positioned(LETTERS[c(4,4,4,5,5,5)], value=c(1,2)) a.b <- interaction.positioned(a, b) a.b.2 <- interaction.positioned(a, b, b.scale=.2) b.a <- interaction.positioned(b, a)
The main diagonal
displays boxplots for the main effects of each factor. The
off-diagonals show the interaction plots for each pair of factors.
The i,j
panel shows the same factors as the j,i
but with
the trace- and x-factor roles interchanged.
interaction2wt(x, ...) ## S3 method for class 'formula' interaction2wt(x, data=NULL, responselab, ...) ## Default S3 method: interaction2wt(x, response.var, responselab = deparse(substitute(response.var)), responselab.expression = responselab, relation = list(x = "same", y = "same"), x.relation = relation$x, y.relation = relation$y, digits = 3, x.between=1, y.between=1, between, cex = 0.75, rot=c(0,0), panel.input = panel.interaction2wt, strip.input = if (label.as.interaction.formula) strip.default else strip.interaction2wt, par.strip.text.input = trellis.par.get()$add.text, scales.additional, main.in = paste(responselab, ": ", c("main", "simple")[1+simple], " effects and 2-way interactions", sep=""), xlab = "", ylab = "", simple=FALSE, box.ratio=if (simple) .32 else 1, label.as.interaction.formula=TRUE, ..., main.cex, key.cex.title=.8, key.cex.text=.7, factor.expressions=names.x, simple.pch=NULL, col.by.row=TRUE, col =trellis.par.get("superpose.line")$col, lty =trellis.par.get("superpose.line")$lty, lwd =trellis.par.get("superpose.line")$lwd, alpha=trellis.par.get("superpose.line")$alpha )
interaction2wt(x, ...) ## S3 method for class 'formula' interaction2wt(x, data=NULL, responselab, ...) ## Default S3 method: interaction2wt(x, response.var, responselab = deparse(substitute(response.var)), responselab.expression = responselab, relation = list(x = "same", y = "same"), x.relation = relation$x, y.relation = relation$y, digits = 3, x.between=1, y.between=1, between, cex = 0.75, rot=c(0,0), panel.input = panel.interaction2wt, strip.input = if (label.as.interaction.formula) strip.default else strip.interaction2wt, par.strip.text.input = trellis.par.get()$add.text, scales.additional, main.in = paste(responselab, ": ", c("main", "simple")[1+simple], " effects and 2-way interactions", sep=""), xlab = "", ylab = "", simple=FALSE, box.ratio=if (simple) .32 else 1, label.as.interaction.formula=TRUE, ..., main.cex, key.cex.title=.8, key.cex.text=.7, factor.expressions=names.x, simple.pch=NULL, col.by.row=TRUE, col =trellis.par.get("superpose.line")$col, lty =trellis.par.get("superpose.line")$lty, lwd =trellis.par.get("superpose.line")$lwd, alpha=trellis.par.get("superpose.line")$alpha )
Arguments when x
is a formula.
x |
The object on which method dispatch is carried out. For the For the |
data |
For the |
responselab |
Character name of response variable, defaults to
the name of the response variable in the |
responselab.expression |
|
... |
additional arguments, primarily trellis arguments. |
response.var |
For the |
simple |
logical. |
box.ratio |
Trellis/Lattice arguments. Default values are set by the
the formula
method. The user may override the defaults.
See also
xyplot
.
relation |
|
x.relation |
|
y.relation |
|
digits |
doesn't do anything at the moment |
x.between |
|
y.between |
|
between |
trellis/lattice |
cex |
S-Plus: changes the size of the median dot in the boxplots. R: doesn't do anything. |
panel.input |
panel function. Default is |
label.as.interaction.formula |
logical. If |
strip.input |
strip function. Default depends on the value of
|
par.strip.text.input |
|
scales.additional |
additional arguments to |
main.in |
Text of main title. |
xlab |
No effect. |
ylab |
No effect. |
main.cex |
|
key.cex.title |
|
key.cex.text |
|
factor.expressions |
Expressions for titles of keys and
|
rot |
Rotation of x tick labels and y tick labels. Only 0 and 90 will look good. |
simple.pch |
Named list containing plotting characters for each
level of one or more of the factors. |
col.by.row |
logical. If |
col , lty , lwd , alpha
|
Arguments to
|
"trellis"
object containing the plot.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(vulcan) interaction2wt(wear ~ filler + pretreat + raw, data=vulcan, par.strip.text=list(cex=.7)) interaction2wt(wear ~ filler + pretreat + raw, data=vulcan, par.strip.text=list(cex=.7), label.as.interaction.formula=FALSE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col.by.row=FALSE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, simple.scale=c(filler=.15, raw=.2), xlim=c(.3, 5.6)) interaction2wt(wear ~ filler + raw, data=vulcan, col=1:5, lwd=1:5, lty=1:5) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col=1:5, lwd=1:5, lty=1:5) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col=1:5, lwd=1:5, lty=1:5, col.by.row=FALSE, simple.pch=list(filler=LETTERS[1:5], raw=letters[6:9]), cex=2) ToothGrowth$dose <- positioned(ToothGrowth$dose) ## modify local copy anova(aov(len ~ supp*dose, data=ToothGrowth)) interaction2wt(len ~ supp + dose, data=ToothGrowth) esoph$ntotal <- with(esoph, ncases + ncontrols) ## modify local copy esoph$rate <- with(esoph, ncases/ntotal) ## modify local copy position(esoph$alcgp) <- 2:5 position(esoph$tobgp) <- 2:5 interaction2wt(rate ~ agegp + alcgp + tobgp, esoph, rot=c(90,0), par.strip.text=list(cex=.8)) interaction2wt(rate ~ agegp + alcgp + tobgp, esoph, rot=c(90,0), par.strip.text=list(cex=.8), factor.expressions=c( agegp=expression(Age~~(years)), alcgp=expression(Alcohol~ bgroup("(",scriptstyle(frac(gm, day)),")")), tobgp=expression(Tobacco~ bgroup("(",scriptstyle(frac(gm, day)),")"))), par.settings=list( par.xlab.text=list(cex=.8), par.ylab.text=list(cex=.8)), responselab.expression="Cancer\nRate", main=list( "Esophogeal Cancer Rate ~ Alcohol Consumption + Tobacco Consumption", cex=1.2)) esoph.aov <- aov(rate ~ agegp + alcgp + tobgp, data=esoph) anova(esoph.aov)
data(vulcan) interaction2wt(wear ~ filler + pretreat + raw, data=vulcan, par.strip.text=list(cex=.7)) interaction2wt(wear ~ filler + pretreat + raw, data=vulcan, par.strip.text=list(cex=.7), label.as.interaction.formula=FALSE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col.by.row=FALSE) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, simple.scale=c(filler=.15, raw=.2), xlim=c(.3, 5.6)) interaction2wt(wear ~ filler + raw, data=vulcan, col=1:5, lwd=1:5, lty=1:5) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col=1:5, lwd=1:5, lty=1:5) interaction2wt(wear ~ filler + raw, data=vulcan, simple=TRUE, col=1:5, lwd=1:5, lty=1:5, col.by.row=FALSE, simple.pch=list(filler=LETTERS[1:5], raw=letters[6:9]), cex=2) ToothGrowth$dose <- positioned(ToothGrowth$dose) ## modify local copy anova(aov(len ~ supp*dose, data=ToothGrowth)) interaction2wt(len ~ supp + dose, data=ToothGrowth) esoph$ntotal <- with(esoph, ncases + ncontrols) ## modify local copy esoph$rate <- with(esoph, ncases/ntotal) ## modify local copy position(esoph$alcgp) <- 2:5 position(esoph$tobgp) <- 2:5 interaction2wt(rate ~ agegp + alcgp + tobgp, esoph, rot=c(90,0), par.strip.text=list(cex=.8)) interaction2wt(rate ~ agegp + alcgp + tobgp, esoph, rot=c(90,0), par.strip.text=list(cex=.8), factor.expressions=c( agegp=expression(Age~~(years)), alcgp=expression(Alcohol~ bgroup("(",scriptstyle(frac(gm, day)),")")), tobgp=expression(Tobacco~ bgroup("(",scriptstyle(frac(gm, day)),")"))), par.settings=list( par.xlab.text=list(cex=.8), par.ylab.text=list(cex=.8)), responselab.expression="Cancer\nRate", main=list( "Esophogeal Cancer Rate ~ Alcohol Consumption + Tobacco Consumption", cex=1.2)) esoph.aov <- aov(rate ~ agegp + alcgp + tobgp, data=esoph) anova(esoph.aov)
Prediction and Confidence Intervals for glm
Objects
interval(glm.object, ...) ## S3 method for class 'glm' interval(glm.object, linkfit.object, type = c("link", "response"), conf.level = 0.95, ...)
interval(glm.object, ...) ## S3 method for class 'glm' interval(glm.object, linkfit.object, type = c("link", "response"), conf.level = 0.95, ...)
glm.object |
result from a call to the |
linkfit.object |
result from a call to the |
type |
Either |
conf.level |
Confidence level, for example |
... |
Other arguments to be passed to |
Matrix with five columns: fit, ci.low, ci.hi, pi.low,
pi.hi
and as many rows as predict.glm
returns.
Richard M. Heiberger <[email protected]>
data(spacshu) spacshu.bin.glm <- glm(damage ~ tempF, data=spacshu, family=binomial) ## observed data spacshu.interval <- interval(spacshu.bin.glm) ## new data, link spacshu.interval.link <- interval(spacshu.bin.glm, newdata=data.frame(tempF=30:85)) ## new data, response spacshu.interval.response <- interval(spacshu.bin.glm, newdata=data.frame(tempF=30:85), type="response")
data(spacshu) spacshu.bin.glm <- glm(damage ~ tempF, data=spacshu, family=binomial) ## observed data spacshu.interval <- interval(spacshu.bin.glm) ## new data, link spacshu.interval.link <- interval(spacshu.bin.glm, newdata=data.frame(tempF=30:85)) ## new data, response spacshu.interval.response <- interval(spacshu.bin.glm, newdata=data.frame(tempF=30:85), type="response")
Interaction plot, with an option to print standard error bars. There is an option to offset group lines to prevent the bars from overprinting.
intxplot(x, data=NULL, groups.in, scales, key.length=1, key.lines, key=TRUE, trace.factor.name=deparse(substitute(groups.in)), x.factor.name=x.factor, xlab=x.factor.name, main=list(main.title, cex=main.cex), condition.name="condition", panel="panel.intxplot", summary.function="sufficient", se, ..., data.is.summary=FALSE, main.title=paste( "Interactions of", trace.factor.name, "and", x.factor.name, if (length(x[[3]]) > 1) paste("|", condition.name.to.use)), main.cex=1.5, col, lwd, lty, alpha) panel.intxplot(x, y, subscripts, groups, type = "l", se, cv=1.96, offset.use=(!missing(groups) && !missing(se)), offset.scale=2*max(as.numeric(groups)), offset= as.numeric(groups[match(levels(groups), groups)]) / offset.scale, rug.use=offset.use, col, lwd, lty, alpha, ...)
intxplot(x, data=NULL, groups.in, scales, key.length=1, key.lines, key=TRUE, trace.factor.name=deparse(substitute(groups.in)), x.factor.name=x.factor, xlab=x.factor.name, main=list(main.title, cex=main.cex), condition.name="condition", panel="panel.intxplot", summary.function="sufficient", se, ..., data.is.summary=FALSE, main.title=paste( "Interactions of", trace.factor.name, "and", x.factor.name, if (length(x[[3]]) > 1) paste("|", condition.name.to.use)), main.cex=1.5, col, lwd, lty, alpha) panel.intxplot(x, y, subscripts, groups, type = "l", se, cv=1.96, offset.use=(!missing(groups) && !missing(se)), offset.scale=2*max(as.numeric(groups)), offset= as.numeric(groups[match(levels(groups), groups)]) / offset.scale, rug.use=offset.use, col, lwd, lty, alpha, ...)
x |
For |
data |
data.frame, as used in |
groups.in |
|
scales |
Optional, additional arguments for the standard |
key.length |
Number of columns in the key. |
key.lines |
default value for the |
key |
logical. If |
trace.factor.name |
Name of the grouping variable. |
x.factor.name |
name of the dependent variable. |
xlab |
as in |
main |
as in |
panel |
as in |
condition.name |
name of the conditioning variable. |
summary.function |
The default |
se |
standard errors to be passed to |
,
... |
In |
data.is.summary |
logical, defaults to |
main.title |
Default main title for plot. |
main.cex |
Default character expansion for main title. |
y , subscripts , groups , type
|
Standard arguments for panel functions. |
cv |
critical value for confidence intervals. Defaults to 1.96. |
offset.use |
logical. If |
offset.scale |
Scale number indicating how far apart the ends of the groups will be placed. Larger numbers make them closer together. |
offset |
Actual numbers by which the end of the groups are offset
from their nominal location which is the |
rug.use |
logical. If |
col , lwd , lty , alpha
|
Arguments to
|
"trellis"
object.
Richard M. Heiberger <[email protected]>
## This uses the same data as the HH Section 12.13 rhizobium example. data(rhiz.clover) ## interaction plot, no SE intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, main="Interaction Plot. No SE") ## interaction plot, individual SE for each treatment combination ## Rescaled to allow the CI bars to stay within the plot region intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=TRUE, ylim=c(17,47), main="Interaction Plot. Rescaled to keep CI bars within the plot region") ## Common SE based on ANOVA table. Rescaled to allow the CI bars to stay within the plot region intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=sqrt(sum((nobs-1)*sd^2)/(sum(nobs-1)))/sqrt(5), ylim=c(16,41), main=paste("Interaction Plot. Common SE based on ANOVA table.\n", "Rescaled to keep CI bars within the plot region")) ## change distance between endpoints intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=TRUE, offset.scale=10, ylim=c(18,46), main="Interaction plot. Change distance between endpoints") ## When data includes the nobs and sd variables, data.is.summary=TRUE is needed. intxplot(Npg ~ strain, groups=comb, se=sqrt(sum((nobs-1)*sd^2)/(sum(nobs-1)))/sqrt(5), data=sufficient(rhiz.clover, y="Npg", c("strain","comb")), data.is.summary=TRUE, ylim=c(16,41), main=paste("Interaction plot. When data includes the nobs and sd variables,\n", "'data.is.summary=TRUE' is needed"))
## This uses the same data as the HH Section 12.13 rhizobium example. data(rhiz.clover) ## interaction plot, no SE intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, main="Interaction Plot. No SE") ## interaction plot, individual SE for each treatment combination ## Rescaled to allow the CI bars to stay within the plot region intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=TRUE, ylim=c(17,47), main="Interaction Plot. Rescaled to keep CI bars within the plot region") ## Common SE based on ANOVA table. Rescaled to allow the CI bars to stay within the plot region intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=sqrt(sum((nobs-1)*sd^2)/(sum(nobs-1)))/sqrt(5), ylim=c(16,41), main=paste("Interaction Plot. Common SE based on ANOVA table.\n", "Rescaled to keep CI bars within the plot region")) ## change distance between endpoints intxplot(Npg ~ strain, groups=comb, data=rhiz.clover, se=TRUE, offset.scale=10, ylim=c(18,46), main="Interaction plot. Change distance between endpoints") ## When data includes the nobs and sd variables, data.is.summary=TRUE is needed. intxplot(Npg ~ strain, groups=comb, se=sqrt(sum((nobs-1)*sd^2)/(sum(nobs-1)))/sqrt(5), data=sufficient(rhiz.clover, y="Npg", c("strain","comb")), data.is.summary=TRUE, ylim=c(16,41), main=paste("Interaction plot. When data includes the nobs and sd variables,\n", "'data.is.summary=TRUE' is needed"))
Draw a "ladder of powers" plot, plotting each of several powers of y against the same powers of x. The powers are
result <- data.frame(-1/x, -1/sqrt(x), log(x), sqrt(x), x, x^2)
names(result) <- c(-1, -.5, 0, .5, 1, 2)
ladder(formula.in, data=NULL, main.in="Ladders of Powers", panel.in=panel.cartesian, xlab=deparse(formula.in[[3]]), ylab=deparse(formula.in[[2]]), scales=list(alternating=FALSE, labels=FALSE, ticks=FALSE, cex=.6), par.strip.text=list(cex=.6), cex=.5, pch=16, between=list(x=.3, y=.3), dsx=xlab, dsy=ylab, ladder.function=ladder.f, strip.number=2, strip.names, strip.style=1, strip, oma=c(0,0,0,0), ## S-Plus axis3.line=.61, layout=c(length(tmp$x.power), length(tmp$y.power)), axis.key.padding = 10, ## R right axis key.axis.padding = 10, ## R top axis useOuter=TRUE, ## R useOuterStrips(combineLimits(result)) ...) ladder3(x, y, dsx=deparse(substitute(x)), dsy=deparse(substitute(y)), ladder.function=ladder.f) ladder.f(x, name.prefix="") ladder.fstar(x, name.prefix="") strip.ladder(which.given, which.panel, var.name, factor.levels, shingle.intervals, par.strip.text=trellis.par.get("add.text"), strip.names=c(TRUE,TRUE), style=1, ...)
ladder(formula.in, data=NULL, main.in="Ladders of Powers", panel.in=panel.cartesian, xlab=deparse(formula.in[[3]]), ylab=deparse(formula.in[[2]]), scales=list(alternating=FALSE, labels=FALSE, ticks=FALSE, cex=.6), par.strip.text=list(cex=.6), cex=.5, pch=16, between=list(x=.3, y=.3), dsx=xlab, dsy=ylab, ladder.function=ladder.f, strip.number=2, strip.names, strip.style=1, strip, oma=c(0,0,0,0), ## S-Plus axis3.line=.61, layout=c(length(tmp$x.power), length(tmp$y.power)), axis.key.padding = 10, ## R right axis key.axis.padding = 10, ## R top axis useOuter=TRUE, ## R useOuterStrips(combineLimits(result)) ...) ladder3(x, y, dsx=deparse(substitute(x)), dsy=deparse(substitute(y)), ladder.function=ladder.f) ladder.f(x, name.prefix="") ladder.fstar(x, name.prefix="") strip.ladder(which.given, which.panel, var.name, factor.levels, shingle.intervals, par.strip.text=trellis.par.get("add.text"), strip.names=c(TRUE,TRUE), style=1, ...)
formula.in |
A formula with exactly one variable on each side. |
data |
data.frame |
main.in |
|
panel.in |
|
xlab , ylab
|
Trellis arguments, default to right- and left-sides
of the |
strip |
Strip function. Our default is |
cex , pch , between , scales , layout
|
arguments for |
dsx , dsy
|
Names to be used as level names in
|
ladder.function |
function to use to create data.frame of powers of input variable. |
name.prefix |
Base name used for column names of powers. The
default is empty ( |
strip.number |
Number of strip labels in each panel of the display.
0: no strip labels; 1: one strip label of the form |
useOuter |
logical, defaults to |
strip.style |
|
oma |
argument to |
... |
other arguments to |
axis3.line |
extra space to make the top axis align with the top of the top row of panels. Trial and error to choose a good value. |
axis.key.padding |
Extra space on right of set of panels in R. |
key.axis.padding |
Extra space on top of set of panels in R. |
x , y
|
variables. |
which.given , which.panel , var.name , factor.levels , shingle.intervals , par.strip.text
|
See
|
strip.names , style
|
We always print the |
The ladder
function uses panel.cartesian
which is
defined differently in R (using grid graphics) and S-Plus (using
traditional graphics). Therefore the fine control over appearance
uses different arguments or different values for the same arguments.
ladder
returns a "trellis"
object.
The functions ladder.fstar
and ladder.f
take an input
vector x
of non-negative values and construct a data.frame by
taking the input to the powers c(-1, -.5, 0, .5, 1, 2)
, one
column per power. ladder.f
uses the simple powers and
ladder.fstar
uses the scaled Box–Cox transformation.
ladder.fstar |
ladder.fstar |
notation |
(x^p - 1)/p |
(x^p - 1)/p |
p |
(1/x - 1)/(-1) |
(1/x - 1)/(-1) |
-1.0 |
(1/sqrt(x)-1)/(-.5) |
(1/sqrt(x)-1)/(-.5) |
-0.5 |
log(x) |
log(x) |
0.0 |
((sqrt(x)-1)/.5) |
((sqrt(x)-1)/.5) |
0.5 |
x-1 |
x-1 |
1.0 |
(x^2 - 1)/2 |
(x^2 - 1)/2 |
2.0 |
ladder3
takes two vectors as arguments. It returns a
data.frame
with five columns:
X, Y
: data to be plotted. The column X
contains the data
from the input x
taken to all the powers and aligned with the
similarly expanded column Y
.
x, y
: symbolic labeling of the power corresponding to X,Y
.
group
: result from pasting the labels in x, y
with *
between them.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Hoaglin, D.~C., Mosteller, F., and Tukey, J.~W., editors (1983). Understanding Robust and Exploratory Data Analysis. Wiley.
Box, G. E.~P. and Cox, D.~R. (1964). An analysis of transformations. J. Royal Statist Soc B, 26:211–252.
data(tv) ## default ## R: outer strip labels ladder(life.exp ~ ppl.per.phys, data=tv, main="Ladder of Powers for Life Expectancy and People per Physician") ## Not run: ## one strip label ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=1, useOuter=FALSE, dsx="ppp", dsy="le") ## two strip labels ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=2, useOuter=FALSE) ## outer strip labels ladder(life.exp ~ ppl.per.phys, data=tv, useOuter=TRUE) ## no strip labels (probably silly, but possible) ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=0, useOuter=FALSE) ## End(Not run)
data(tv) ## default ## R: outer strip labels ladder(life.exp ~ ppl.per.phys, data=tv, main="Ladder of Powers for Life Expectancy and People per Physician") ## Not run: ## one strip label ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=1, useOuter=FALSE, dsx="ppp", dsy="le") ## two strip labels ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=2, useOuter=FALSE) ## outer strip labels ladder(life.exp ~ ppl.per.phys, data=tv, useOuter=TRUE) ## no strip labels (probably silly, but possible) ladder(life.exp ~ ppl.per.phys, data=tv, strip.number=0, useOuter=FALSE) ## End(Not run)
"array"
or "table"
with 3, 4, or more dimensions.
Generate the latex code for an "array"
or "table"
with 3, 4, or more dimensions.
## S3 method for class 'array' latex(object, ..., var.sep = "}\\tabularnewline{\\bfseries ", value.sep = ": ", use.ndn = TRUE, cgroup = NULL, ## rgroup here captures and ignores any incoming rgroup argument rgroup = NULL, n.rgroup = NULL, title = first.word(deparse(substitute(object))), rowlabel=title, rsubgroup=NULL, n.rsubgroup=NULL) ## S3 method for class 'matrix' latex(object, ..., use.ndn=TRUE, cgroup=NULL, title=first.word(deparse(substitute(object))), rowlabel=title) ## S3 method for class 'table' latex(object, ...) ## prepend c("matrix", "array") to the ## class of the input object, and then call latex.default
## S3 method for class 'array' latex(object, ..., var.sep = "}\\tabularnewline{\\bfseries ", value.sep = ": ", use.ndn = TRUE, cgroup = NULL, ## rgroup here captures and ignores any incoming rgroup argument rgroup = NULL, n.rgroup = NULL, title = first.word(deparse(substitute(object))), rowlabel=title, rsubgroup=NULL, n.rsubgroup=NULL) ## S3 method for class 'matrix' latex(object, ..., use.ndn=TRUE, cgroup=NULL, title=first.word(deparse(substitute(object))), rowlabel=title) ## S3 method for class 'table' latex(object, ...) ## prepend c("matrix", "array") to the ## class of the input object, and then call latex.default
object |
A |
... |
Arguments forwarded to the "default" method for |
use.ndn |
Logical.
|
rgroup , n.rgroup
|
These are the standard arguments for |
rsubgroup , n.rsubgroup
|
These are based on the standard arguments for |
title , rowlabel , cgroup
|
These are the standard arguments for |
value.sep |
When |
var.sep |
When |
latex.matrix
calls latex.default
directly.
When use.ndn
is TRUE
(the default), rowlabel
and
cgroup
are constructed from names(dimnames(object))
unless the user explicitly specified them.
latex.array
appends all two-dimensional layers
object[,, one, at, a, time]
into a single long "matrix"
,
ignores any incoming rgroup
and n.rgroup
(with a warning),
and constructs rgroup
and n.rgroup
to label the layers.
When use.ndn
is TRUE
(the default), rowlabel
and
cgroup
are constructed from names(dimnames(object))
unless the user explicitly specified them.
latex.table
prepends c("matrix", "array")
to the class of
the "table"
object, then calls the generic "latex"
.
This step is necessary because the survey
package creates
objects whose class includes the value "table"
but not the values
c("matrix", "array")
. Should this object be sent directly to
latex.default
, it would cause on error for any table with
dimension larger than two.
See latex
.
Richard M. Heiberger <[email protected]>
## Not run: ## These are the recommended options. See ?Hmisc::latex for details. options(latexcmd='pdflatex') options(dviExtension='pdf') options(xdvicmd='open') ## Macintosh, Windows, SMP linux ## End(Not run) ## This sets up the defaults for latex to write to a pdf file microplot::latexSetOptions() ## It is needed for R CMD check. ## It is recommended if you normally use pdflatex. ## If you want some other destination for latex, use a non-default argument. tmp3 <- array(1:8, c(2,2,2), list(letters[1:2], letters[3:4], letters[5:6])) tmp3 ltmp3 <- latex(tmp3) ## assignment prevents display of the generated pdf file ## enter the object name to display the file on screen ## ltmp3 ## latex(tmp3) causes a file tmp3.tex to be created in the working directory. ## A user might want to keep tmp3.tex and \input{tmp3.tex} it into a longer .tex file. ## R CMD check doesn't like tmp3.tex to remain, so it is removed here. file.remove("tmp3.tex") ## Not run: try( ## warning: Input rgroup and n.rgroup are ignored latex(tmp3, rgroup=letters[1:3], n.rgroup=c(1,1,2), file="ignorergroup.tex") ) names(dimnames(tmp3)) <- LETTERS[24:26] latex(tmp3, file="LETTERS3.tex") latex(tmp3, rowlabel="Something Else", file="SomethingElse.tex") tmp4 <- array(1:120, c(5,4,3,2), list(letters[1:5], letters[6:9], letters[10:12], letters[13:14])) tmp4 latex(tmp4, var.sep=" ; ") names(dimnames(tmp4)) <- LETTERS[23:26] latex(tmp4, file="LETTERS4.tex") ## with rsubgroup and n.rsubgroup latex(tmp4, var.sep=" ; ", file="LETTERS4sub.tex", rsubgroup=c("Three","Two"), n.rsubgroup=c(3,2)) ## with rsubgroup and n.rsubgroup and cgroup and n.cgroup latex(tmp4, var.sep=" ; ", file="LETTERS4sub.tex", rsubgroup=c("Three","Two"), n.rsubgroup=c(3,2), cgroup=c("FGH","I"), n.cgroup=c(3,1)) tmp2 <- array(1:6, c(3,2), list(Rows=letters[1:3], Columns=letters[4:5])) tmp2 latex(tmp2) ## Input rgroup honored for "matrix" latex(tmp2, rgroup=c("Two","One"), n.rgroup=c(2,1), file="rgroup.tex") latex(tmp2, rowlabel="something else", file="something.tex") ## tableDemo is based on a table constructed from ## survey::svytable(~ FactorA + FactorB + FactorC, Survey.Design.Object) tableDemo <- structure(c(28, 25, 33, 12, 6, 22, 8, 12, 23, 24, 6, 32, 32, 31, 59, 11, 2, 33, 10, 3, 23, 7, 2, 26), .Dim = c(3L, 4L, 2L), .Dimnames = list(FactorA = c("a", "b", "c"), FactorB = c("d", "e", "f", "g"), FactorC = c("h", "i")), class = "table") class(tableDemo) latex(tableDemo) ## End(Not run)
## Not run: ## These are the recommended options. See ?Hmisc::latex for details. options(latexcmd='pdflatex') options(dviExtension='pdf') options(xdvicmd='open') ## Macintosh, Windows, SMP linux ## End(Not run) ## This sets up the defaults for latex to write to a pdf file microplot::latexSetOptions() ## It is needed for R CMD check. ## It is recommended if you normally use pdflatex. ## If you want some other destination for latex, use a non-default argument. tmp3 <- array(1:8, c(2,2,2), list(letters[1:2], letters[3:4], letters[5:6])) tmp3 ltmp3 <- latex(tmp3) ## assignment prevents display of the generated pdf file ## enter the object name to display the file on screen ## ltmp3 ## latex(tmp3) causes a file tmp3.tex to be created in the working directory. ## A user might want to keep tmp3.tex and \input{tmp3.tex} it into a longer .tex file. ## R CMD check doesn't like tmp3.tex to remain, so it is removed here. file.remove("tmp3.tex") ## Not run: try( ## warning: Input rgroup and n.rgroup are ignored latex(tmp3, rgroup=letters[1:3], n.rgroup=c(1,1,2), file="ignorergroup.tex") ) names(dimnames(tmp3)) <- LETTERS[24:26] latex(tmp3, file="LETTERS3.tex") latex(tmp3, rowlabel="Something Else", file="SomethingElse.tex") tmp4 <- array(1:120, c(5,4,3,2), list(letters[1:5], letters[6:9], letters[10:12], letters[13:14])) tmp4 latex(tmp4, var.sep=" ; ") names(dimnames(tmp4)) <- LETTERS[23:26] latex(tmp4, file="LETTERS4.tex") ## with rsubgroup and n.rsubgroup latex(tmp4, var.sep=" ; ", file="LETTERS4sub.tex", rsubgroup=c("Three","Two"), n.rsubgroup=c(3,2)) ## with rsubgroup and n.rsubgroup and cgroup and n.cgroup latex(tmp4, var.sep=" ; ", file="LETTERS4sub.tex", rsubgroup=c("Three","Two"), n.rsubgroup=c(3,2), cgroup=c("FGH","I"), n.cgroup=c(3,1)) tmp2 <- array(1:6, c(3,2), list(Rows=letters[1:3], Columns=letters[4:5])) tmp2 latex(tmp2) ## Input rgroup honored for "matrix" latex(tmp2, rgroup=c("Two","One"), n.rgroup=c(2,1), file="rgroup.tex") latex(tmp2, rowlabel="something else", file="something.tex") ## tableDemo is based on a table constructed from ## survey::svytable(~ FactorA + FactorB + FactorC, Survey.Design.Object) tableDemo <- structure(c(28, 25, 33, 12, 6, 22, 8, 12, 23, 24, 6, 32, 32, 31, 59, 11, 2, 33, 10, 3, 23, 7, 2, 26), .Dim = c(3L, 4L, 2L), .Dimnames = list(FactorA = c("a", "b", "c"), FactorB = c("d", "e", "f", "g"), FactorC = c("h", "i")), class = "table") class(tableDemo) latex(tableDemo) ## End(Not run)
Subroutine used by residual.plots.lattice
latticeresids(x, data, main = "please use an appropriate main title", par.strip.text, scales.cex, y.relation, ...)
latticeresids(x, data, main = "please use an appropriate main title", par.strip.text, scales.cex, y.relation, ...)
x , data , main , par.strip.text , ...
|
lattice arguments. See |
scales.cex |
|
y.relation |
|
"trellis"
object.
Richard M. Heiberger <[email protected]>
Each key is created and then inserted into a single grob.
legendGrob2wt(...)
legendGrob2wt(...)
... |
key1, key2, etc. Each key will normally be the result of
a |
A Grid frame object (that inherits from 'grob').
Richard M. Heiberger, with asssistance from Deepayan Sarkar.
Constructs and plots diverging stacked barcharts for Likert, semantic differential, rating scale data, and population pyramids.
likert(x, ...) likertplot(x, ...) ## S3 method for class 'likert' plot(x, ...) ## S3 method for class 'formula' plot.likert(x, data, ReferenceZero=NULL, value, levelsName="", scales.in=NULL, ## use scales= between=list(x=1 + (horizontal), y=.5 + 2*(!horizontal)), auto.key.in=NULL, ## use auto.key= panel.in=NULL, ## use panel= horizontal=TRUE, par.settings.in=NULL, ## use par.settings= ..., as.percent = FALSE, ## titles ylab= if (horizontal) { if (length(x)==3) deparse(x[[2]]) else "Question" } else if (as.percent != FALSE) "Percent" else "Count", xlab= if (!horizontal) { if (length(x)==3) deparse(x[[2]]) else "Question" } else if (as.percent != FALSE) "Percent" else "Count", main = x.sys.call, ## right axis rightAxisLabels = rowSums(data.list$Nums), rightAxis = !missing(rightAxisLabels), ylab.right = if (rightAxis) "Row Count Totals" else NULL, xlab.top = NULL, right.text.cex = if (horizontal) { ## lazy evaluation if (!is.null(scales$y$cex)) scales$y$cex else .8 } else { if (!is.null(scales$x$cex)) scales$x$cex else .8 }, ## scales xscale.components = xscale.components.top.HH, yscale.components = yscale.components.right.HH, xlimEqualLeftRight = FALSE, xTickLabelsPositive = TRUE, ## row sequencing as.table=TRUE, positive.order=FALSE, data.order=FALSE, reverse=ifelse(horizontal, as.table, FALSE), ## resizePanels arguments h.resizePanels=sapply(result$y.used.at, length), w.resizePanels=sapply(result$x.used.at, length), ## color options reference.line.col="gray65", col.strip.background="gray97", key.border.white=TRUE, col=likertColor(Nums.attr$nlevels, ReferenceZero=ReferenceZero, colorFunction=colorFunction, colorFunctionOption=colorFunctionOption), colorFunction="diverge_hcl", colorFunctionOption="lighter" ) ## S3 method for class 'matrix' plot.likert(x, positive.order=FALSE, ylab=names(dimnames(x)[1]), xlab=if (as.percent != FALSE) "Percent" else "Count", main=xName, reference.line.col="gray65", col.strip.background="gray97", col=likertColor(attr(x, "nlevels"), ReferenceZero=ReferenceZero, colorFunction=colorFunction, colorFunctionOption=colorFunctionOption), colorFunction="diverge_hcl", colorFunctionOption="lighter", as.percent=FALSE, par.settings.in=NULL, horizontal=TRUE, ReferenceZero=NULL, ..., key.border.white=TRUE, xName=deparse(substitute(x)), rightAxisLabels=rowSums(abs(x)), rightAxis=!missing(rightAxisLabels), ylab.right=if (rightAxis) "Row Count Totals" else NULL, panel=panel.barchart, xscale.components=xscale.components.top.HH, yscale.components=yscale.components.right.HH, xlimEqualLeftRight=FALSE, xTickLabelsPositive=TRUE, reverse=FALSE) ## Default S3 method: plot.likert(x, ...) ## calls plot.likert.matrix ## S3 method for class 'array' plot.likert(x, condlevelsName=paste("names(dimnames(", xName, "))[-(1:2)]", sep=""), xName=deparse(substitute(x)), main=paste("layers of", xName, "by", condlevelsName), ...) ## S3 method for class 'likert' plot.likert(x, ...) ## See Details ## S3 method for class 'list' plot.likert(x, ## named list of matrices, 2D tables, ## 2D ftables, or 2D structables, ## or all-numeric data.frames condlevelsName="ListNames", xName=deparse(substitute(x)), main=paste("List items of", xName, "by", condlevelsName), layout=if (length(dim.x) > 1) dim.x else { if (horizontal) c(1, length(x)) else c(length(x), 1)}, positive.order=FALSE, strip=!horizontal, strip.left=horizontal, strip.left.values=names(x), strip.values=names(x), strip.par=list(cex=1, lines=1), strip.left.par=list(cex=1, lines=1), horizontal=TRUE, ..., rightAxisLabels=sapply(x, function(x) rowSums(abs(x)), simplify = FALSE), rightAxis=!missing(rightAxisLabels), resize.height.tuning=-.5, resize.height=if (missing(layout) || length(dim.x) != 2) { c("nrow","rowSums") } else { rep(1, layout[2]) }, resize.width=if (missing(layout)) {1 } else { rep(1, layout[1]) }, box.ratio=if ( length(resize.height)==1 && resize.height == "rowSums") 1000 else 2, xscale.components=xscale.components.top.HH, yscale.components=yscale.components.right.HH) ## S3 method for class 'table' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'ftable' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'structable' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'data.frame' plot.likert(x, ..., xName=deparse(substitute(x))) xscale.components.top.HH(...) yscale.components.right.HH(...)
likert(x, ...) likertplot(x, ...) ## S3 method for class 'likert' plot(x, ...) ## S3 method for class 'formula' plot.likert(x, data, ReferenceZero=NULL, value, levelsName="", scales.in=NULL, ## use scales= between=list(x=1 + (horizontal), y=.5 + 2*(!horizontal)), auto.key.in=NULL, ## use auto.key= panel.in=NULL, ## use panel= horizontal=TRUE, par.settings.in=NULL, ## use par.settings= ..., as.percent = FALSE, ## titles ylab= if (horizontal) { if (length(x)==3) deparse(x[[2]]) else "Question" } else if (as.percent != FALSE) "Percent" else "Count", xlab= if (!horizontal) { if (length(x)==3) deparse(x[[2]]) else "Question" } else if (as.percent != FALSE) "Percent" else "Count", main = x.sys.call, ## right axis rightAxisLabels = rowSums(data.list$Nums), rightAxis = !missing(rightAxisLabels), ylab.right = if (rightAxis) "Row Count Totals" else NULL, xlab.top = NULL, right.text.cex = if (horizontal) { ## lazy evaluation if (!is.null(scales$y$cex)) scales$y$cex else .8 } else { if (!is.null(scales$x$cex)) scales$x$cex else .8 }, ## scales xscale.components = xscale.components.top.HH, yscale.components = yscale.components.right.HH, xlimEqualLeftRight = FALSE, xTickLabelsPositive = TRUE, ## row sequencing as.table=TRUE, positive.order=FALSE, data.order=FALSE, reverse=ifelse(horizontal, as.table, FALSE), ## resizePanels arguments h.resizePanels=sapply(result$y.used.at, length), w.resizePanels=sapply(result$x.used.at, length), ## color options reference.line.col="gray65", col.strip.background="gray97", key.border.white=TRUE, col=likertColor(Nums.attr$nlevels, ReferenceZero=ReferenceZero, colorFunction=colorFunction, colorFunctionOption=colorFunctionOption), colorFunction="diverge_hcl", colorFunctionOption="lighter" ) ## S3 method for class 'matrix' plot.likert(x, positive.order=FALSE, ylab=names(dimnames(x)[1]), xlab=if (as.percent != FALSE) "Percent" else "Count", main=xName, reference.line.col="gray65", col.strip.background="gray97", col=likertColor(attr(x, "nlevels"), ReferenceZero=ReferenceZero, colorFunction=colorFunction, colorFunctionOption=colorFunctionOption), colorFunction="diverge_hcl", colorFunctionOption="lighter", as.percent=FALSE, par.settings.in=NULL, horizontal=TRUE, ReferenceZero=NULL, ..., key.border.white=TRUE, xName=deparse(substitute(x)), rightAxisLabels=rowSums(abs(x)), rightAxis=!missing(rightAxisLabels), ylab.right=if (rightAxis) "Row Count Totals" else NULL, panel=panel.barchart, xscale.components=xscale.components.top.HH, yscale.components=yscale.components.right.HH, xlimEqualLeftRight=FALSE, xTickLabelsPositive=TRUE, reverse=FALSE) ## Default S3 method: plot.likert(x, ...) ## calls plot.likert.matrix ## S3 method for class 'array' plot.likert(x, condlevelsName=paste("names(dimnames(", xName, "))[-(1:2)]", sep=""), xName=deparse(substitute(x)), main=paste("layers of", xName, "by", condlevelsName), ...) ## S3 method for class 'likert' plot.likert(x, ...) ## See Details ## S3 method for class 'list' plot.likert(x, ## named list of matrices, 2D tables, ## 2D ftables, or 2D structables, ## or all-numeric data.frames condlevelsName="ListNames", xName=deparse(substitute(x)), main=paste("List items of", xName, "by", condlevelsName), layout=if (length(dim.x) > 1) dim.x else { if (horizontal) c(1, length(x)) else c(length(x), 1)}, positive.order=FALSE, strip=!horizontal, strip.left=horizontal, strip.left.values=names(x), strip.values=names(x), strip.par=list(cex=1, lines=1), strip.left.par=list(cex=1, lines=1), horizontal=TRUE, ..., rightAxisLabels=sapply(x, function(x) rowSums(abs(x)), simplify = FALSE), rightAxis=!missing(rightAxisLabels), resize.height.tuning=-.5, resize.height=if (missing(layout) || length(dim.x) != 2) { c("nrow","rowSums") } else { rep(1, layout[2]) }, resize.width=if (missing(layout)) {1 } else { rep(1, layout[1]) }, box.ratio=if ( length(resize.height)==1 && resize.height == "rowSums") 1000 else 2, xscale.components=xscale.components.top.HH, yscale.components=yscale.components.right.HH) ## S3 method for class 'table' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'ftable' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'structable' plot.likert(x, ..., xName=deparse(substitute(x))) ## S3 method for class 'data.frame' plot.likert(x, ..., xName=deparse(substitute(x))) xscale.components.top.HH(...) yscale.components.right.HH(...)
x |
For the formula method, a model formula. All terms in the
formula must be the names of columns in the data.frame argument
Otherwise, any numeric object stored as a vector, matrix, array,
data.frame, table, ftable, structable (as defined in the |
data |
For the formula method, a |
ReferenceZero |
Numeric scalar or |
value |
Name of the numeric variable containing the data when the formula method is used with the long data form. The predictor in the formula will be a factor name. The name of the predictor will be used as the title in the key. |
levelsName |
(optional) Name of the implied factor distinguishing the columns of the response variables when the formula method is used with the wide data form. This name will be used as the title in the key. |
positive.order |
If |
data.order |
|
as.percent |
When |
as.table |
Standard |
par.settings.in , scales.in , auto.key.in , panel.in
|
These are placeholders
for |
ylab , xlab , ylab.right , xlab.top , main
|
Standard |
right.text.cex |
The right axis, as used here for the
"Row Count Totals", has non-standard controls. It's |
between |
Standard |
col |
Vector of color names for the levels of the agreement factor.
Although the colors can be specified as an arbitrary vector of color names, for example,
|
colorFunction , colorFunctionOption
|
See |
reference.line.col |
Color for reference line at zero. |
col.strip.background |
Background color for the strip labels. |
key.border.white |
Logical. If |
horizontal |
Logical, with default |
... |
other arguments. These will be passed to the |
strip.left , strip
|
Logical. The default |
condlevelsName , strip.left.values , strip.values , strip.par , strip.left.par , layout
|
Arguments which will be passed to
|
xName |
Name of the argument in its original environment. |
rightAxis |
logical. Should right axis values be displayed?
Defaults to |
rightAxisLabels |
Values to be displayed on the right axis. The
default values are the row totals. These are sensible for
tables of counts. When the data is rescaled to percents by the
|
resize.height.tuning |
Tuning parameter used to adjust the space
between bars as specified by the |
h.resizePanels , resize.height
|
Either character scalar or numeric vector.
If |
w.resizePanels , resize.width
|
Numeric vector. The panel widths are proportional to the numbers in the argument. |
box.ratio |
If there are more than one bar in any panel, then
this defaults to the |
panel |
panel function eventually to be used by |
xscale.components , yscale.components
|
See
|
xlimEqualLeftRight |
Logical. The default is |
xTickLabelsPositive |
Logical. The default is |
reverse |
Logical. The default is |
The counts (or percentages) of respondents on each row who agree with
the statement are shown to the right of the zero line; the counts (or
percentages) who disagree are shown to the left. The counts (or
percentages) for respondents who neither agree nor disagree are split
down the middle and are shown in a neutral color. The neutral category
is omitted when the scale has an even number of choices.
It is difficult to compare
lengths without a common baseline. In this situation, we are primarily
interested in the total count (or percent) to the right or left of the
zero line; the breakdown into strongly or not is of lesser interest so
that the primary comparisons do have a common baseline of zero. The
rows within each panel are displayed in their original order by
default. If the argument positive.order=TRUE
is specified, the rows
are ordered by the counts (or percentages) who agree.
Diverging stacked barcharts are also called "two-directional stacked barcharts". Some authors use the term "floating barcharts" for vertical diverging stacked barcharts and the term "sliding barcharts" for horizontal diverging stacked barcharts.
All items in a list of named two-dimensional objects must have the
same number of columns. If the items have different column names, the
column names of the last item in the list will be used in the key. If
the dimnames of the matrices are named, the names will be used in the
plot. It is possible to produce a likert plot with a list of objects
with different numbers of columns, but not with the
plot.likert.list
method. These must be done manually by using
the ResizeEtc
function on each of the individual likert
plots. The difficulty is that the legend is based on the last item in
the list and will have the wrong number of values for some of the
panels.
A single data.frame x
will be plotted as data.matrix(x[sapply(x, is.numeric)])
.
The subscripting on the class of the columns is there to remove
columns of characters (which would otherwise be coerced to NA) and
factor columns (which would otherwise be coerced to integers).
A data.frame with only numeric columns will work in a named list.
A list of data.frame with factors or characters will be plotted by
automatically removing columns that are not numeric.
ftable
and structable
arguments x
will be plotted as
as.table(x)
. This changes the display sequence.
Therefore the user will probably want to use aperm
on the
ftable
or structable
before using plot.likert
.
The likert
method is designed for use with "likert"
objects created with the independent likert package. It is not
recommended that the HH package and the likert
package
both be loaded at the same time, as they have incompatible usage of
the exported function names likert
and plot.likert
. If
the likert package is installed, it can be run without loading
by using the function calls likert::likert()
and
likert:::plot.likert()
.
A "trellis"
object containing the plot. The plot will be
automatically displayed unless the result is assigned to an object.
The current version of the likert
function uses the default diverging
palette from diverge_hcl
as the default.
Previous versions used the RColorBrewer
palette "RdBu"
as the default
color palette. The previous color palette is still available with an explicit
call to likertColorBrewer
, for example
col=likertColorBrewer(nc, ReferenceZero=ReferenceZero,
BrewerPaletteName="RdBu", middle.color="gray90")
Ann Liu-Ferrara was a beta tester for the shiny app.
Most of the plots drawn by plot.likert
have a long
left-axis tick label. They therefore require a wider window
than R's default of a nominal 7in 7in window. The
comments with the examples suggest aesthetic window sizes.
There are three (almost) equivalent calling sequences for likert plots.
likert(x) ## recommended
likert
is an alias for plot.likert()
.
plot.likert(x)
plot.likert
is both a method of
plot
for "likert"
objects, and a generic function in its own
right. There are methods of plot.likert
for
"formula"
,
"matrix"
,
"array"
, "table"
, and several other classes of input objects.
plot(as.likert(x))
Both likert
and plot.likert
work by calling the
as.likert
function on their argument x
. Once as.likert
has converted its argument to a "likert"
object, the method
dispatch technology for the generic plot.likert
is in play.
The user can make the explicit call as.likert(x)
to see what
a "likert"
object looks like, but is very unlikely to want to
look a second time.
Richard M. Heiberger, with contributions from Naomi B. Robbins <[email protected]>.
Maintainer: Richard M. Heiberger <[email protected]>
Richard M. Heiberger, Naomi B. Robbins (2014)., "Design of Diverging Stacked Bar Charts for Likert Scales and Other Applications", Journal of Statistical Software, 57(5), 1–32, doi:10.18637/jss.v057.i05.
Richard Heiberger and Naomi Robbins (2011), "Alternative to Charles Blow's Figure in \"Newt's War on Poor Children\"", Forbes OnLine, December 20, 2011. https://www.forbes.com/sites/naomirobbins/2011/12/20/alternative-to-charles-blows-figure-in-newts-war-on-poor-children-2/
Naomi Robbins (2011), "Visualizing Data: Challenges to
Presentation of Quality Graphics—and Solutions", Amstat News,
September 2011, 28–30.
http://magazine.amstat.org/blog/2011/09/01/visualizingdata/
Luo, Amy and Tim Keyes (2005). "Second Set of Results in from the Career Track Member Survey," Amstat News. Arlington, VA: American Statistical Association.
barchart
, ResizeEtc
,
as.likert
,
as.matrix.listOfNamedMatrices
,
pyramidLikert
## See file HH/demo/likert-paper.r for a complete set of examples using ## the formula method into the underlying lattice:::barchart plotting ## technology. See file HH/demo/likert-paper-noFormula.r for the same ## set of examples using the matrix and list of matrices methods. See ## file HH/demo/likertMosaic-paper.r for the same set of examples using ## the still experimental functions built on the vcd:::mosaic as the ## underlying plotting technology data(ProfChal) ## ProfChal is a data.frame. ## See below for discussion of the dataset. ## Count plot likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") ## Percent plot calculated automatically from Count data likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") ## formula method data(NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## Not run: ## formula notation with expanded right-hand-side likert(Question ~ "Strongly disagree" + Disagree + Neutral + Agree + "Strongly agree" | Subtable, data=NZScienceTeaching, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## End(Not run) ## Not run: ## formula notation with long data arrangement NZScienceTeachingLong <- reshape2::melt(NZScienceTeaching, id.vars=c("Question", "Subtable")) names(NZScienceTeachingLong)[3] <- "Agreement" head(NZScienceTeachingLong) likert(Question ~ Agreement | Subtable, value="value", data=NZScienceTeachingLong, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## End(Not run) ## Examples with higher-dimensional arrays. tmp3 <- array(1:24, dim=c(2,3,4), dimnames=list(A=letters[1:2], B=LETTERS[3:5], C=letters[6:9])) ## positive.order=FALSE is the default. With arrays ## the rownames within each item of an array are identical. ## likert(tmp3) likert(tmp3, layout=c(1,4)) likert(tmp3, layout=c(2,2), resize.height=c(2,1), resize.width=c(3,4)) ## plot.likert interprets vectors as single-row matrices. ## http://survey.cvent.com/blog/customer-insights-2/box-scores-are-not-just-for-baseball Responses <- c(15, 13, 12, 25, 35) names(Responses) <- c("Strongly Disagree", "Disagree", "No Opinion", "Agree", "Strongly Agree") ## Not run: likert(Responses, main="Retail-R-Us offers the best everyday prices.", sub="This plot looks better in a 9in x 2.6in window.") ## End(Not run) ## reverse=TRUE is needed for a single-column key with ## horizontal=FALSE and with space="right" likert(Responses, horizontal=FALSE, aspect=1.5, main="Retail-R-Us offers the best everyday prices.", auto.key=list(space="right", columns=1, reverse=TRUE, padding.text=2), sub="This plot looks better in a 4in x 3in window.") ## Not run: ## Since age is always positive and increases in a single direction, ## this example uses colors from a sequential palette for the age ## groups. In this example we do not use a diverging palette that is ## appropriate when groups are defined by a characteristic, such as ## strength of agreement or disagreement, that can increase in two directions. ## Initially we use the default Blue palette in the sequential_hcl function. data(AudiencePercent) likert(AudiencePercent, auto.key=list(between=1, between.columns=2), xlab=paste("Percentage of audience younger than 35 (left of zero)", "and older than 35 (right of zero)"), main="Target Audience", col=rev(colorspace::sequential_hcl(4)), sub="This plot looks better in a 7in x 3.5in window.") ## The really light colors in the previous example are too light. ## Therefore we use the col argument directly. We chose to use an ## intermediate set of Blue colors selected from a longer Blue palette. likert(AudiencePercent, positive.order=TRUE, auto.key=list(between=1, between.columns=2), xlab=paste("Percentage of audience younger than 35", "(left of zero) and older than 35 (right of zero)"), main="Brand A has the most even distribution of ages", col=colorspace::sequential_hcl(11)[5:2], scales=list(x=list(at=seq(-90,60,10), labels=as.vector(rbind("",seq(-80,60,20))))), sub="This plot looks better in a 7in x 3.5in window.") ## End(Not run) ## Not run: ## See the ?as.pyramidLikert help page for these examples ## Population Pyramid data(USAge.table) USA79 <- USAge.table[75:1, 2:1, "1979"]/1000000 PL <- likert(USA79, main="Population of United States 1979 (ages 0-74)", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)) ) PL as.pyramidLikert(PL) likert(USAge.table[75:1, 2:1, c("1939","1959","1979")]/1000000, main="Population of United States 1939,1959,1979 (ages 0-74)", sub="Look for the Baby Boom", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)), strip.left=FALSE, strip=TRUE, layout=c(3,1), between=list(x=.5)) ## End(Not run) Pop <- rbind(a=c(3,2,4,9), b=c(6,10,12,10)) dimnames(Pop)[[2]] <- c("Very Low", "Low", "High", "Very High") likert(as.listOfNamedMatrices(Pop), as.percent=TRUE, resize.height="rowSums", strip=FALSE, strip.left=FALSE, main=paste("Area and Height are proportional to 'Row Count Totals'.", "Width is exactly 100%.", sep="\n")) ## Professional Challenges example. ## ## The data for this example is a list of related likert scales, with ## each item in the list consisting of differently named rows. The data ## is from a questionnaire analyzed in a recent Amstat News article. ## The study population was partitioned in several ways. Data from one ## of the partitions (Employment sector) was used in the first example ## in this help file. The examples here show various options for ## displaying all partitions on the same plot. ## data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## 1. Plot counts with rows in each panel sorted by positive counts. ## ## Not run: likert(Question ~ . | Subtable, ProfChal, positive.order=TRUE, main="This works, but needs more specified arguments to look good") likert(Question ~ . | Subtable, ProfChal, scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", ylab=NULL, sub="This looks better in a 10inx7in window") ## End(Not run) ProfChalCountsPlot <- likert(Question ~ . | Subtable, ProfChal, scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, box.width=unit(.4,"cm"), between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", rightAxis=TRUE, ## display Row Count Totals ylab=NULL, sub="This looks better in a 10inx7in window") ProfChalCountsPlot ## Not run: ## 2. Plot percents with rows in each panel sorted by positive percents. ## This is a different sequence than the counts. Row Count Totals are ## displayed on the right axis. ProfChalPctPlot <- likert(Question ~ . | Subtable, ProfChal, as.percent=TRUE, ## implies display Row Count Totals scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, box.width=unit(.4,"cm"), between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", rightAxis=TRUE, ## display Row Count Totals ylab=NULL, sub="This looks better in a 10inx7in window") ProfChalPctPlot ## 3. Putting both percents and counts on the same plot, both in ## the order of the positive percents. LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Restore original name ## levels(ProfChal$Subtable)[6] <- "Attitude\ntoward\nProfessional\nRecognition" ## End(Not run) ## Not run: ## 4. All possible forms of formula for the likert formula method: data(ProfChal) row.names(ProfChal) <- abbreviate(ProfChal$Question, 8) likert( Question ~ . | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( Question ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree" | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( Question ~ . , data=ProfChal) likert( Question ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree", data=ProfChal) likert( ~ . | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree" | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( ~ . , data=ProfChal) likert( ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree", data=ProfChal) ## End(Not run) ## Not run: ## 5. putting the x-axis tick labels on top for horizontal plots ## putting the y-axis tick lables on right for vertical plots ## ## This non-standard specification is a consequence of using the right ## axis labels for different values than appear on the left axis labels ## with horizontal plots, and using the top axis labels for different ## values than appear on the bottom axis labels with vertical plots. ## Percent plot calculated automatically from Count data tmph <- likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") tmph$x.scales$labels names(tmph$x.scales$labels) <- tmph$x.scales$labels update(tmph, scales=list(x=list(alternating=2)), xlab=NULL, xlab.top="Percent") tmpv <- likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', sub="likert plots with long Question names look better horizontally. With effort they can be made to look adequate vertically.", horizontal=FALSE, scales=list(y=list(alternating=2), x=list(rot=c(90, 0))), ylab.right="Percent", ylab=NULL, xlab.top="Column Count Totals", par.settings=list( layout.heights=list(key.axis.padding=5), layout.widths=list(key.right=1.5, right.padding=0)) ) tmpv$y.scales$labels names(tmpv$y.scales$labels) <- tmpv$y.scales$labels tmpv tmpv$x.limits <- abbreviate(tmpv$x.limits,8) tmpv$x.scales$rot=c(0, 0) tmpv ## End(Not run) ## Not run: ## illustration that a border on the bars is misleading when it splits a bar. tmp <- data.frame(a=1, b=2, c=3) likert(~ . , data=tmp, ReferenceZero=2, main="No border. OK.") likert(~ . , data=tmp, ReferenceZero=2, border="white", main="Border. Misleading split of central bar.") likert(~ . , data=tmp, ReferenceZero=2.5, main="No border. OK.") likert(~ . , data=tmp, ReferenceZero=2.5, border="white", main="Border. OK.") ## End(Not run) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/likert", package="HH")) ## End(Not run) ## The ProfChal data is done again with explicit use of ResizeEtc ## in ?HH:::ResizeEtc
## See file HH/demo/likert-paper.r for a complete set of examples using ## the formula method into the underlying lattice:::barchart plotting ## technology. See file HH/demo/likert-paper-noFormula.r for the same ## set of examples using the matrix and list of matrices methods. See ## file HH/demo/likertMosaic-paper.r for the same set of examples using ## the still experimental functions built on the vcd:::mosaic as the ## underlying plotting technology data(ProfChal) ## ProfChal is a data.frame. ## See below for discussion of the dataset. ## Count plot likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") ## Percent plot calculated automatically from Count data likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") ## formula method data(NZScienceTeaching) likert(Question ~ . | Subtable, data=NZScienceTeaching, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## Not run: ## formula notation with expanded right-hand-side likert(Question ~ "Strongly disagree" + Disagree + Neutral + Agree + "Strongly agree" | Subtable, data=NZScienceTeaching, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## End(Not run) ## Not run: ## formula notation with long data arrangement NZScienceTeachingLong <- reshape2::melt(NZScienceTeaching, id.vars=c("Question", "Subtable")) names(NZScienceTeachingLong)[3] <- "Agreement" head(NZScienceTeachingLong) likert(Question ~ Agreement | Subtable, value="value", data=NZScienceTeachingLong, ylab=NULL, scales=list(y=list(relation="free")), layout=c(1,2)) ## End(Not run) ## Examples with higher-dimensional arrays. tmp3 <- array(1:24, dim=c(2,3,4), dimnames=list(A=letters[1:2], B=LETTERS[3:5], C=letters[6:9])) ## positive.order=FALSE is the default. With arrays ## the rownames within each item of an array are identical. ## likert(tmp3) likert(tmp3, layout=c(1,4)) likert(tmp3, layout=c(2,2), resize.height=c(2,1), resize.width=c(3,4)) ## plot.likert interprets vectors as single-row matrices. ## http://survey.cvent.com/blog/customer-insights-2/box-scores-are-not-just-for-baseball Responses <- c(15, 13, 12, 25, 35) names(Responses) <- c("Strongly Disagree", "Disagree", "No Opinion", "Agree", "Strongly Agree") ## Not run: likert(Responses, main="Retail-R-Us offers the best everyday prices.", sub="This plot looks better in a 9in x 2.6in window.") ## End(Not run) ## reverse=TRUE is needed for a single-column key with ## horizontal=FALSE and with space="right" likert(Responses, horizontal=FALSE, aspect=1.5, main="Retail-R-Us offers the best everyday prices.", auto.key=list(space="right", columns=1, reverse=TRUE, padding.text=2), sub="This plot looks better in a 4in x 3in window.") ## Not run: ## Since age is always positive and increases in a single direction, ## this example uses colors from a sequential palette for the age ## groups. In this example we do not use a diverging palette that is ## appropriate when groups are defined by a characteristic, such as ## strength of agreement or disagreement, that can increase in two directions. ## Initially we use the default Blue palette in the sequential_hcl function. data(AudiencePercent) likert(AudiencePercent, auto.key=list(between=1, between.columns=2), xlab=paste("Percentage of audience younger than 35 (left of zero)", "and older than 35 (right of zero)"), main="Target Audience", col=rev(colorspace::sequential_hcl(4)), sub="This plot looks better in a 7in x 3.5in window.") ## The really light colors in the previous example are too light. ## Therefore we use the col argument directly. We chose to use an ## intermediate set of Blue colors selected from a longer Blue palette. likert(AudiencePercent, positive.order=TRUE, auto.key=list(between=1, between.columns=2), xlab=paste("Percentage of audience younger than 35", "(left of zero) and older than 35 (right of zero)"), main="Brand A has the most even distribution of ages", col=colorspace::sequential_hcl(11)[5:2], scales=list(x=list(at=seq(-90,60,10), labels=as.vector(rbind("",seq(-80,60,20))))), sub="This plot looks better in a 7in x 3.5in window.") ## End(Not run) ## Not run: ## See the ?as.pyramidLikert help page for these examples ## Population Pyramid data(USAge.table) USA79 <- USAge.table[75:1, 2:1, "1979"]/1000000 PL <- likert(USA79, main="Population of United States 1979 (ages 0-74)", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)) ) PL as.pyramidLikert(PL) likert(USAge.table[75:1, 2:1, c("1939","1959","1979")]/1000000, main="Population of United States 1939,1959,1979 (ages 0-74)", sub="Look for the Baby Boom", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)), strip.left=FALSE, strip=TRUE, layout=c(3,1), between=list(x=.5)) ## End(Not run) Pop <- rbind(a=c(3,2,4,9), b=c(6,10,12,10)) dimnames(Pop)[[2]] <- c("Very Low", "Low", "High", "Very High") likert(as.listOfNamedMatrices(Pop), as.percent=TRUE, resize.height="rowSums", strip=FALSE, strip.left=FALSE, main=paste("Area and Height are proportional to 'Row Count Totals'.", "Width is exactly 100%.", sep="\n")) ## Professional Challenges example. ## ## The data for this example is a list of related likert scales, with ## each item in the list consisting of differently named rows. The data ## is from a questionnaire analyzed in a recent Amstat News article. ## The study population was partitioned in several ways. Data from one ## of the partitions (Employment sector) was used in the first example ## in this help file. The examples here show various options for ## displaying all partitions on the same plot. ## data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## 1. Plot counts with rows in each panel sorted by positive counts. ## ## Not run: likert(Question ~ . | Subtable, ProfChal, positive.order=TRUE, main="This works, but needs more specified arguments to look good") likert(Question ~ . | Subtable, ProfChal, scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", ylab=NULL, sub="This looks better in a 10inx7in window") ## End(Not run) ProfChalCountsPlot <- likert(Question ~ . | Subtable, ProfChal, scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, box.width=unit(.4,"cm"), between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", rightAxis=TRUE, ## display Row Count Totals ylab=NULL, sub="This looks better in a 10inx7in window") ProfChalCountsPlot ## Not run: ## 2. Plot percents with rows in each panel sorted by positive percents. ## This is a different sequence than the counts. Row Count Totals are ## displayed on the right axis. ProfChalPctPlot <- likert(Question ~ . | Subtable, ProfChal, as.percent=TRUE, ## implies display Row Count Totals scales=list(y=list(relation="free")), layout=c(1,6), positive.order=TRUE, box.width=unit(.4,"cm"), between=list(y=0), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.6, lines=5), main="Is your job professionally challenging?", rightAxis=TRUE, ## display Row Count Totals ylab=NULL, sub="This looks better in a 10inx7in window") ProfChalPctPlot ## 3. Putting both percents and counts on the same plot, both in ## the order of the positive percents. LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Restore original name ## levels(ProfChal$Subtable)[6] <- "Attitude\ntoward\nProfessional\nRecognition" ## End(Not run) ## Not run: ## 4. All possible forms of formula for the likert formula method: data(ProfChal) row.names(ProfChal) <- abbreviate(ProfChal$Question, 8) likert( Question ~ . | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( Question ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree" | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( Question ~ . , data=ProfChal) likert( Question ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree", data=ProfChal) likert( ~ . | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree" | Subtable, data=ProfChal, scales=list(y=list(relation="free")), layout=c(1,6)) likert( ~ . , data=ProfChal) likert( ~ "Strongly Disagree" + Disagree + "No Opinion" + Agree + "Strongly Agree", data=ProfChal) ## End(Not run) ## Not run: ## 5. putting the x-axis tick labels on top for horizontal plots ## putting the y-axis tick lables on right for vertical plots ## ## This non-standard specification is a consequence of using the right ## axis labels for different values than appear on the left axis labels ## with horizontal plots, and using the top axis labels for different ## values than appear on the bottom axis labels with vertical plots. ## Percent plot calculated automatically from Count data tmph <- likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', ylab=NULL, sub="This plot looks better in a 9in x 4in window.") tmph$x.scales$labels names(tmph$x.scales$labels) <- tmph$x.scales$labels update(tmph, scales=list(x=list(alternating=2)), xlab=NULL, xlab.top="Percent") tmpv <- likert(Question ~ . , ProfChal[ProfChal$Subtable=="Employment sector",], as.percent=TRUE, main='Is your job professionally challenging?', sub="likert plots with long Question names look better horizontally. With effort they can be made to look adequate vertically.", horizontal=FALSE, scales=list(y=list(alternating=2), x=list(rot=c(90, 0))), ylab.right="Percent", ylab=NULL, xlab.top="Column Count Totals", par.settings=list( layout.heights=list(key.axis.padding=5), layout.widths=list(key.right=1.5, right.padding=0)) ) tmpv$y.scales$labels names(tmpv$y.scales$labels) <- tmpv$y.scales$labels tmpv tmpv$x.limits <- abbreviate(tmpv$x.limits,8) tmpv$x.scales$rot=c(0, 0) tmpv ## End(Not run) ## Not run: ## illustration that a border on the bars is misleading when it splits a bar. tmp <- data.frame(a=1, b=2, c=3) likert(~ . , data=tmp, ReferenceZero=2, main="No border. OK.") likert(~ . , data=tmp, ReferenceZero=2, border="white", main="Border. Misleading split of central bar.") likert(~ . , data=tmp, ReferenceZero=2.5, main="No border. OK.") likert(~ . , data=tmp, ReferenceZero=2.5, border="white", main="Border. OK.") ## End(Not run) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/likert", package="HH")) ## End(Not run) ## The ProfChal data is done again with explicit use of ResizeEtc ## in ?HH:::ResizeEtc
Selection of colors for Likert plots.
ColorSet(nc, ReferenceZero=NULL) likertColor(nc, ReferenceZero=NULL, colorFunction=c("diverge_hcl","sequential_hcl"), colorFunctionOption=c("lighter","flatter","default"), colorFunctionArgs= likertColorFunctionArgs[[colorFunctionOption, colorFunction]], ...) likertColorBrewer(nc, ReferenceZero=NULL, BrewerPaletteName="RdBu", middle.color="gray90") brewer.pal.likert(n, name, middle.color)
ColorSet(nc, ReferenceZero=NULL) likertColor(nc, ReferenceZero=NULL, colorFunction=c("diverge_hcl","sequential_hcl"), colorFunctionOption=c("lighter","flatter","default"), colorFunctionArgs= likertColorFunctionArgs[[colorFunctionOption, colorFunction]], ...) likertColorBrewer(nc, ReferenceZero=NULL, BrewerPaletteName="RdBu", middle.color="gray90") brewer.pal.likert(n, name, middle.color)
n , nc
|
Number of colors in the palette.
If there are more levels than |
ReferenceZero |
Numeric scalar or |
colorFunction |
Function name from the colorspace package,
either |
colorFunctionOption |
Name of a list item defined inside the
|
colorFunctionArgs |
list of arguments to the colorspace
function.
The default selects the values by indexing into a list defined in the
|
. For non-default usage, see the BlueOrange example in this help page.
... |
Other arguments are ignored. |
BrewerPaletteName , name
|
|
middle.color |
Darker middle color than the default
|
These are support functions for the plot.likert
function.
Please see plot.likert
for details.
likertColor
uses by default the diverge_hcl
diverging palette defined by the argumentcolorFunctionOption="lighter"
.
likertColorBrewer
by default uses the "RdBu"
diverging palette from RColorBrewer
.
ColorSet
returns a vector of integers, one per each level,
corresponding to the strength of the levels from Disagree to Agree.
For balanced levels, such asc("Disagree Strongly", "Disagree Weakly", "Agree
Weakly", "Agree Strongly")
,
corresponding to nc=4,
ReferenceZero=2.5
, it returns -2 -1 1 2
.
For unbalanced levels, such as c("Disagree", "Neutral", "Agree
Weakly", "Agree Strongly")
, corresponding to nc=4,
ReferenceZero=2
, it returns -1 0 1 2
.
likertColor
returns a subset of a palette constructed by
either diverge_hcl
or
sequential_hcl
in the
colorspace package.
The subset corresponds to the levels specified by ColorSet
.
brewer.pal.likert
returns a
RColorBrewer
palette.
likertColorBrewer
returns a subset of a palette constructed by
brewer.pal.likert
.
The subset corresponds to the levels specified by ColorSet
.
Richard M. Heiberger, with contributions from Naomi B. Robbins <[email protected]>.
Maintainer: Richard M. Heiberger <[email protected]>
brewer.pal.likert(4, "RdBu") brewer.pal.likert(5, "RdBu") ColorSet(4) ColorSet(4, 2) likertColor(4) likertColor(4, 2.5) ## same as above likertColor(4, 2) ## one negative level and two positive levels: default likertColor(5, 3)[-2] ## one negative level and two positive levels: stronger negative ## Not run: ## Examples illustrating the six predefined likertColor palettes, and how ## to define additional hcl color palettes for use with the likert functions. data(ProfDiv) ProfDiv.df <- data.frame(ProfDiv) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="default") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="flatter") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="default") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="flatter") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE) likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="default") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="flatter") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="default") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="flatter") likertMosaic(ProfDiv.df) likertMosaic(ProfDiv.df, colorFunctionOption="default") likertMosaic(ProfDiv.df, colorFunctionOption="flatter") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl", colorFunctionOption="default") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl", colorFunctionOption="flatter") ## specify an hcl palette for use with the likert functions. BlueOrange <- likertColor(nc=4, ReferenceZero=NULL, colorFunction="diverge_hcl", colorFunctionArgs= list(h=c(246, 40), c=96, l=c(65,90), power=1.5)) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, col=BlueOrange) ## End(Not run)
brewer.pal.likert(4, "RdBu") brewer.pal.likert(5, "RdBu") ColorSet(4) ColorSet(4, 2) likertColor(4) likertColor(4, 2.5) ## same as above likertColor(4, 2) ## one negative level and two positive levels: default likertColor(5, 3)[-2] ## one negative level and two positive levels: stronger negative ## Not run: ## Examples illustrating the six predefined likertColor palettes, and how ## to define additional hcl color palettes for use with the likert functions. data(ProfDiv) ProfDiv.df <- data.frame(ProfDiv) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="default") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="flatter") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="default") likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="flatter") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE) likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="default") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunctionOption="flatter") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="default") likert(ProfDiv, horizontal=FALSE, positive.order=FALSE, colorFunction="sequential_hcl", colorFunctionOption="flatter") likertMosaic(ProfDiv.df) likertMosaic(ProfDiv.df, colorFunctionOption="default") likertMosaic(ProfDiv.df, colorFunctionOption="flatter") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl", colorFunctionOption="default") likertMosaic(ProfDiv.df, colorFunction="sequential_hcl", colorFunctionOption="flatter") ## specify an hcl palette for use with the likert functions. BlueOrange <- likertColor(nc=4, ReferenceZero=NULL, colorFunction="diverge_hcl", colorFunctionArgs= list(h=c(246, 40), c=96, l=c(65,90), power=1.5)) likert( ~ . , ProfDiv.df, horizontal=FALSE, positive.order=FALSE, col=BlueOrange) ## End(Not run)
Constructs and plots diverging stacked barcharts for Likert, semantic
differential, rating scale data, and population pyramids,
.based on mosaic
as the plotting style.
likertMosaic(x, ...) ## S3 method for class 'formula' likertMosaic(x, data, ReferenceZero = NULL, spacing=NULL, ..., between.y = c(1.2, 0.3)) ## S3 method for class 'array' likertMosaic(x, ReferenceZero = NULL, col = NULL, main = NULL, ..., as.percent = FALSE, variable.width = NULL, positive.order = FALSE, Conditions = NULL, x.legend = list(text = list(dimnames(x)[[ndim]]), columns = x.dim[ndim], space = "bottom", size = 2, cex = 0.8, between = 0.6, rect= list(col = col, border = "white")), legend.y = 0.05, spacing = spacing_highlighting, split_vertical = c(TRUE, FALSE), margins = c(3, 2, 4, 22), keep_aspect = FALSE, rot_labels = c(0, 0, 90, 0), just_labels = c("center", "center", "center", "right"), labels = c(TRUE, TRUE, FALSE, TRUE), varnames = FALSE, zero_size = 0, gp = gpar(fill = col.extended, col = 0), colorFunction="diverge_hcl", colorFunctionOption="lighter") ## S3 method for class 'data.frame' likertMosaic(x, ...) ## Default S3 method: likertMosaic(x, ...) ## most likely for a vector ## S3 method for class 'list' likertMosaic(x, ...) ## S3 method for class 'matrix' likertMosaic(x, ..., split_vertical = c(FALSE, TRUE), rot_labels = c(90, 0, 0, 0), just_labels = c("left", "center", "center", "right"), labels = c(TRUE, FALSE))
likertMosaic(x, ...) ## S3 method for class 'formula' likertMosaic(x, data, ReferenceZero = NULL, spacing=NULL, ..., between.y = c(1.2, 0.3)) ## S3 method for class 'array' likertMosaic(x, ReferenceZero = NULL, col = NULL, main = NULL, ..., as.percent = FALSE, variable.width = NULL, positive.order = FALSE, Conditions = NULL, x.legend = list(text = list(dimnames(x)[[ndim]]), columns = x.dim[ndim], space = "bottom", size = 2, cex = 0.8, between = 0.6, rect= list(col = col, border = "white")), legend.y = 0.05, spacing = spacing_highlighting, split_vertical = c(TRUE, FALSE), margins = c(3, 2, 4, 22), keep_aspect = FALSE, rot_labels = c(0, 0, 90, 0), just_labels = c("center", "center", "center", "right"), labels = c(TRUE, TRUE, FALSE, TRUE), varnames = FALSE, zero_size = 0, gp = gpar(fill = col.extended, col = 0), colorFunction="diverge_hcl", colorFunctionOption="lighter") ## S3 method for class 'data.frame' likertMosaic(x, ...) ## Default S3 method: likertMosaic(x, ...) ## most likely for a vector ## S3 method for class 'list' likertMosaic(x, ...) ## S3 method for class 'matrix' likertMosaic(x, ..., split_vertical = c(FALSE, TRUE), rot_labels = c(90, 0, 0, 0), just_labels = c("left", "center", "center", "right"), labels = c(TRUE, FALSE))
x |
For the formula method, a model formula. Otherwise,
any numeric object stored as a vector, matrix, array,
data.frame, table, ftable,
structable (as defined in the |
data |
For the formula method, a |
ReferenceZero |
Numeric scalar or |
positive.order |
If |
as.percent |
When |
variable.width |
When |
col |
Colors for the bars. With the default value |
colorFunction , colorFunctionOption
|
See |
main |
|
... |
Additional arguments, passed to the next method and possibly all the way
to |
Conditions |
Factor used to divide the rows of the plot into sets of rows
corresponding to levels of Condition. In the formula method, the
conditions are the factors appearing after the |
between.y |
vertical spacing between bars. |
x.legend |
Description of legend using the terminology and conventions of the
|
legend.y |
Adjust vertical location of legend. |
spacing , split_vertical , margins , keep_aspect , rot_labels , just_labels , labels
|
Please see |
varnames , zero_size , gp
|
Please see |
The counts (or percentages) of respondents on each row who agree with
the statement are shown to the right of the zero line; the counts (or
percentages) who disagree are shown to the left. The counts (or
percentages) for respondents who neither agree nor disagree are split
down the middle and are shown in a neutral color. The neutral category
is omitted when the scale has an even number of choices.
It is difficult to compare
lengths without a common baseline. In this situation, we are primarily
interested in the total count (or percent) to the right or left of the
zero line; the breakdown into strongly or not is of lesser interest so
that the primary comparisons do have a common baseline of zero. The
rows within each panel are displayed in their original order by
default. If the argument positive.order=TRUE
is specified, the rows
are ordered by the counts (or percentages) who agree.
Diverging stacked barcharts are also called "two-directional stacked barcharts". Some authors use the term "floating barcharts" for vertical diverging stacked barcharts and the term "sliding barcharts" for horizontal diverging stacked barcharts.
All items in a list of named two-dimensional objects must have the
same number of columns. If the items have different column names, the
column names of the last item in the list will be used in the key. If
the dimnames of the matrices are named, the names will be used in the
plot. It is possible to produce a likert plot with a list of objects
with different numbers of columns, but not with the
plot.likert.list
method. These must be done manually by using
the ResizeEtc
function on each of the individual likert
plots. The difficulty is that the legend is based on the last item in
the list and will have the wrong number of values for some of the
panels.
A single data.frame x
will be plotted as data.matrix(x)
;
therefore factor columns will be converted to integers and character
columns will become NA
and will be plotted as if they had value
0. A data.frame with only numeric columns will work in a named list.
A data.frame with factors or characters won't work in a named list.
ftable and structable arguments x
will be plotted as
as.table(x)
. This changes the display sequence.
Therefore the user will probably want to use aperm
on the
ftable or structable before using plot.likert
.
Please see strucplot
for a description of the
returned object.
The functions described here are currently missing the following features:
no axis ticks, number, nor axis label for the x axis
no zero reference line
no right-axis labels for Row Count Totals
no strip.left labels for grouping by Conditions
In Figure 8 and 9 (HH/demo/likertMosaic-paper.r
),
no control of the thickness of the bars
All bars are horizontal.
No borders on the overall plot nor on the panels in plots with grouping by Conditions
No control of between=list(x=number)
cex
for labeling
border on empty boxes
I am using a lattice legend, not a native strucplot legend
Richard M. Heiberger, with contributions from Naomi B. Robbins <[email protected]>.
Maintainer: Richard M. Heiberger <[email protected]>
Richard M. Heiberger, Naomi B. Robbins (2014)., "Design of Diverging Stacked Bar Charts for Likert Scales and Other Applications", Journal of Statistical Software, 57(5), 1–32, doi:10.18637/jss.v057.i05.
Richard Heiberger and Naomi Robbins (2011), "Alternative to Charles Blow's Figure in \"Newt's War on Poor Children\"", Forbes OnLine, December 20, 2011. https://www.forbes.com/sites/naomirobbins/2011/12/20/alternative-to-charles-blows-figure-in-newts-war-on-poor-children-2/
Naomi Robbins (2011), "Visualizing Data: Challenges to
Presentation of Quality Graphics—and Solutions", Amstat News,
September 2011, 28–30.
http://magazine.amstat.org/blog/2011/09/01/visualizingdata/
Luo, Amy and Tim Keyes (2005). "Second Set of Results in from the Career Track Member Survey," Amstat News. Arlington, VA: American Statistical Association.
## See file HH/demo/likertMosaic-paper.r for a complete set of examples. ## Not run: require(vcd) data(ProfChal) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?") likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE, positive.order=TRUE) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE, variable.width=TRUE) EmpRows <- ProfChal$Subtable == "Employment sector" ProfChal2 <- ProfChal[EmpRows, 1:5] rownames(ProfChal2) <- substr(ProfChal[EmpRows, "Question"], 1, 5) likertMosaic(ProfChal2) likertMosaic(ProfChal2, main="Employment") likertMosaic(ProfChal2, main="Employment", ReferenceZero=0) likertMosaic(ProfChal2, main="Employment", ReferenceZero=3.5) likertMosaic(ProfChal2, main="Employment", ReferenceZero=4) likertMosaic(ProfChal2, main="Employment", ReferenceZero=6) likertMosaic(ProfChal2, main="Employment", positive.order=TRUE) likertMosaic(ProfChal2, main="Employment", variable.width=TRUE) likertMosaic(~ ., data.frame(ProfChal2), main="Employment", positive.order=TRUE) likertMosaic(~ ., data.frame(ProfChal2), main="Employment", variable.width=TRUE) likert(~ ., data.frame(ProfChal2), main="Employment", variable.width=TRUE) data(SFF8121) likertMosaic(aperm(SFF8121, c(3,1,2))) ## End(Not run)
## See file HH/demo/likertMosaic-paper.r for a complete set of examples. ## Not run: require(vcd) data(ProfChal) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?") likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE, positive.order=TRUE) likertMosaic(Question ~ . | Subtable, ProfChal, main="Is your job professionally challenging?", as.percent=TRUE, variable.width=TRUE) EmpRows <- ProfChal$Subtable == "Employment sector" ProfChal2 <- ProfChal[EmpRows, 1:5] rownames(ProfChal2) <- substr(ProfChal[EmpRows, "Question"], 1, 5) likertMosaic(ProfChal2) likertMosaic(ProfChal2, main="Employment") likertMosaic(ProfChal2, main="Employment", ReferenceZero=0) likertMosaic(ProfChal2, main="Employment", ReferenceZero=3.5) likertMosaic(ProfChal2, main="Employment", ReferenceZero=4) likertMosaic(ProfChal2, main="Employment", ReferenceZero=6) likertMosaic(ProfChal2, main="Employment", positive.order=TRUE) likertMosaic(ProfChal2, main="Employment", variable.width=TRUE) likertMosaic(~ ., data.frame(ProfChal2), main="Employment", positive.order=TRUE) likertMosaic(~ ., data.frame(ProfChal2), main="Employment", variable.width=TRUE) likert(~ ., data.frame(ProfChal2), main="Employment", variable.width=TRUE) data(SFF8121) likertMosaic(aperm(SFF8121, c(3,1,2))) ## End(Not run)
Display likert plots with percents in the first column of panels and counts in the second column of panels. Order the rows either in their original order or by the positive order of the percent display.
LikertPercentCountColumns( x, data, px=list( ## defaults designed for long QuestionName values LL=c(.00, .50), ## and 7in x 7in window LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00)), ..., QuestionName="Question", as.percent="Capture and then ignore this argument", positive.order=FALSE)
LikertPercentCountColumns( x, data, px=list( ## defaults designed for long QuestionName values LL=c(.00, .50), ## and 7in x 7in window LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00)), ..., QuestionName="Question", as.percent="Capture and then ignore this argument", positive.order=FALSE)
x , data , positive.order
|
formula, data.frame, Logical.
See |
... |
other arguments that can be used for |
px |
|
as.percent |
Capture this argument and ignore it. The
|
QuestionName |
Character string containing the name of the
column in |
A "TwoTrellisColumns5"
object, consisting of a list
containing the constructed left, middle, and right trellis objects,
and an attribute containing the px
value.
See as.TwoTrellisColumns5
for details.
Richard M. Heiberger <[email protected]>
## These are based on the Professional Challenges example in ?likert data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## See ?print.TwoTrellisColumns for this example using the original ordering ## Order both the plot of the count plot and the percent plot by the ## positive.order of the percent plot. LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Not run: ## Retain original order of the Question variable LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), main="Is your job professionally challenging?") ## Order both the plot of the count plot and the percent plot by the ## positive.order of the percent plot. ## Just the "Employment sector". LPCCEs <- LikertPercentCountColumns(Question ~ . , ProfChal[ProfChal$Subtable == "Employment sector", -7], ylab=NULL, between=list(y=0), par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?\nEmployment sector", px=list( ## defaults designed for long QuestionName values LL=c(.00, .50), ## and 7in x 7in window LP=c(.49, .70), ML=c(.50, .51), ## arbitrary, visually center the labels and legend RP=c(.71, .84), RL=c(.87, 1.00))) LPCCEs$RP$x.scales$at <- c(0,100,200) LPCCEs$RP$x.scales$labels <- c(0,100,200) LPCCEs ## End(Not run)
## These are based on the Professional Challenges example in ?likert data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## See ?print.TwoTrellisColumns for this example using the original ordering ## Order both the plot of the count plot and the percent plot by the ## positive.order of the percent plot. LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Not run: ## Retain original order of the Question variable LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), main="Is your job professionally challenging?") ## Order both the plot of the count plot and the percent plot by the ## positive.order of the percent plot. ## Just the "Employment sector". LPCCEs <- LikertPercentCountColumns(Question ~ . , ProfChal[ProfChal$Subtable == "Employment sector", -7], ylab=NULL, between=list(y=0), par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?\nEmployment sector", px=list( ## defaults designed for long QuestionName values LL=c(.00, .50), ## and 7in x 7in window LP=c(.49, .70), ML=c(.50, .51), ## arbitrary, visually center the labels and legend RP=c(.71, .84), RL=c(.87, 1.00))) LPCCEs$RP$x.scales$at <- c(0,100,200) LPCCEs$RP$x.scales$labels <- c(0,100,200) LPCCEs ## End(Not run)
Special case wrapper for likert() when multiple columns are to have the same bar thicknesses. Uses formula with one or two conditioning variables.
likertWeighted(x, ...) ## generic ## S3 method for class 'array' likertWeighted(x, ..., C = 1, Q = 3, R = 2) ## array ## Default S3 method: likertWeighted(x, ...) ## matrix, table, data.frame ## S3 method for class 'formula' likertWeighted(x, data, xlim=c(-100, 100), scales=list(y=list(relation="free", cex=1.3), x=list(at=seq(-100, 100, 50), labels=abs(seq(-100, 100, 50)), cex=.5)), box.ratio=1000, as.percent=TRUE, rightAxis=FALSE, between=list(x=1, y=0), strip=FALSE, strip.left=FALSE, par.settings=list(clip=list(panel="off")), h.resizePanels=1, auto.key.title=NULL, auto.key.columns=dim(data)[[2]] - NumberOfConditioningVariables(formula), ## excludes conditioning variables auto.key.cex=1.2, auto.key.cex.title=1.2, auto.key.lines.title=3, ylab=NULL, axis.top=dimnames(result)[[1]], ## Questions axis.top.row=1, ...)
likertWeighted(x, ...) ## generic ## S3 method for class 'array' likertWeighted(x, ..., C = 1, Q = 3, R = 2) ## array ## Default S3 method: likertWeighted(x, ...) ## matrix, table, data.frame ## S3 method for class 'formula' likertWeighted(x, data, xlim=c(-100, 100), scales=list(y=list(relation="free", cex=1.3), x=list(at=seq(-100, 100, 50), labels=abs(seq(-100, 100, 50)), cex=.5)), box.ratio=1000, as.percent=TRUE, rightAxis=FALSE, between=list(x=1, y=0), strip=FALSE, strip.left=FALSE, par.settings=list(clip=list(panel="off")), h.resizePanels=1, auto.key.title=NULL, auto.key.columns=dim(data)[[2]] - NumberOfConditioningVariables(formula), ## excludes conditioning variables auto.key.cex=1.2, auto.key.cex.title=1.2, auto.key.lines.title=3, ylab=NULL, axis.top=dimnames(result)[[1]], ## Questions axis.top.row=1, ...)
x |
For the default method, a matrix or data.frame or two-dimensional table. For the array method, a two- or-three-dimensional array. For the formula method, a formula. |
formula |
Standard trellis formula, usually |
data |
A |
C , R , Q
|
Integers, one each of 1,2,3; positions of the three dimensions. Used in
|
xlim , between , strip , strip.left , par.settings , ylab
|
See |
scales |
See |
box.ratio |
See |
as.percent , rightAxis , ... , h.resizePanels
|
First see the formula method for |
auto.key.title , auto.key.columns , auto.key.cex , auto.key.cex.title , auto.key.lines.title
|
Values which will be used in |
axis.top |
Label to be placed at |
axis.top.row |
Which rows will have |
A likert
plot as a "trellis"
object.
Richard M. Heiberger <[email protected]>
## simplest 2D example tmp <- matrix(1:12, 3, 4, dimnames=list(c("A","B","C"), c(letters[4:7]))) * c(1,2,3) tmp rowSums(tmp) likertWeighted(tmp, h.resizePanels=rowSums(tmp), main="likertWeighted, simplest example, defaults to Percent, specified row thicknesses") ## Same example with explicit use of the formula method ## (default method does this for you). tmpdd <- data.frame(tmp, row=row.names(tmp)) tmpdd likertWeighted(~ . | row, tmpdd, ## tmpdd h.resizePanels=rowSums(tmp), ## tmp main="likertWeighted, same example but with explicit formula method") ## show subgroups likertWeighted(tmp, h.resizePanels=rowSums(tmp), between=list(y=c(0, 1)), ylab=c("C in its own group","A and B together"), main="between=list(y=c(0,1) ## standard lattice between argument Adjacent A and B with y.between = 0 are in the same bordered group. Adjacent B and C with y.between != 0 are in different bordered groups.") ## simplest 3D example ## This is natural when multiple questions are asked of the ## same set of respondents in a survey. ## This example simulates that situation. ## tmp3D <- abind::abind(h=tmp, i=tmp, j=tmp, along=3) tmp3D[1,,"i"] <- tmp3D[1,c(4,2,1,3),"h"] tmp3D[2,,"i"] <- tmp3D[2,c(2,4,3,1),"h"] tmp3D[3,,"i"] <- tmp3D[3,c(4,1,2,3),"h"] tmp3D[1,,"j"] <- tmp3D[1,c(4,3,2,1),"h"] tmp3D[2,,"j"] <- tmp3D[2,c(1,4,3,2),"h"] tmp3D[3,,"j"] <- tmp3D[3,c(2,4,3,1),"h"] ## now rowSums(tmp3D[,,1]) == rowSums(tmp3D[,,2]) rowSums(tmp3D[,,1]) == rowSums(tmp3D[,,3]) likertWeighted(tmp3D, h.resizePanels=rowSums(tmp3D[,,1]), main="simplest 3D example, array method") likertWeighted(tmp3D, h.resizePanels=rowSums(tmp3D[,,1]), between=list(x=1, y=c(0, 1)), main="simplest 3D example, array method, with subgroups") ## Same example with explicit use of the formula method ## (array method does this for you). tmp3Ddf <- toCQxR(tmp3D) dimnames(tmp3Ddf) tmp3Ddf likertWeighted(~ . | group + row, tmp3Ddf, h.resizePanels=rowSums(tmp3D[,,1]), main="simplest 3D example, formula method")
## simplest 2D example tmp <- matrix(1:12, 3, 4, dimnames=list(c("A","B","C"), c(letters[4:7]))) * c(1,2,3) tmp rowSums(tmp) likertWeighted(tmp, h.resizePanels=rowSums(tmp), main="likertWeighted, simplest example, defaults to Percent, specified row thicknesses") ## Same example with explicit use of the formula method ## (default method does this for you). tmpdd <- data.frame(tmp, row=row.names(tmp)) tmpdd likertWeighted(~ . | row, tmpdd, ## tmpdd h.resizePanels=rowSums(tmp), ## tmp main="likertWeighted, same example but with explicit formula method") ## show subgroups likertWeighted(tmp, h.resizePanels=rowSums(tmp), between=list(y=c(0, 1)), ylab=c("C in its own group","A and B together"), main="between=list(y=c(0,1) ## standard lattice between argument Adjacent A and B with y.between = 0 are in the same bordered group. Adjacent B and C with y.between != 0 are in different bordered groups.") ## simplest 3D example ## This is natural when multiple questions are asked of the ## same set of respondents in a survey. ## This example simulates that situation. ## tmp3D <- abind::abind(h=tmp, i=tmp, j=tmp, along=3) tmp3D[1,,"i"] <- tmp3D[1,c(4,2,1,3),"h"] tmp3D[2,,"i"] <- tmp3D[2,c(2,4,3,1),"h"] tmp3D[3,,"i"] <- tmp3D[3,c(4,1,2,3),"h"] tmp3D[1,,"j"] <- tmp3D[1,c(4,3,2,1),"h"] tmp3D[2,,"j"] <- tmp3D[2,c(1,4,3,2),"h"] tmp3D[3,,"j"] <- tmp3D[3,c(2,4,3,1),"h"] ## now rowSums(tmp3D[,,1]) == rowSums(tmp3D[,,2]) rowSums(tmp3D[,,1]) == rowSums(tmp3D[,,3]) likertWeighted(tmp3D, h.resizePanels=rowSums(tmp3D[,,1]), main="simplest 3D example, array method") likertWeighted(tmp3D, h.resizePanels=rowSums(tmp3D[,,1]), between=list(x=1, y=c(0, 1)), main="simplest 3D example, array method, with subgroups") ## Same example with explicit use of the formula method ## (array method does this for you). tmp3Ddf <- toCQxR(tmp3D) dimnames(tmp3Ddf) tmp3Ddf likertWeighted(~ . | group + row, tmp3Ddf, h.resizePanels=rowSums(tmp3D[,,1]), main="simplest 3D example, formula method")
Case statistics for regression analysis.
case.lm
calculates the statistics.
plot.case
plots the cases, one statistic per panel, and
illustrates and flags all observations for which the standard
thresholds are exceeded. plot.case
returns an object with
class c("trellis.case", "trellis")
containing the plot and the row.names of the
flagged observations. The object is printed by a method which
displays the set of graphs and prints the list of flagged cases.
panel.case
is a panel function for plot.case
.
case(fit, ...) ## S3 method for class 'lm' case(fit, lms = summary.lm(fit), lmi = lm.influence(fit), ...) ## S3 method for class 'case' plot(x, fit, which=c("stu.res","si","h","cook","dffits", dimnames(x)[[2]][-(1:8)]), ##DFBETAS between.in=list(y=4, x=9), cex.threshold=1.2, main.in=list( paste(deparse(fit$call), collapse=""), cex=main.cex), sigma.in=summary.lm(fit)$sigma, p.in=summary.lm(fit)$df[1]-1, main.cex=NULL, ...) panel.case(x, y, subscripts, rownames, group.names, thresh, case.large, nn, pp, ss, cex.threshold, ...)
case(fit, ...) ## S3 method for class 'lm' case(fit, lms = summary.lm(fit), lmi = lm.influence(fit), ...) ## S3 method for class 'case' plot(x, fit, which=c("stu.res","si","h","cook","dffits", dimnames(x)[[2]][-(1:8)]), ##DFBETAS between.in=list(y=4, x=9), cex.threshold=1.2, main.in=list( paste(deparse(fit$call), collapse=""), cex=main.cex), sigma.in=summary.lm(fit)$sigma, p.in=summary.lm(fit)$df[1]-1, main.cex=NULL, ...) panel.case(x, y, subscripts, rownames, group.names, thresh, case.large, nn, pp, ss, cex.threshold, ...)
fit |
|
lms |
|
lmi |
|
x |
In |
which |
In |
between.in |
|
cex.threshold |
Multiplier for |
main.in |
|
sigma.in |
standard error for the |
p.in |
The number of degrees of freedom associated with the fitted model. |
main.cex |
|
... |
other arguments to |
y |
the y variable to be plotted. |
thresh |
Named list of lists. Each list contains the components threshold ($y$-locations where a reference line will be drawn), thresh.label (the right-axis labels for the reference lines), thresh.id (the bounds defining "Noteworthy Observations"). |
case.large |
Named list of "Noteworthy Observations". |
nn |
Number of rows in original dataset. |
pp |
The number of degrees of freedom associated with the fitted model. |
ss |
Standard error for the |
subscripts |
trellis/lattice argument, position in the reshaped
dataset constructed by |
rownames |
row name in the original data.frame. |
group.names |
names of the individual statistics. |
lm.influence
is part of S-Plus and R
case.lm
and plot.case
are based on:
Section 4.3.3 "Influence of Individual Obervations
in Chambers and Hastie", Statistical Models in S.
case.lm
returns a matrix, with one row for each observation
in the original dataset. The columns contain the diagnostic statistics:
e
(residuals),
h
* (hat diagonals),
si
* (deleted standard deviation),
sta.res
(standardized residuals),
stu.res
* (Studentized deleted resididuals),
dffit
(difference in fits, change in predicted y when
observation i is deleted),
dffits
* (standardized difference in fits, standardized change
in predicted y when observation i is deleted),
cook
* (Cook's distance),
and DFBETAs* (standardized difference in regression coefficients when
observation i is deleted, one for each column of the x-matrix,
including the intercept).
plot.case
returns a c("trellis.case", "trellis")
object
containing the plot
(including the starred columns by default) and also retains the
row.names of the flagged observations in the
$panel.args.common$case.large
component. The print method for the c("trellis.case",
"trellis")
object prints the graph and the list of flagged observations.
panel.case
is a panel function for plot.case
.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(kidney) kidney2.lm <- lm(clearance ~ concent + age + weight + concent*age, data=kidney, na.action=na.exclude) ## recommended kidney2.case <- case(kidney2.lm) ## this picture looks much better in portrait, specification is device dependent plot(kidney2.case, kidney2.lm, par.strip.text=list(cex=.9), layout=c(2,3))
data(kidney) kidney2.lm <- lm(clearance ~ concent + age + weight + concent*age, data=kidney, na.action=na.exclude) ## recommended kidney2.case <- case(kidney2.lm) ## this picture looks much better in portrait, specification is device dependent plot(kidney2.case, kidney2.lm, par.strip.text=list(cex=.9), layout=c(2,3))
The regsubsets
function in the leaps
package finds the
model with the highest adjusted . This function evaluates the full
lm
object for that model.
lm.regsubsets(object, model.number, ...)
lm.regsubsets(object, model.number, ...)
object |
An object of class |
model.number |
Index number generated by |
... |
Other arguments. |
"lm"
object for the selected model.
Richard M. Heiberger <[email protected]>
lmatPairwise
lmatPairwise(x, ...) ## S3 method for class 'matrix' lmatPairwise(x, levels, ...) ## S3 method for class 'glht' lmatPairwise(x, ...) ## S3 method for class 'mmc.multicomp' lmatPairwise(x, ...) ## S3 method for class 'mmc' lmatPairwise(x, ...)
lmatPairwise(x, ...) ## S3 method for class 'matrix' lmatPairwise(x, levels, ...) ## S3 method for class 'glht' lmatPairwise(x, ...) ## S3 method for class 'mmc.multicomp' lmatPairwise(x, ...) ## S3 method for class 'mmc' lmatPairwise(x, ...)
x |
x |
... |
... |
levels |
levels |
details
matrix
rmh
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- mmc(catalystm1.aov) lmatPairwise(catalystm.mmc)
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- mmc(catalystm1.aov) lmatPairwise(catalystm.mmc)
lmatRows
finds the row numbers in the lmat (column numbers in the linfct in R)
corresponding to the focus factor. See mmc
for more information.
These are internal functions that the user doesn't see.
They are necessary when the design has more than one factor.
lmatContrast
converts user-specified contrasts of levels of a
factor to the full lmat
or linfct
matrix that carries the
information about other factors and their interactions and covariates.
lmatRows(x, focus) ## S3 method for class 'mmc.multicomp' lmatRows(x, focus) ## S3 method for class 'multicomp' lmatRows(x, focus) ## S3 method for class 'glht' lmatRows(x, focus) ## R only ## S3 method for class 'lm' lmatRows(x, focus) lmatContrast(lmat.none, contrast.matrix)
lmatRows(x, focus) ## S3 method for class 'mmc.multicomp' lmatRows(x, focus) ## S3 method for class 'multicomp' lmatRows(x, focus) ## S3 method for class 'glht' lmatRows(x, focus) ## R only ## S3 method for class 'lm' lmatRows(x, focus) lmatContrast(lmat.none, contrast.matrix)
x |
|
focus |
The name of the term in the ANOVA table for which multiple comparisons are to be constructed. |
lmat.none |
|
contrast.matrix |
Matrix of column contrasts for a factor. The columns are the contrasts, the rows are the levels of the factor. |
The MMC
function are based on glht
in R and on
multicomp
in S-Plus. The two packages have different conventions for specifying
the linear contrasts. The lmatRows
function gives appropriate
values in each system.
For lmatRows
, vector of row numbers of the lmat
,
the matrix of linear contrasts defining the comparisons of interest.
For lmatContrast
, a linear contrast matrix that follows the
conventions of the multiple comparisons package. It has columns for each contrast
specified by the input contrast.matrix
and rows as needed for
the other terms in the model.
Richard M. Heiberger <[email protected]>
## catalystm example ## See ?MMC for more on this example data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- if.R(r=mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")), s=multicomp.mmc(catalystm1.aov, plot=FALSE)) dimnames(catalystm.mmc$mca$lmat)[[1]] lmatRows(catalystm1.aov, focus="catalyst") ## user-specified contrasts catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) zapsmall(lmatContrast(catalystm.mmc$none$lmat, catalystm.lmat))
## catalystm example ## See ?MMC for more on this example data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- if.R(r=mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")), s=multicomp.mmc(catalystm1.aov, plot=FALSE)) dimnames(catalystm.mmc$mca$lmat)[[1]] lmatRows(catalystm1.aov, focus="catalyst") ## user-specified contrasts catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) zapsmall(lmatContrast(catalystm.mmc$none$lmat, catalystm.lmat))
Four types of residual plots for linear models. The first three are redesigns of
plots that stats:::plot.lm
presents.
The first two show the positive residuals in col[2]
and the
negative residuals
in color col[1]
. The third and fourth use color col[1]
.
The fourth is based on an S-Plus
panel that R\ doesn't provide.
lmplot(lm.object, ..., main=NULL, col=trellis.par.get("superpose.symbol")$col[1:2], ylim=NULL)
lmplot(lm.object, ..., main=NULL, col=trellis.par.get("superpose.symbol")$col[1:2], ylim=NULL)
lm.object |
Linear model object. See |
col |
Vector of color names. Only the first two are used.
If not specified, then
|
main |
standard |
ylim |
standard lattice argument.
It is used as specified for the |
... |
Other arguments, currently ignored. |
The trellis plots from the four functions residVSfitted
,
scaleLocation
, diagQQ
, diagplot5new
are displayed on the current device in a coordinated display.
A list of three trellis objects is returned invisibly, the first
contains the result of residVSfitted
and
scaleLocation
together. The second diagQQ
,
and the third diagplot5new
.
Richard M. Heiberger <[email protected]>
residVSfitted
, scaleLocation
,
diagQQ
, diagplot5new
.
tmp <- data.frame(y=rnorm(100), x1=rnorm(100), x2=rnorm(100)) tmp.lm <- lm(y ~ x1 + x2, data=tmp) lmplot(tmp.lm)
tmp <- data.frame(y=rnorm(100), x1=rnorm(100), x2=rnorm(100)) tmp.lm <- lm(y ~ x1 + x2, data=tmp) lmplot(tmp.lm)
Logistic and odds functions and their inverses.
logit(p) antilogit(x) odds(p) antiodds(o)
logit(p) antilogit(x) odds(p) antiodds(o)
p |
Probability value, a vector of numbers between 0 and 1, inclusive. |
x |
Real number, a vector of numbers between |
o |
Real number, a vector of numbers between |
Vector of real values log(p/(1-p))
for logit
.
Vector of probabilities exp(x)/(1+exp(x))
for antilogit
with
boundary values of -Inf
and Inf
for x
correctly handled.
Vector of real values p/(1-p)
for odds
.
Vector of probabilities o/(o+1)
for antiodds
with the
boundary value of Inf
for o
correctly handled.
Richard M. Heiberger <[email protected]>
logit(seq(0, 1, .1)) antilogit(logit(seq(0, 1, .1))) odds(seq(0, 1, .1)) antiodds(odds(seq(0, 1, .1)))
logit(seq(0, 1, .1)) antilogit(logit(seq(0, 1, .1))) odds(seq(0, 1, .1)) antiodds(odds(seq(0, 1, .1)))
matrix.trellis
matrix.trellis(x = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) ## S3 method for class 'trellis' as.matrix(x, ..., row = FALSE, yname)
matrix.trellis(x = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) ## S3 method for class 'trellis' as.matrix(x, ..., row = FALSE, yname)
x |
x |
nrow , ncol , byrow , dimnames
|
See |
row |
Logical. The default is |
yname |
Character. Provides the name of the generated conditioning factor. |
... |
Other arguments are ignored. |
matrix.trellis
lets the user specify nrow
and ncol
.
as.matrix.trellis
produces either be a single column (by
default) or a single row.
trellis
object with length(dim(x)) == 2
and specified nrow and ncol.
Richard M. Heiberger <[email protected]>
tmp <- data.frame(a=1:3, b=c(4,5,7), c=5:7, d=c(8, 9, 12), e=9:11) tmp a1 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, main="a1") a1 dim(a1) a2 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, scales=list(relation="free"), main="a2") a2 dim(a2) try(combineLimits(a2)) combineLimits.trellisvector(a2) combineLimits.trellisvector(update(a2, layout=c(3,2))) a21 <- matrix.trellis(a2, ncol=3, nrow=2, byrow=TRUE) a21 <- update(a21, main="a21") a21 dim(a21) a21$x.scales$at combineLimits(a21) a22 <- update(a21, main="a22") a22$x.scales$at <- list(FALSE, FALSE, FALSE, NULL, NULL, NULL) a22$y.scales$at <- list(FALSE, NULL, NULL, FALSE, NULL, NULL) a22 a23 <- useOuterStrips(combineLimits(a21)) a23 <- update(a23, main="a23") a23 a23$condlevels a23$condlevels <- list(letters[3:5], letters[1:2]) a23 a24 <- resizePanels(update(a23, main="a24"), h=c(3,4), w=c(3,5,3)) a24 a25 <- update(a23, xlab=letters[3:5], ylab.right=letters[1:2], xlab.top="column variables", ylab="row variables", scales=list(x=list(alternating=1), y=list(alternating=2)), main="a25: what I want\nxyplot(a + b ~ c + d + e, data=tmp, outer=TRUE)\nto produce.") a25 as.matrix(a1) as.matrix(a1, yname="abcd") as.matrix(a1, yname="abcd", row=TRUE)
tmp <- data.frame(a=1:3, b=c(4,5,7), c=5:7, d=c(8, 9, 12), e=9:11) tmp a1 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, main="a1") a1 dim(a1) a2 <- xyplot(a + b ~ c + d + e, data=tmp, outer=TRUE, scales=list(relation="free"), main="a2") a2 dim(a2) try(combineLimits(a2)) combineLimits.trellisvector(a2) combineLimits.trellisvector(update(a2, layout=c(3,2))) a21 <- matrix.trellis(a2, ncol=3, nrow=2, byrow=TRUE) a21 <- update(a21, main="a21") a21 dim(a21) a21$x.scales$at combineLimits(a21) a22 <- update(a21, main="a22") a22$x.scales$at <- list(FALSE, FALSE, FALSE, NULL, NULL, NULL) a22$y.scales$at <- list(FALSE, NULL, NULL, FALSE, NULL, NULL) a22 a23 <- useOuterStrips(combineLimits(a21)) a23 <- update(a23, main="a23") a23 a23$condlevels a23$condlevels <- list(letters[3:5], letters[1:2]) a23 a24 <- resizePanels(update(a23, main="a24"), h=c(3,4), w=c(3,5,3)) a24 a25 <- update(a23, xlab=letters[3:5], ylab.right=letters[1:2], xlab.top="column variables", ylab="row variables", scales=list(x=list(alternating=1), y=list(alternating=2)), main="a25: what I want\nxyplot(a + b ~ c + d + e, data=tmp, outer=TRUE)\nto produce.") a25 as.matrix(a1) as.matrix(a1, yname="abcd") as.matrix(a1, yname="abcd", row=TRUE)
MCA multiple comparisons analysis (pairwise). We calculate the contrast matrix for all pairwise comparisons, taking account of covariates and interactions.
mcalinfct(model, focus, mmm.data=model$model, formula.in=terms(model), linfct.Means= multcomp.meanslinfct(model, focus, mmm.data, formula.in, contrasts.arg=model$contrasts), type="Tukey" )
mcalinfct(model, focus, mmm.data=model$model, formula.in=terms(model), linfct.Means= multcomp.meanslinfct(model, focus, mmm.data, formula.in, contrasts.arg=model$contrasts), type="Tukey" )
model |
|
focus |
name of one of the factors in the model, as a character object. |
mmm.data |
|
formula.in |
|
linfct.Means |
Contrast matrix for the adjusted means of each level of the focus factor. Normally, the default is the correct value. |
type |
Name of the multiple comparison procedure to be used.
See |
Matrix to be used as a value for the linfct
argument to
glht
.
This function provides results similar to the
mcp(focusname="Tukey")
argument to glht
.
I think it provides better values for covariate and interaction terms.
Richard M. Heiberger <[email protected]>
## See the examples in HH/scripts/MMC.cc176.R
## See the examples in HH/scripts/MMC.cc176.R
Constructs a "mmc.multicomp"
object from the formula and
other arguments. The constructed object must be explicitly plotted
with the mmcplot
function.
mmc(model, ...) ## R ## S3 method for class 'glht' mmc(model, ...) ## Default S3 method: mmc(model, ## lm object linfct=NULL, focus= if (is.null(linfct)) { if (length(model$contrasts)==1) names(model$contrasts) else stop("focus or linfct must be specified.") } else { if (is.null(names(linfct))) stop("focus must be specified.") else names(linfct) }, focus.lmat, ylabel=deparse(terms(model)[[2]]), lmat=if (missing(focus.lmat)) { t(linfct) } else { lmatContrast(t(none.glht$linfct), focus.lmat) }, lmat.rows=lmatRows(model, focus), lmat.scale.abs2=TRUE, estimate.sign=1, order.contrasts=TRUE, level=.95, calpha=NULL, alternative = c("two.sided", "less", "greater"), ... ) multicomp.mmc(x, ## S-Plus focus=dimnames(attr(x$terms,"factors"))[[2]][1], comparisons="mca", lmat, lmat.rows=lmatRows(x, focus), lmat.scale.abs2=TRUE, ry, plot=TRUE, crit.point, iso.name=TRUE, estimate.sign=1, x.offset=0, order.contrasts=TRUE, main, main2, focus.lmat, ...) ## S3 method for class 'mmc.multicomp' x[..., drop = TRUE]
mmc(model, ...) ## R ## S3 method for class 'glht' mmc(model, ...) ## Default S3 method: mmc(model, ## lm object linfct=NULL, focus= if (is.null(linfct)) { if (length(model$contrasts)==1) names(model$contrasts) else stop("focus or linfct must be specified.") } else { if (is.null(names(linfct))) stop("focus must be specified.") else names(linfct) }, focus.lmat, ylabel=deparse(terms(model)[[2]]), lmat=if (missing(focus.lmat)) { t(linfct) } else { lmatContrast(t(none.glht$linfct), focus.lmat) }, lmat.rows=lmatRows(model, focus), lmat.scale.abs2=TRUE, estimate.sign=1, order.contrasts=TRUE, level=.95, calpha=NULL, alternative = c("two.sided", "less", "greater"), ... ) multicomp.mmc(x, ## S-Plus focus=dimnames(attr(x$terms,"factors"))[[2]][1], comparisons="mca", lmat, lmat.rows=lmatRows(x, focus), lmat.scale.abs2=TRUE, ry, plot=TRUE, crit.point, iso.name=TRUE, estimate.sign=1, x.offset=0, order.contrasts=TRUE, main, main2, focus.lmat, ...) ## S3 method for class 'mmc.multicomp' x[..., drop = TRUE]
model |
|
ylabel |
name of the response variable. |
lmat |
contrast matrix as in the S-Plus |
lmat.rows |
rows in |
focus |
define the factor to compute contrasts of.
In R this argument often can be used to simplify the call.
The statement |
focus.lmat |
R only. Contrast matrix used in the user-specified
comparisons of the |
linfct |
In R, see
|
... |
other arguments. |
comparisons |
argument to |
lmat.scale.abs2 |
logical, scale the contrasts in the columns of
|
estimate.sign |
numeric. If |
order.contrasts |
sort the contrasts in the ( |
alternative |
Direction of alternative hypothesis.
See
in R. S-Plus |
level |
Confidence level. Defaults to 0.95. |
crit.point , calpha
|
critical value for the tests. The value from the
specified |
plot |
logical, display the plot if |
ry , iso.name , x.offset , main , main2
|
arguments to
|
x , drop
|
See |
By default, if lmat
is not specified, we plot the isomeans grid
and the pairwise comparisons for the focus
factor. By default,
we plot the specified contrasts if the lmat
is specified.
Each contrast is plotted at a height which is the weighted average of
the means being compared. The weights are scaled to the sum of their
absolute values equals 2.
We get the right contrasts automatically if the aov is oneway. If we specify an lmat for oneway it must have a leading row of 0.
For any more complex design, we must study the lmat
from the mca
component of the result to see how to construct the lmat
(with the
extra rows as needed) and how to specify the lmat.rows
corresponding to the rows for the focus factor.
mmc
in R works from either an "glht"
object or an
"aov"
object. multicomp.mmc
in S-Plus works from an
"aov"
object.
An "mmc.multicomp"
object contains either the first two or all
three of the "multicomp"
components mca
, none
,
lmat
described here. Each "multicomp"
component in
R also contains a "glht"
object.
mca |
Object containing the pairwise comparisons. |
none |
Object comparing each mean to 0. |
lmat |
Object for the contrasts specified in
the |
"[.mmc.multicomp"
is a subscript method.
The multiple comparisons calculations in R and S-Plus use
completely different functions.
MMC plots in R are constructed by mmc
based on
glht
.
MMC plots in S-Plus are constructed by
multicomp.mmc
based on the S-Plus
multicomp
.
The MMC plot is the same in both systems. The details of getting the plot differ.
Function mmc
calls
glht
and confint.glht
.
With a large number of levels
for the focus factor, the confint
function is exceedingly slow
(80 minutes for 30 levels on 1.5GHz Windows XP). Therefore,
always specify calpha
to reduce the time to under a second for
the same example.
There are two plotting functions for MMC plots. mmcplot
, the
newer lattice-based function, is recommended. mmcplot
,
chooses better default values for it arguments and is better coordinated
with the tiebreaker plot.
The older
plot.mmc.multicomp
, built on base graphics, chooses sensible defaults for its many
arguments, but they still often need manual adjustment. The examples show
several types of adjustments. We have changed the centering and scaling
to avoid overprinting of label information. By default the significant
contrasts are shown in a more intense color than the nonsignificant
contrasts.
We have an option to reduce the color intensity of the isomeans grid.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
Hsu, J. and Peruggia, M. (1994). "Graphical representations of Tukey's multiple comparison method." Journal of Computational and Graphical Statistics, 3:143–161.
mmcplot
, plot.mmc.multicomp
, as.multicomp
## Use mmc with R. ## Use multicomp.mmc with S-Plus. ## data and ANOVA ## catalystm example data(catalystm) bwplot(concent ~ catalyst, data=catalystm, scales=list(cex=1.5), ylab=list("concentration", cex=1.5), xlab=list("catalyst",cex=1.5)) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) catalystm.mca <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) confint(catalystm.mca) plot(catalystm.mca) ## multcomp plot mmcplot(catalystm.mca, focus="catalyst") ## HH plot ## pairwise comparisons catalystm.mmc <- mmc(catalystm1.aov, focus="catalyst") catalystm.mmc ## Not run: ## these three statements are identical for a one-way aov mmc(catalystm1.aov) ## simplest mmc(catalystm1.aov, focus="catalyst") ## generalizes to higher-order designs mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) ## glht arguments ## End(Not run) mmcplot(catalystm.mmc, style="both") ## User-Specified Contrasts ## Row names must include all levels of the factor. ## Column names are the names the user assigns to the contrasts. ## Each column must sum to zero. catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.lmat catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat) catalystm.mmc mmcplot(catalystm.mmc, style="both", type="lmat") ## Not run: ## Dunnett's test ## weightloss example data(weightloss) bwplot(loss ~ group, data=weightloss, scales=list(cex=1.5), ylab=list("Weight Loss", cex=1.5), xlab=list("group",cex=1.5)) weightloss.aov <- aov(loss ~ group, data=weightloss) summary(weightloss.aov) group.count <- table(weightloss$group) tmp.dunnett <- glht(weightloss.aov, linfct=mcp(group=contrMat(group.count, base=4)), alternative="greater") mmcplot(tmp.dunnett, main="contrasts in alphabetical order", focus="group") tmp.dunnett.mmc <- mmc(weightloss.aov, linfct=mcp(group=contrMat(group.count, base=4)), alternative="greater") mmcplot(tmp.dunnett.mmc, main="contrasts ordered by average value of the means\nof the two levels in the contrasts") tmp.dunnett.mmc ## End(Not run) ## Not run: ## two-way ANOVA ## display example data(display) interaction2wt(time ~ emergenc * panel.ordered, data=display) displayf.aov <- aov(time ~ emergenc * panel, data=display) anova(displayf.aov) ## multiple comparisons ## MMC plot displayf.mmc <- mmc(displayf.aov, focus="panel") displayf.mmc ## same thing using glht argument list displayf.mmc <- mmc(displayf.aov, linfct=mcp(panel="Tukey", `interaction_average`=TRUE, `covariate_average`=TRUE)) mmcplot(displayf.mmc) panel.lmat <- cbind("3-12"=c(-1,-1,2), "1-2"=c( 1,-1,0)) dimnames(panel.lmat)[[1]] <- levels(display$panel) panel.lmat displayf.mmc <- mmc(displayf.aov, focus="panel", focus.lmat=panel.lmat) ## same thing using glht argument list displayf.mmc <- mmc(displayf.aov, linfct=mcp(panel="Tukey", `interaction_average`=TRUE, `covariate_average`=TRUE), focus.lmat=panel.lmat) mmcplot(displayf.mmc, type="lmat") ## End(Not run) ## Not run: ## split plot design with tiebreaker plot ## ## This example is based on the query by Tomas Goicoa to R-news ## http://article.gmane.org/gmane.comp.lang.r.general/76275/match=goicoa ## It is a split plot similar to the one in HH Section 14.2 based on ## Yates 1937 example. I am using the Goicoa example here because its ## MMC plot requires a tiebreaker plot. data(maiz) interaction2wt(yield ~ hibrido+nitrogeno+bloque, data=maiz, par.strip.text=list(cex=.7)) interaction2wt(yield ~ hibrido+nitrogeno, data=maiz) maiz.aov <- aov(yield ~ nitrogeno*hibrido + Error(bloque/nitrogeno), data=maiz) summary(maiz.aov) summary(maiz.aov, split=list(hibrido=list(P3732=1, Mol17=2, A632=3, LH74=4))) try(glht(maiz.aov, linfct=mcp(hibrido="Tukey"))) ## can't use 'aovlist' objects in glht ## R glht() requires aov, not aovlist maiz2.aov <- aov(terms(yield ~ bloque*nitrogeno + hibrido/nitrogeno, keep.order=TRUE), data=maiz) summary(maiz2.aov) ## There are many ties in the group means. ## These are easily seen in the MMC plot, where the two clusters ## c("P3747", "P3732", "LH74") and c("Mol17", "A632") ## are evident from the top three contrasts including zero and the ## bottom contrast including zero. The significant contrasts are the ## ones comparing hybrids in the top group of three to ones in the ## bottom group of two. ## We have two graphical responses to the ties. ## 1. We constructed the tiebreaker plot. ## 2. We construct a set of orthogonal contrasts to illustrate ## the clusters. ## pairwise contrasts with tiebreakers. maiz2.mmc <- mmc(maiz2.aov, linfct=mcp(hibrido="Tukey", interaction_average=TRUE)) mmcplot(maiz2.mmc, style="both") ## MMC and Tiebreaker ## orthogonal contrasts ## user-specified contrasts hibrido.lmat <- cbind("PPL-MA" =c(2, 2,-3,-3, 2), "PP-L" =c(1, 1, 0, 0,-2), "P47-P32"=c(1,-1, 0, 0, 0), "M-A" =c(0, 0, 1,-1, 0)) dimnames(hibrido.lmat)[[1]] <- levels(maiz$hibrido) hibrido.lmat maiz2.mmc <- mmc(maiz2.aov, focus="hibrido", focus.lmat=hibrido.lmat) maiz2.mmc ## same thing using glht argument list maiz2.mmc <- mmc(maiz2.aov, linfct=mcp(hibrido="Tukey", `interaction_average`=TRUE), focus.lmat=hibrido.lmat) mmcplot(maiz2.mmc, style="both", type="lmat") ## End(Not run)
## Use mmc with R. ## Use multicomp.mmc with S-Plus. ## data and ANOVA ## catalystm example data(catalystm) bwplot(concent ~ catalyst, data=catalystm, scales=list(cex=1.5), ylab=list("concentration", cex=1.5), xlab=list("catalyst",cex=1.5)) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) catalystm.mca <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) confint(catalystm.mca) plot(catalystm.mca) ## multcomp plot mmcplot(catalystm.mca, focus="catalyst") ## HH plot ## pairwise comparisons catalystm.mmc <- mmc(catalystm1.aov, focus="catalyst") catalystm.mmc ## Not run: ## these three statements are identical for a one-way aov mmc(catalystm1.aov) ## simplest mmc(catalystm1.aov, focus="catalyst") ## generalizes to higher-order designs mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) ## glht arguments ## End(Not run) mmcplot(catalystm.mmc, style="both") ## User-Specified Contrasts ## Row names must include all levels of the factor. ## Column names are the names the user assigns to the contrasts. ## Each column must sum to zero. catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.lmat catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat) catalystm.mmc mmcplot(catalystm.mmc, style="both", type="lmat") ## Not run: ## Dunnett's test ## weightloss example data(weightloss) bwplot(loss ~ group, data=weightloss, scales=list(cex=1.5), ylab=list("Weight Loss", cex=1.5), xlab=list("group",cex=1.5)) weightloss.aov <- aov(loss ~ group, data=weightloss) summary(weightloss.aov) group.count <- table(weightloss$group) tmp.dunnett <- glht(weightloss.aov, linfct=mcp(group=contrMat(group.count, base=4)), alternative="greater") mmcplot(tmp.dunnett, main="contrasts in alphabetical order", focus="group") tmp.dunnett.mmc <- mmc(weightloss.aov, linfct=mcp(group=contrMat(group.count, base=4)), alternative="greater") mmcplot(tmp.dunnett.mmc, main="contrasts ordered by average value of the means\nof the two levels in the contrasts") tmp.dunnett.mmc ## End(Not run) ## Not run: ## two-way ANOVA ## display example data(display) interaction2wt(time ~ emergenc * panel.ordered, data=display) displayf.aov <- aov(time ~ emergenc * panel, data=display) anova(displayf.aov) ## multiple comparisons ## MMC plot displayf.mmc <- mmc(displayf.aov, focus="panel") displayf.mmc ## same thing using glht argument list displayf.mmc <- mmc(displayf.aov, linfct=mcp(panel="Tukey", `interaction_average`=TRUE, `covariate_average`=TRUE)) mmcplot(displayf.mmc) panel.lmat <- cbind("3-12"=c(-1,-1,2), "1-2"=c( 1,-1,0)) dimnames(panel.lmat)[[1]] <- levels(display$panel) panel.lmat displayf.mmc <- mmc(displayf.aov, focus="panel", focus.lmat=panel.lmat) ## same thing using glht argument list displayf.mmc <- mmc(displayf.aov, linfct=mcp(panel="Tukey", `interaction_average`=TRUE, `covariate_average`=TRUE), focus.lmat=panel.lmat) mmcplot(displayf.mmc, type="lmat") ## End(Not run) ## Not run: ## split plot design with tiebreaker plot ## ## This example is based on the query by Tomas Goicoa to R-news ## http://article.gmane.org/gmane.comp.lang.r.general/76275/match=goicoa ## It is a split plot similar to the one in HH Section 14.2 based on ## Yates 1937 example. I am using the Goicoa example here because its ## MMC plot requires a tiebreaker plot. data(maiz) interaction2wt(yield ~ hibrido+nitrogeno+bloque, data=maiz, par.strip.text=list(cex=.7)) interaction2wt(yield ~ hibrido+nitrogeno, data=maiz) maiz.aov <- aov(yield ~ nitrogeno*hibrido + Error(bloque/nitrogeno), data=maiz) summary(maiz.aov) summary(maiz.aov, split=list(hibrido=list(P3732=1, Mol17=2, A632=3, LH74=4))) try(glht(maiz.aov, linfct=mcp(hibrido="Tukey"))) ## can't use 'aovlist' objects in glht ## R glht() requires aov, not aovlist maiz2.aov <- aov(terms(yield ~ bloque*nitrogeno + hibrido/nitrogeno, keep.order=TRUE), data=maiz) summary(maiz2.aov) ## There are many ties in the group means. ## These are easily seen in the MMC plot, where the two clusters ## c("P3747", "P3732", "LH74") and c("Mol17", "A632") ## are evident from the top three contrasts including zero and the ## bottom contrast including zero. The significant contrasts are the ## ones comparing hybrids in the top group of three to ones in the ## bottom group of two. ## We have two graphical responses to the ties. ## 1. We constructed the tiebreaker plot. ## 2. We construct a set of orthogonal contrasts to illustrate ## the clusters. ## pairwise contrasts with tiebreakers. maiz2.mmc <- mmc(maiz2.aov, linfct=mcp(hibrido="Tukey", interaction_average=TRUE)) mmcplot(maiz2.mmc, style="both") ## MMC and Tiebreaker ## orthogonal contrasts ## user-specified contrasts hibrido.lmat <- cbind("PPL-MA" =c(2, 2,-3,-3, 2), "PP-L" =c(1, 1, 0, 0,-2), "P47-P32"=c(1,-1, 0, 0, 0), "M-A" =c(0, 0, 1,-1, 0)) dimnames(hibrido.lmat)[[1]] <- levels(maiz$hibrido) hibrido.lmat maiz2.mmc <- mmc(maiz2.aov, focus="hibrido", focus.lmat=hibrido.lmat) maiz2.mmc ## same thing using glht argument list maiz2.mmc <- mmc(maiz2.aov, linfct=mcp(hibrido="Tukey", `interaction_average`=TRUE), focus.lmat=hibrido.lmat) mmcplot(maiz2.mmc, style="both", type="lmat") ## End(Not run)
Constructs a "mmc.multicomp"
object from the sufficient statistics
for a one-way design. The object must be explicitly plotted.
This is the S-Plus version. See ?aovSufficient for R
multicomp.mean(group, n, ybar, s, alpha=.05, ## S-Plus ylabel="ylabel", focus.name="focus.factor", plot=FALSE, lmat, labels=NULL, ..., df=sum(n) - length(n), sigmahat=(sum((n-1)*s^2) / df)^.5) multicomp.mmc.mean(group, n, ybar, s, ylabel, focus.name, ## S-Plus lmat, ..., comparisons="mca", lmat.rows=seq(length=length(ybar)), ry, plot=TRUE, crit.point, iso.name=TRUE, estimate.sign=1, x.offset=0, order.contrasts=TRUE, method="tukey", df=sum(n)-length(n), sigmahat=(sum((n-1)*s^2)/df)^.5)
multicomp.mean(group, n, ybar, s, alpha=.05, ## S-Plus ylabel="ylabel", focus.name="focus.factor", plot=FALSE, lmat, labels=NULL, ..., df=sum(n) - length(n), sigmahat=(sum((n-1)*s^2) / df)^.5) multicomp.mmc.mean(group, n, ybar, s, ylabel, focus.name, ## S-Plus lmat, ..., comparisons="mca", lmat.rows=seq(length=length(ybar)), ry, plot=TRUE, crit.point, iso.name=TRUE, estimate.sign=1, x.offset=0, order.contrasts=TRUE, method="tukey", df=sum(n)-length(n), sigmahat=(sum((n-1)*s^2)/df)^.5)
group |
character vector of levels |
n |
numeric vector of sample sizes |
ybar |
vector of group means |
s |
vector of group standard deviations |
alpha |
Significance levels of test |
ylabel |
name of response variable |
focus.name |
name of factor |
plot |
logical. Should the |
lmat |
|
labels |
|
method |
method for critical point calculation. This corresponds
to |
df |
scalar, residual degrees of freedom |
sigmahat |
|
... |
other arguments |
comparisons |
argument to S-Plus |
estimate.sign , order.contrasts , lmat.rows
|
See |
ry |
See argument |
crit.point |
See argument The equivalent is not in |
iso.name , x.offset
|
See |
multicomp.mmc.mean
returns a "mmc.multicomp" object.
multicomp.mean
returns a "multicomp" object.
The multiple comparisons calculations in R and S-Plus use
completely different functions.
MMC plots in R are constructed by mmc
based on
glht
.
MMC plots in S-Plus are constructed by
multicomp.mmc
based on the S-Plus
multicomp
.
The MMC plot is the same in both systems. The details of getting the plot differ.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
Hsu, J. and Peruggia, M. (1994). "Graphical representations of Tukey's multiple comparison method." Journal of Computational and Graphical Statistics, 3:143–161.
## This example is from Hsu and Peruggia ## This is the S-Plus version ## See ?aovSufficient for R if.R(r={}, s={ data(pulmonary) pulmonary.aov <- aovSufficient(FVC ~ smoker, data=pulmonary) summary(pulmonary.aov) ## multicomp object pulmonary.mca <- multicomp.mean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary", focus="smoker") pulmonary.mca ## lexicographic ordering of contrasts, some positive and some negative plot(pulmonary.mca) pulm.lmat <- cbind("npnl-mh"=c( 1, 1, 1, 1,-2,-2), ## not.much vs lots "n-pnl" =c( 3,-1,-1,-1, 0, 0), ## none vs light "p-nl" =c( 0, 2,-1,-1, 0, 0), ## {} arbitrary 2 df "n-l" =c( 0, 0, 1,-1, 0, 0), ## {} for 3 types of light "m-h" =c( 0, 0, 0, 0, 1,-1)) ## moderate vs heavy dimnames(pulm.lmat)[[1]] <- row.names(pulmonary) pulm.lmat ## mmc.multicomp object pulmonary.mmc <- multicomp.mmc.mean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary", focus="smoker", lmat=pulm.lmat, plot=FALSE) old.omd <- par(omd=c(0,.95, 0,1)) ## pairwise comparisons plot(pulmonary.mmc, print.mca=TRUE, print.lmat=FALSE) ## tiebreaker plot, with contrasts ordered to match MMC plot, ## with all contrasts forced positive and with names also reversed, ## and with matched x-scale. plotMatchMMC(pulmonary.mmc$mca) ## orthogonal contrasts plot(pulmonary.mmc) ## pairwise and orthogonal contrasts on the same plot plot(pulmonary.mmc, print.mca=TRUE, print.lmat=TRUE) par(old.omd) })
## This example is from Hsu and Peruggia ## This is the S-Plus version ## See ?aovSufficient for R if.R(r={}, s={ data(pulmonary) pulmonary.aov <- aovSufficient(FVC ~ smoker, data=pulmonary) summary(pulmonary.aov) ## multicomp object pulmonary.mca <- multicomp.mean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary", focus="smoker") pulmonary.mca ## lexicographic ordering of contrasts, some positive and some negative plot(pulmonary.mca) pulm.lmat <- cbind("npnl-mh"=c( 1, 1, 1, 1,-2,-2), ## not.much vs lots "n-pnl" =c( 3,-1,-1,-1, 0, 0), ## none vs light "p-nl" =c( 0, 2,-1,-1, 0, 0), ## {} arbitrary 2 df "n-l" =c( 0, 0, 1,-1, 0, 0), ## {} for 3 types of light "m-h" =c( 0, 0, 0, 0, 1,-1)) ## moderate vs heavy dimnames(pulm.lmat)[[1]] <- row.names(pulmonary) pulm.lmat ## mmc.multicomp object pulmonary.mmc <- multicomp.mmc.mean(pulmonary$smoker, pulmonary$n, pulmonary$FVC, pulmonary$s, ylabel="pulmonary", focus="smoker", lmat=pulm.lmat, plot=FALSE) old.omd <- par(omd=c(0,.95, 0,1)) ## pairwise comparisons plot(pulmonary.mmc, print.mca=TRUE, print.lmat=FALSE) ## tiebreaker plot, with contrasts ordered to match MMC plot, ## with all contrasts forced positive and with names also reversed, ## and with matched x-scale. plotMatchMMC(pulmonary.mmc$mca) ## orthogonal contrasts plot(pulmonary.mmc) ## pairwise and orthogonal contrasts on the same plot plot(pulmonary.mmc, print.mca=TRUE, print.lmat=TRUE) par(old.omd) })
Control aspect ratio in MMC plots to maintain isomeans grid as a square.
mmcAspect(trellis)
mmcAspect(trellis)
trellis |
A |
New numeric aspect ratio that will force the isomeans grid to be a square rotated to have vertical and horizontal diagonals.
Richard M. Heiberger <[email protected]>
Functions used by mmcplot.
mmcisomeans(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", xlim = NULL, ylim = NULL, ..., axis.right=2.2, ylab=paste( mmc$none$ylabel, "means", " | ", mmc$none$focus, "level"), ylab.right=NULL, xlab="contrast value", contrast.label=TRUE, means.height=TRUE) mmcmatch(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", xlim = NULL, ylim = NULL, ..., axis.right=2.2, ylab=NULL, ylab.right=NULL, xlab="contrast value", contrast.label=TRUE, xlim.match=(type != "none")) mmcboth(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", h = c(0.7, 0.3), xlim = NULL, ylim = NULL, ..., ylab.right=NULL, MMCname="MMC", Tiebreakername="Tiebreaker")
mmcisomeans(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", xlim = NULL, ylim = NULL, ..., axis.right=2.2, ylab=paste( mmc$none$ylabel, "means", " | ", mmc$none$focus, "level"), ylab.right=NULL, xlab="contrast value", contrast.label=TRUE, means.height=TRUE) mmcmatch(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", xlim = NULL, ylim = NULL, ..., axis.right=2.2, ylab=NULL, ylab.right=NULL, xlab="contrast value", contrast.label=TRUE, xlim.match=(type != "none")) mmcboth(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), type = "mca", h = c(0.7, 0.3), xlim = NULL, ylim = NULL, ..., ylab.right=NULL, MMCname="MMC", Tiebreakername="Tiebreaker")
mmc |
|
type |
One of |
h |
|
xlim , ylim , xlab , ylab , ylab.right
|
Standard
|
col , lwd , lty
|
Standard
|
... |
Other arguments, to be forwarded to methods. |
axis.right |
Value used internally for |
contrast.label |
Logical. The default |
MMCname , Tiebreakername
|
Panel names when |
xlim.match |
Logical. If |
means.height |
Logical, with default value |
A "trellis"
object.
Richard M. Heiberger <[email protected]>
See mmc
for the references.
mmc
for the discussion of the MMC.
mmcplot
for the user calls that get executed by the
functions documented here.
## Not run: ## these examples exercise all optional arguments data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.glht <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) confint(catalystm.glht) plot(catalystm.glht) ## this is the multcomp:::plot.glht mmcplot(catalystm.glht) ## mmcplot.glht sends its argument to HH:::as.multicomp.glht with ## the default arguments (estimate.sign = 1, order.contrasts = TRUE) unless overridden: ## mmcplot(catalystm.glht, order.contrasts=FALSE, estimate.sign=0, main="B'") catalystm.lmat <- cbind("AB-D" =c(1, 1, 0,-2), "A-B" =c(1,-1, 0, 0), "ABD-C"=c(1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat) mmcplot(catalystm.mmc, type="mca", style="confint") mmcplot(catalystm.mmc, type="lmat", style="confint") mmcplot(catalystm.mmc, type="none", style="confint") mmcplot(catalystm.mmc, type="none", style="confint", xlim.match=FALSE, main="xlim.match=FALSE is default for none confint") mmcplot(catalystm.mmc, type="none", style="confint", xlim.match=TRUE, main="out of bounds") mmcplot(catalystm.mmc$mca, style="confint") mmcplot(catalystm.mmc$lmat, style="confint") mmcplot(catalystm.mmc$none, style="confint") plot(catalystm.mmc) ## HH:::plot.mmc.multicomp method mmcplot(catalystm.mmc) mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, style="isomeans") mmcplot(catalystm.mmc, style="confint") mmcplot(catalystm.mmc, style="both") mmcplot(catalystm.mmc, style="isomeans", type="mca") mmcplot(catalystm.mmc, style="isomeans", type="lmat") mmcplot(catalystm.mmc, style="isomeans", type="linfct") mmcplot(catalystm.mmc, style="isomeans", type="none") mmcplot(catalystm.mmc, style="isomeans", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc, style="confint", type="mca") mmcplot(catalystm.mmc, style="confint", type="lmat") mmcplot(catalystm.mmc, style="confint", type="linfct") mmcplot(catalystm.mmc, style="confint", type="none") mmcplot(catalystm.mmc, style="confint", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc, style="both", type="mca") mmcplot(catalystm.mmc, style="both", type="lmat") mmcplot(catalystm.mmc, style="both", type="linfct") mmcplot(catalystm.mmc, style="both", type="none") mmcplot(catalystm.mmc, style="both", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc$mca) mmcplot(catalystm.mmc$mca$glht) mmcplot(catalystm.mmc$none) mmcplot(catalystm.mmc$none$glht) mmcplot(catalystm.mmc$lmat) mmcplot(catalystm.mmc$lmat$glht) mmcplot(catalystm.mmc, type="none") mmcplot(catalystm.mmc, type="none", xlim.match=FALSE) mmcplot(catalystm.mmc$none) ## End(Not run)
## Not run: ## these examples exercise all optional arguments data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.glht <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) confint(catalystm.glht) plot(catalystm.glht) ## this is the multcomp:::plot.glht mmcplot(catalystm.glht) ## mmcplot.glht sends its argument to HH:::as.multicomp.glht with ## the default arguments (estimate.sign = 1, order.contrasts = TRUE) unless overridden: ## mmcplot(catalystm.glht, order.contrasts=FALSE, estimate.sign=0, main="B'") catalystm.lmat <- cbind("AB-D" =c(1, 1, 0,-2), "A-B" =c(1,-1, 0, 0), "ABD-C"=c(1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat) mmcplot(catalystm.mmc, type="mca", style="confint") mmcplot(catalystm.mmc, type="lmat", style="confint") mmcplot(catalystm.mmc, type="none", style="confint") mmcplot(catalystm.mmc, type="none", style="confint", xlim.match=FALSE, main="xlim.match=FALSE is default for none confint") mmcplot(catalystm.mmc, type="none", style="confint", xlim.match=TRUE, main="out of bounds") mmcplot(catalystm.mmc$mca, style="confint") mmcplot(catalystm.mmc$lmat, style="confint") mmcplot(catalystm.mmc$none, style="confint") plot(catalystm.mmc) ## HH:::plot.mmc.multicomp method mmcplot(catalystm.mmc) mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, style="isomeans") mmcplot(catalystm.mmc, style="confint") mmcplot(catalystm.mmc, style="both") mmcplot(catalystm.mmc, style="isomeans", type="mca") mmcplot(catalystm.mmc, style="isomeans", type="lmat") mmcplot(catalystm.mmc, style="isomeans", type="linfct") mmcplot(catalystm.mmc, style="isomeans", type="none") mmcplot(catalystm.mmc, style="isomeans", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc, style="confint", type="mca") mmcplot(catalystm.mmc, style="confint", type="lmat") mmcplot(catalystm.mmc, style="confint", type="linfct") mmcplot(catalystm.mmc, style="confint", type="none") mmcplot(catalystm.mmc, style="confint", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc, style="both", type="mca") mmcplot(catalystm.mmc, style="both", type="lmat") mmcplot(catalystm.mmc, style="both", type="linfct") mmcplot(catalystm.mmc, style="both", type="none") mmcplot(catalystm.mmc, style="both", type="none", xlim.match=FALSE) mmcplot(catalystm.mmc$mca) mmcplot(catalystm.mmc$mca$glht) mmcplot(catalystm.mmc$none) mmcplot(catalystm.mmc$none$glht) mmcplot(catalystm.mmc$lmat) mmcplot(catalystm.mmc$lmat$glht) mmcplot(catalystm.mmc, type="none") mmcplot(catalystm.mmc, type="none", xlim.match=FALSE) mmcplot(catalystm.mmc$none) ## End(Not run)
MMC (Mean–mean Multiple Comparisons) plots in lattice
mmcplot(mmc, ...) ## S3 method for class 'mmc' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ..., style=c("isomeans", "confint", "both"), type=c("mca", "lmat", "linfct", "none")) ## S3 method for class 'glht' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), focus=mmc$focus, ...) ## S3 method for class 'mmc.multicomp' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ...) ## S3 method for class 'multicomp' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ...) ## Default S3 method: mmcplot(mmc, ...)
mmcplot(mmc, ...) ## S3 method for class 'mmc' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ..., style=c("isomeans", "confint", "both"), type=c("mca", "lmat", "linfct", "none")) ## S3 method for class 'glht' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), focus=mmc$focus, ...) ## S3 method for class 'mmc.multicomp' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ...) ## S3 method for class 'multicomp' mmcplot(mmc, col=c("black","red"), lwd=c(1,1), lty=c(2,1), ...) ## Default S3 method: mmcplot(mmc, ...)
mmc |
|
col , lwd , lty
|
Standard
|
focus |
Name of the factor for which the |
... |
Other arguments to be passed on to the functions called by the methods. |
style |
Style of graph: The default |
type |
|
A trellis
object containing the graphs.
Richard M. Heiberger <[email protected]>
See mmc
for the references.
mmc
for the discussion of the MMC and for many examples.
The functions mmcisomeans
, mmcmatch
,
mmcboth
are the internal functions that do the
actual work of plotting.
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, style="both", MMCname="catalyst")
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, style="both", MMCname="catalyst")
MMC plots in lattice—suppress isomeans grid lines for specified levels of the factor.
mmcPruneIsomeans(mmc, keep=NULL)
mmcPruneIsomeans(mmc, keep=NULL)
mmc |
An |
keep |
Index vector of rows of |
A modified "mmc.multicomp"
object.
## needed ## Not run: ## See file hh/scripts/hh2/tway.R for the complete example. ## A better example is needed for the .Rd documentation. ## possibly based on filmcoat temperature | pressure example. data(rhiz.clover) c(1,2,5,10,11,12) rhiz.clover$cs <- with(rhiz.clover, interaction(comb, strain)) rhiz.clover.cs.aov <- aov(Npg ~ cs, data=rhiz.clover) rhiz.clover.cs.aov cs.mmc <- mmc(rhiz.clover.cs.aov, linfct=mcp(cs="Tukey"), calpha=qtukey( .95, 6, 48)/sqrt(2)) dlmat2 <- dimnames(cs.mmc$mca$lmat)[[2]] cl.index <- grep("clover\\.[[:print:]]*clover\\.", dlmat2, value=TRUE) cl.index clover.lmat <- cs.mmc$mca$lmat[, cl.index] ## suppress "clover+alfalfa" contrasts dimnames(clover.lmat)[[1]] dimnames(clover.lmat)[[1]] <- levels(rhiz.clover$cs) clover.lmat[1,] <- -colSums(clover.lmat[-1, ]) clover.lmat csc.mmc <- mmc(rhiz.clover.cs.aov, linfct=mcp(cs="Tukey"), focus.lmat=clover.lmat, calpha=qtukey( .95, 6, 48)/sqrt(2)) ## this example needs a window 11 inches high and 14 inches wide mmcplot(csc.mmc, type="lmat", style="both") ## suppress "clover+alfalfa" means csc.mmc.clover <- mmcPruneIsomeans(csc.mmc, keep = c(1,2,5,10,11,12)) csc.mmc.clover ## this example needs a window 11 inches high and 14 inches wide mmcplot(csc.mmc.clover, type="lmat", style="both") ## End(Not run)
## needed ## Not run: ## See file hh/scripts/hh2/tway.R for the complete example. ## A better example is needed for the .Rd documentation. ## possibly based on filmcoat temperature | pressure example. data(rhiz.clover) c(1,2,5,10,11,12) rhiz.clover$cs <- with(rhiz.clover, interaction(comb, strain)) rhiz.clover.cs.aov <- aov(Npg ~ cs, data=rhiz.clover) rhiz.clover.cs.aov cs.mmc <- mmc(rhiz.clover.cs.aov, linfct=mcp(cs="Tukey"), calpha=qtukey( .95, 6, 48)/sqrt(2)) dlmat2 <- dimnames(cs.mmc$mca$lmat)[[2]] cl.index <- grep("clover\\.[[:print:]]*clover\\.", dlmat2, value=TRUE) cl.index clover.lmat <- cs.mmc$mca$lmat[, cl.index] ## suppress "clover+alfalfa" contrasts dimnames(clover.lmat)[[1]] dimnames(clover.lmat)[[1]] <- levels(rhiz.clover$cs) clover.lmat[1,] <- -colSums(clover.lmat[-1, ]) clover.lmat csc.mmc <- mmc(rhiz.clover.cs.aov, linfct=mcp(cs="Tukey"), focus.lmat=clover.lmat, calpha=qtukey( .95, 6, 48)/sqrt(2)) ## this example needs a window 11 inches high and 14 inches wide mmcplot(csc.mmc, type="lmat", style="both") ## suppress "clover+alfalfa" means csc.mmc.clover <- mmcPruneIsomeans(csc.mmc, keep = c(1,2,5,10,11,12)) csc.mmc.clover ## this example needs a window 11 inches high and 14 inches wide mmcplot(csc.mmc.clover, type="lmat", style="both") ## End(Not run)
Update a multicomp object by ordering its contrasts.
The default sort.by = "height"
matches the order in the MMC plot.
An alternate sort.by = "estimate"
matches the order of the
half-normal plot. Or the argument sort.order
can be used
to specify any other order.
multicomp.order(mca, sort.by = "height", sort.order = NULL) multicomp.label.change(x, old="adj", new="new", how.many=2) ## S3 method for class 'multicomp' multicomp.label.change(x, old="adj", new="new", how.many=2) ## S3 method for class 'mmc.multicomp' multicomp.label.change(x, old="adj", new="new", how.many=2)
multicomp.order(mca, sort.by = "height", sort.order = NULL) multicomp.label.change(x, old="adj", new="new", how.many=2) ## S3 method for class 'multicomp' multicomp.label.change(x, old="adj", new="new", how.many=2) ## S3 method for class 'mmc.multicomp' multicomp.label.change(x, old="adj", new="new", how.many=2)
mca |
|
sort.by |
Either |
sort.order |
Vector of indices by which the contrasts are to be
sorted. When |
x |
|
old |
character string to be removed from contrast names. |
new |
replacement character string to be inserted in contrast names. |
how.many |
number of times to make the replacement. |
The result is a "multicomp"
object containing the same
contrasts as the argument.multicomp.order
sorts the contrasts
(and renames them consistently) according to the specifications.multicomp.label.change
changes the contrast names according to the specifications.
When sort.by=="height"
, sort the contrasts by the reverse order
of the heights. This provides a "multicomp"
object that will be
plotted by plot.multicomp
in the same order used bymmcplot
or the older plot.mmc.multicomp
. If there is not "height"
component,
the original "multicomp"
object is returned.
When sort.by=="estimate"
, sort the contrasts by the reverse order
of the contrast estimates. This provides the same order as the
half-normal plot.
When sort.order
in non-NULL
, sort the contrasts in
that order.
S-Plus use the multicomp
functions
and R uses the multcomp
package.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
MMC
, as.glht in R
,
multicomp.reverse
## continue with the example in mmc in R, or multicomp.mmc in S-Plus data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) if.R(r={ catalystm.mca <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) print(confint(catalystm.mca)) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) ## the contrasts have been ordered by height (see ?MMC), ## which in this example corresponds to sort.order=c(1,2,4,3,5,6), ## and reversed, to make the contrast Estimates positive. print(as.glht(catalystm.mmc$mca)) ## ## For consistency with the S-Plus example, ## ## we change all factor level "A" to "control". ## as.glht(multicomp.label.change(catalystm.mmc$mca, "A", "control")) },s={ catalystm.mca <- multicomp(catalystm1.aov, method="Tukey") print(catalystm.mca) catalystm.mmc <- multicomp.mmc(catalystm1.aov, method="Tukey", plot=FALSE) ## the contrasts have been ordered by height (see ?MMC), ## which in this example corresponds to sort.order=c(1,2,4,3,5,6), ## and reversed, to make the contrast Estimates positive. print(catalystm.mmc$mca) ## S-Plus multicomp already uses simple names. This function is ## therefore used in more complex two-way ANOVA examples. We illustrate ## here by changing all factor level "A" to "control". print(multicomp.label.change(catalystm.mmc$mca, "A", "control")) })
## continue with the example in mmc in R, or multicomp.mmc in S-Plus data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) if.R(r={ catalystm.mca <- glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) print(confint(catalystm.mca)) catalystm.mmc <- mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey")) ## the contrasts have been ordered by height (see ?MMC), ## which in this example corresponds to sort.order=c(1,2,4,3,5,6), ## and reversed, to make the contrast Estimates positive. print(as.glht(catalystm.mmc$mca)) ## ## For consistency with the S-Plus example, ## ## we change all factor level "A" to "control". ## as.glht(multicomp.label.change(catalystm.mmc$mca, "A", "control")) },s={ catalystm.mca <- multicomp(catalystm1.aov, method="Tukey") print(catalystm.mca) catalystm.mmc <- multicomp.mmc(catalystm1.aov, method="Tukey", plot=FALSE) ## the contrasts have been ordered by height (see ?MMC), ## which in this example corresponds to sort.order=c(1,2,4,3,5,6), ## and reversed, to make the contrast Estimates positive. print(catalystm.mmc$mca) ## S-Plus multicomp already uses simple names. This function is ## therefore used in more complex two-way ANOVA examples. We illustrate ## here by changing all factor level "A" to "control". print(multicomp.label.change(catalystm.mmc$mca, "A", "control")) })
Force all comparisons in a "multicomp"
object
to have the same sign. If the contrast "A-B"
has a negative estimate,
reverse it show the contrast "B-A"
with a positive estimate.
If a contrast name does not include a minus sign "-"
and the
contrast is reversed, then an informative message is printed.
multicomp.reverse(y, estimate.sign = 1, ...)
multicomp.reverse(y, estimate.sign = 1, ...)
y |
|
estimate.sign |
If |
... |
other arguments not used. |
The result is a "multicomp"
object containing the same contrasts
as the argument but with the sign of the contrasts changed as needed.
S-Plus use the multicomp
functions and R uses the multcomp
package.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
## see example in multicomp.order
## see example in multicomp.order
Plot a normal curve or a t-curve with both x (with mean
and se
as specified) and z or t (mean=0, se=1) axes.
Shade a region for rejection region, acceptance region, confidence
interval.
The density axis is marked in units appropriate for the z or t axis.
The existence of any of the arguments se
, sd
, n
forces dual x
and (z
or t
) scales. When none of these
arguments
are used, the main title defaults to
"Standard Normal Density N(0,1)"
and only the z
scale is
printed. A second density curve, appropriate for an alternative
hypothesis
is displayed when the argument axis.name="z1"
is specified.
The shaded area is printed on the plot.
When the optional argument df.t
is specified, then a
t-distribution with df.t
degrees of freedom is plotted.
norm.observed
plots a vertical line with arrowhead markers at
the location of the observed xbar.
normal.and.t.dist
is a driver function that uses all the
others. It's primary function is drawing a plot. It returns
an invisible list containing the values it calculated and
displayed on the graph.
norm.curve
draws the curves and filled areas as requested
by the normal.and.t.dist
function. Any out of bounds
errors (for example, with normal.and.t.dist(deg.free=1)
)
are suppressed with par(err=-1)
by this function and
restored to the previous value when the norm.curve
function completes.
normal.and.t.dist(mu.H0 = 0, mu.H1 = NA, obs.mean = 0, std.dev = 1, n = NA, deg.freedom = NA, alpha.left = alpha.right, alpha.right = .05, Use.mu.H1 = FALSE, Use.obs.mean = FALSE, Use.alpha.left = FALSE, Use.alpha.right= TRUE, hypoth.or.conf = 'Hypoth', xmin = NA, xmax = NA, gxbar.min = NA, gxbar.max = NA, cex.crit = 1.2, polygon.density= -1, polygon.lwd = 4, col.mean = 'limegreen', col.mean.label = 'limegreen', col.alpha = 'blue', col.alpha.label= 'blue', col.beta = 'red', col.beta.label = 'red', col.conf = 'palegreen', col.conf.arrow = 'darkgreen', col.conf.label = 'darkgreen' ) norm.setup(xlim=c(-2.5,2.5), ylim = c(0, 0.4)/se, mean=0, main=main.calc, se=sd/sqrt(n), sd=1, n=1, df.t=NULL, Use.obs.mean=TRUE, ...) norm.curve(mean=0, se=sd/sqrt(n), critical.values=mean + se*c(-1, 1)*z.975, z=if(se==0) 0 else do.call("seq", as.list(c((par()$usr[1:2]-mean)/se, length=109))), shade, col="blue", axis.name=ifelse(is.null(df.t) || df.t==Inf, "z", "t"), second.axis.label.line=3, sd=1, n=1, df.t=NULL, axis.name.expr=axis.name, Use.obs.mean=TRUE, col.label=col, hypoth.or.conf="Hypoth", col.conf.arrow=par("col"), col.conf.label=par("col"), col.crit=ifelse(hypoth.or.conf=="Hypoth", 'blue', col.conf.arrow), cex.crit=1.2, polygon.density=-1, polygon.lwd=4, col.border=ifelse(is.na(polygon.density), FALSE, col), ...) norm.observed(xbar, t.xbar, t.xbar.H1=NULL, col="green", p.val=NULL, p.val.x=par()$usr[2]+ left.margin, t.or.z=ifelse(is.null(deg.free) || deg.free==Inf, "z", "t"), t.or.z.position=par()$usr[1]-left.margin, cex.small=par()$cex*.7, col.label=col, xbar.negt=NULL, cex.large=par()$cex, left.margin=.15*diff(par()$usr[1:2]), sided="", deg.free=NULL) norm.outline(dfunction, left, right, mu.H0, se, deg.free=NULL, col.mean="green")
normal.and.t.dist(mu.H0 = 0, mu.H1 = NA, obs.mean = 0, std.dev = 1, n = NA, deg.freedom = NA, alpha.left = alpha.right, alpha.right = .05, Use.mu.H1 = FALSE, Use.obs.mean = FALSE, Use.alpha.left = FALSE, Use.alpha.right= TRUE, hypoth.or.conf = 'Hypoth', xmin = NA, xmax = NA, gxbar.min = NA, gxbar.max = NA, cex.crit = 1.2, polygon.density= -1, polygon.lwd = 4, col.mean = 'limegreen', col.mean.label = 'limegreen', col.alpha = 'blue', col.alpha.label= 'blue', col.beta = 'red', col.beta.label = 'red', col.conf = 'palegreen', col.conf.arrow = 'darkgreen', col.conf.label = 'darkgreen' ) norm.setup(xlim=c(-2.5,2.5), ylim = c(0, 0.4)/se, mean=0, main=main.calc, se=sd/sqrt(n), sd=1, n=1, df.t=NULL, Use.obs.mean=TRUE, ...) norm.curve(mean=0, se=sd/sqrt(n), critical.values=mean + se*c(-1, 1)*z.975, z=if(se==0) 0 else do.call("seq", as.list(c((par()$usr[1:2]-mean)/se, length=109))), shade, col="blue", axis.name=ifelse(is.null(df.t) || df.t==Inf, "z", "t"), second.axis.label.line=3, sd=1, n=1, df.t=NULL, axis.name.expr=axis.name, Use.obs.mean=TRUE, col.label=col, hypoth.or.conf="Hypoth", col.conf.arrow=par("col"), col.conf.label=par("col"), col.crit=ifelse(hypoth.or.conf=="Hypoth", 'blue', col.conf.arrow), cex.crit=1.2, polygon.density=-1, polygon.lwd=4, col.border=ifelse(is.na(polygon.density), FALSE, col), ...) norm.observed(xbar, t.xbar, t.xbar.H1=NULL, col="green", p.val=NULL, p.val.x=par()$usr[2]+ left.margin, t.or.z=ifelse(is.null(deg.free) || deg.free==Inf, "z", "t"), t.or.z.position=par()$usr[1]-left.margin, cex.small=par()$cex*.7, col.label=col, xbar.negt=NULL, cex.large=par()$cex, left.margin=.15*diff(par()$usr[1:2]), sided="", deg.free=NULL) norm.outline(dfunction, left, right, mu.H0, se, deg.free=NULL, col.mean="green")
xlim , ylim , xmin , xmax , gxbar.min , gxbar.max
|
|
mean |
Mean of the normal distribution in xbar-scale,
used in calls to |
se |
standard error of the normal distribution in xbar-scale,
used in calls to |
sd , std.dev , n
|
standard deviation and sample size of the normal
distribution in x-scale. These may be used as an alternate way of
specifying the standard error |
df.t , deg.freedom
|
Degrees of freedom for the t distribution. When
|
critical.values |
Critical values in xbar-scale. A scalar value implies a one-sided test. A vector of two values implies a two-sided test. |
main |
Main title. |
z |
z-values (standardized to N(0,1)) used as base of plot. |
shade |
Valid values for shade are "right", "left", "inside", "outside", "none". Default is "right" for one-sided critical.values and "outside" for two-sided critical values. |
col |
color of the shaded region. |
col.label , col.alpha , col.alpha.label
|
color of the area of the shaded rejection region and its label. |
col.beta , col.beta.label
|
color of the area of the shaded region For Type II error and its label. |
hypoth.or.conf |
|
col.conf |
Color of plot within confidence limits. |
col.conf.arrow |
Color of arrow denoting confidence limits. |
col.conf.label |
Color of label giving confidence level. |
col.mean.label |
Color of label for observed mean. |
col.crit , cex.crit
|
Color and cex of critical values. |
axis.name , axis.name.expr
|
defaults to |
second.axis.label.line |
Defaults to |
xbar , obs.mean
|
xbar-value of the observed data. |
t.xbar |
t-value of the observed data under the null hypothesis. |
... |
Other arguments which are ignored. |
Use.obs.mean |
Logical. If |
alpha.right , alpha.left
|
Area in tail of curve. |
Use.alpha.right , Use.alpha.left
|
Logical. If |
t.xbar.H1 |
t-value under alternate hypothesis. |
p.val |
under specified hypothesis |
p.val.x , t.or.z.position
|
location on x-axis to put label |
t.or.z |
label for axis. |
cex.small |
cex for left margin labels of axis. |
xbar.negt |
location in data scale of negative t- or z-value corresponding to observed x-value. Used for two-sided p-values. |
cex.large |
cex for labels in top margin. |
left.margin |
distance to the left of |
sided |
type of test. |
deg.free |
degrees of freedom or |
dfunction |
|
left |
left end of interval |
right |
right end of interval |
mu.H0 , mu.H1
|
mean under the null hypothesis and alternative hypothesis. |
Use.mu.H1 |
Logical. If |
col.mean |
Color of outline. |
polygon.density , polygon.lwd , col.border
|
|
An invisible list containing the
calculated values of probabilities and critical values in the data
scale, the null hypothesis z- or t-scale, and the alternative
hypothesis z- or t-scale, as specified. The components are:
beta.left, beta.middle, beta.right, crit.val, crit.val.H1,
crit.val.H1.left, crit.val.left, crit.val.left.z, crit.val.z, obs.mean.H0.p.val,
obs.mean.H0.side, obs.mean.H0.z, obs.mean.H1.z, obs.mean.x.neg, obs.mean.x.pos,
obs.mean.z.pos, standard, standard.error, standard.normal
Richard M. Heiberger <[email protected]>
normal.and.t.dist() normal.and.t.dist(xmin=-4) normal.and.t.dist(std.dev=2) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6, gxbar.max=.20) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6, gxbar.max=.20, polygon.density=10) normal.and.t.dist(std.dev=2, Use.alpha.left=FALSE, deg.free=6, gxbar.max=.20, polygon.density=10, mu.H1=2, Use.mu.H1=TRUE, obs.mean=2.5, Use.obs.mean=TRUE, xmin=-7) normal.and.t.dist(std.dev=2, hypoth.or.conf="Conf") normal.and.t.dist(std.dev=2, hypoth.or.conf="Conf", deg.free=8) old.par <- par(oma=c(4,0,2,5), mar=c(7,7,4,2)+.1) norm.setup() norm.curve() norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*(1.645)) norm.observed(112, (112-100)/5) norm.outline("dnorm", 112, par()$usr[2], 100, 5) norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*(-1.645), shade="left") norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(mean=100, se=5, col='red') norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*c(-1.96, 1.96)) norm.setup(xlim=c(-3, 6)) norm.curve(critical.values=1.645, mean=1.645+1.281552, col='green', shade="left", axis.name="z1") norm.curve(critical.values=1.645, col='red') norm.setup(xlim=c(-6, 12), se=2) norm.curve(critical.values=2*1.645, se=2, mean=2*(1.645+1.281552), col='green', shade="left", axis.name="z1") norm.curve(critical.values=2*1.645, se=2, mean=0, col='red', shade="right") par(mfrow=c(2,1)) norm.setup() norm.curve() mtext("norm.setup(); norm.curve()", side=1, line=5) norm.setup(n=1) norm.curve(n=1) mtext("norm.setup(n=1); norm.curve(n=1)", side=1, line=5) par(mfrow=c(1,1)) par(mfrow=c(2,2)) ## naively scaled, ## areas under the curve are numerically the same but visually different norm.setup(n=1) norm.curve(n=1) norm.observed(1.2, 1.2/(1/sqrt(1))) norm.setup(n=2) norm.curve(n=2) norm.observed(1.2, 1.2/(1/sqrt(2))) norm.setup(n=4) norm.curve(n=4) norm.observed(1.2, 1.2/(1/sqrt(4))) norm.setup(n=10) norm.curve(n=10) norm.observed(1.2, 1.2/(1/sqrt(10))) mtext("areas under the curve are numerically the same but visually different", side=3, outer=TRUE) ## scaled so all areas under the curve are numerically and visually the same norm.setup(n=1, ylim=c(0,1.3)) norm.curve(n=1) norm.observed(1.2, 1.2/(1/sqrt(1))) norm.setup(n=2, ylim=c(0,1.3)) norm.curve(n=2) norm.observed(1.2, 1.2/(1/sqrt(2))) norm.setup(n=4, ylim=c(0,1.3)) norm.curve(n=4) norm.observed(1.2, 1.2/(1/sqrt(4))) norm.setup(n=10, ylim=c(0,1.3)) norm.curve(n=10) norm.observed(1.2, 1.2/(1/sqrt(10))) mtext("all areas under the curve are numerically and visually the same", side=3, outer=TRUE) par(mfrow=c(1,1)) ## t distribution mu.H0 <- 16 se.val <- .4 df.val <- 10 crit.val <- mu.H0 - qt(.95, df.val) * se.val mu.alt <- 15 obs.mean <- 14.8 alt.t <- (mu.alt - crit.val) / se.val norm.setup(xlim=c(12, 19), se=se.val, df.t=df.val) norm.curve(critical.values=crit.val, se=se.val, df.t=df.val, mean=mu.alt, col='green', shade="left", axis.name="t1") norm.curve(critical.values=crit.val, se=se.val, df.t=df.val, mean=mu.H0, col='gray', shade="right") norm.observed(obs.mean, (obs.mean-mu.H0)/se.val) ## normal norm.setup(xlim=c(12, 19), se=se.val) norm.curve(critical.values=crit.val, se=se.val, mean=mu.alt, col='green', shade="left", axis.name="z1") norm.curve(critical.values=crit.val, se=se.val, mean=mu.H0, col='gray', shade="right") norm.observed(obs.mean, (obs.mean-mu.H0)/se.val) ## normal and t norm.setup(xlim=c(12, 19), se=se.val, main="t(6) and normal") norm.curve(critical.values=15.5, se=se.val, mean=16.3, col='gray', shade="right") norm.curve(critical.values=15.5, se.val, df.t=6, mean=14.7, col='green', shade="left", axis.name="t1", second.axis.label.line=4) norm.curve(critical.values=15.5, se=se.val, mean=16.3, col='gray', shade="none") norm.setup(xlim=c(12, 19), se=se.val, main="t(6) and normal") norm.curve(critical.values=15.5, se=se.val, mean=15.5, col='gray', shade="right") norm.curve(critical.values=15.5, se=se.val, df.t=6, mean=15.5, col='green', shade="left", axis.name="t1", second.axis.label.line=4) norm.curve(critical.values=15.5, se=se.val, mean=15.5, col='gray', shade="none") par(old.par)
normal.and.t.dist() normal.and.t.dist(xmin=-4) normal.and.t.dist(std.dev=2) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6, gxbar.max=.20) normal.and.t.dist(std.dev=2, Use.alpha.left=TRUE, deg.free=6, gxbar.max=.20, polygon.density=10) normal.and.t.dist(std.dev=2, Use.alpha.left=FALSE, deg.free=6, gxbar.max=.20, polygon.density=10, mu.H1=2, Use.mu.H1=TRUE, obs.mean=2.5, Use.obs.mean=TRUE, xmin=-7) normal.and.t.dist(std.dev=2, hypoth.or.conf="Conf") normal.and.t.dist(std.dev=2, hypoth.or.conf="Conf", deg.free=8) old.par <- par(oma=c(4,0,2,5), mar=c(7,7,4,2)+.1) norm.setup() norm.curve() norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*(1.645)) norm.observed(112, (112-100)/5) norm.outline("dnorm", 112, par()$usr[2], 100, 5) norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*(-1.645), shade="left") norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(mean=100, se=5, col='red') norm.setup(xlim=c(75,125), mean=100, se=5) norm.curve(100, 5, 100+5*c(-1.96, 1.96)) norm.setup(xlim=c(-3, 6)) norm.curve(critical.values=1.645, mean=1.645+1.281552, col='green', shade="left", axis.name="z1") norm.curve(critical.values=1.645, col='red') norm.setup(xlim=c(-6, 12), se=2) norm.curve(critical.values=2*1.645, se=2, mean=2*(1.645+1.281552), col='green', shade="left", axis.name="z1") norm.curve(critical.values=2*1.645, se=2, mean=0, col='red', shade="right") par(mfrow=c(2,1)) norm.setup() norm.curve() mtext("norm.setup(); norm.curve()", side=1, line=5) norm.setup(n=1) norm.curve(n=1) mtext("norm.setup(n=1); norm.curve(n=1)", side=1, line=5) par(mfrow=c(1,1)) par(mfrow=c(2,2)) ## naively scaled, ## areas under the curve are numerically the same but visually different norm.setup(n=1) norm.curve(n=1) norm.observed(1.2, 1.2/(1/sqrt(1))) norm.setup(n=2) norm.curve(n=2) norm.observed(1.2, 1.2/(1/sqrt(2))) norm.setup(n=4) norm.curve(n=4) norm.observed(1.2, 1.2/(1/sqrt(4))) norm.setup(n=10) norm.curve(n=10) norm.observed(1.2, 1.2/(1/sqrt(10))) mtext("areas under the curve are numerically the same but visually different", side=3, outer=TRUE) ## scaled so all areas under the curve are numerically and visually the same norm.setup(n=1, ylim=c(0,1.3)) norm.curve(n=1) norm.observed(1.2, 1.2/(1/sqrt(1))) norm.setup(n=2, ylim=c(0,1.3)) norm.curve(n=2) norm.observed(1.2, 1.2/(1/sqrt(2))) norm.setup(n=4, ylim=c(0,1.3)) norm.curve(n=4) norm.observed(1.2, 1.2/(1/sqrt(4))) norm.setup(n=10, ylim=c(0,1.3)) norm.curve(n=10) norm.observed(1.2, 1.2/(1/sqrt(10))) mtext("all areas under the curve are numerically and visually the same", side=3, outer=TRUE) par(mfrow=c(1,1)) ## t distribution mu.H0 <- 16 se.val <- .4 df.val <- 10 crit.val <- mu.H0 - qt(.95, df.val) * se.val mu.alt <- 15 obs.mean <- 14.8 alt.t <- (mu.alt - crit.val) / se.val norm.setup(xlim=c(12, 19), se=se.val, df.t=df.val) norm.curve(critical.values=crit.val, se=se.val, df.t=df.val, mean=mu.alt, col='green', shade="left", axis.name="t1") norm.curve(critical.values=crit.val, se=se.val, df.t=df.val, mean=mu.H0, col='gray', shade="right") norm.observed(obs.mean, (obs.mean-mu.H0)/se.val) ## normal norm.setup(xlim=c(12, 19), se=se.val) norm.curve(critical.values=crit.val, se=se.val, mean=mu.alt, col='green', shade="left", axis.name="z1") norm.curve(critical.values=crit.val, se=se.val, mean=mu.H0, col='gray', shade="right") norm.observed(obs.mean, (obs.mean-mu.H0)/se.val) ## normal and t norm.setup(xlim=c(12, 19), se=se.val, main="t(6) and normal") norm.curve(critical.values=15.5, se=se.val, mean=16.3, col='gray', shade="right") norm.curve(critical.values=15.5, se.val, df.t=6, mean=14.7, col='green', shade="left", axis.name="t1", second.axis.label.line=4) norm.curve(critical.values=15.5, se=se.val, mean=16.3, col='gray', shade="none") norm.setup(xlim=c(12, 19), se=se.val, main="t(6) and normal") norm.curve(critical.values=15.5, se=se.val, mean=15.5, col='gray', shade="right") norm.curve(critical.values=15.5, se=se.val, df.t=6, mean=15.5, col='green', shade="left", axis.name="t1", second.axis.label.line=4) norm.curve(critical.values=15.5, se=se.val, mean=15.5, col='gray', shade="none") par(old.par)
Specify plots to illustrate Normal and t Hypothesis Tests or Confidence Intervals.
NormalAndTplot(mean0, ...) ## Default S3 method: NormalAndTplot(mean0=0, mean1=NA, xbar=NA, df=Inf, n=1, sd=1, xlim=c(-3, 3)*sd/sqrt(n) + range(c(mean0, mean1, xbar), na.rm=TRUE), ylim, alpha.right=.05, alpha.left=0, float=TRUE, ntcolors="original", digits=4, digits.axis=digits, digits.float=digits, distribution.name=c("normal","z","t","binomial"), type=c("hypothesis", "confidence"), zaxis=FALSE, z1axis=FALSE, cex.z=.5, cex.xbar=.5, cex.y=.5, cex.prob=.6, cex.top.axis=1, cex.left.axis=1, cex.pb.axis=1, cex.xlab=1, cex.ylab=1.5, cex.strip=1, main=NA, xlab, ylab, prob.labels=(type=="hypothesis"), xhalf.multiplier=1, yhalf.multiplier=1, cex.main=1, key.axis.padding=4.5, number.vars=1, sub=NULL, NTmethod="default", power=FALSE, beta=FALSE, ...) ## S3 method for class 'htest' NormalAndTplot(mean0, type="hypothesis", xlim=NULL, mean1=NA, ..., xbar, sd, df, n, alpha.left, alpha.right, ## ignored distribution.name, sub ## these input arguments will be ignored )
NormalAndTplot(mean0, ...) ## Default S3 method: NormalAndTplot(mean0=0, mean1=NA, xbar=NA, df=Inf, n=1, sd=1, xlim=c(-3, 3)*sd/sqrt(n) + range(c(mean0, mean1, xbar), na.rm=TRUE), ylim, alpha.right=.05, alpha.left=0, float=TRUE, ntcolors="original", digits=4, digits.axis=digits, digits.float=digits, distribution.name=c("normal","z","t","binomial"), type=c("hypothesis", "confidence"), zaxis=FALSE, z1axis=FALSE, cex.z=.5, cex.xbar=.5, cex.y=.5, cex.prob=.6, cex.top.axis=1, cex.left.axis=1, cex.pb.axis=1, cex.xlab=1, cex.ylab=1.5, cex.strip=1, main=NA, xlab, ylab, prob.labels=(type=="hypothesis"), xhalf.multiplier=1, yhalf.multiplier=1, cex.main=1, key.axis.padding=4.5, number.vars=1, sub=NULL, NTmethod="default", power=FALSE, beta=FALSE, ...) ## S3 method for class 'htest' NormalAndTplot(mean0, type="hypothesis", xlim=NULL, mean1=NA, ..., xbar, sd, df, n, alpha.left, alpha.right, ## ignored distribution.name, sub ## these input arguments will be ignored )
mean0 |
Null hypothesis |
mean1 |
Alternative hypothesis |
xbar |
Observed |
sd |
Standard deviation in the data scale |
df |
Degrees of freedom for |
n |
Number of observations per group. |
main , xlab , ylab , xlim , ylim , sub
|
Standard |
... |
Additional |
number.vars |
Number of variables. 1 for a one-sample test, 2 for two-sample tests and paired tests. |
alpha.left , alpha.right
|
For |
float |
Logical. If |
ntcolors |
Vector of colors used in the graph. The default value is
|
digits.axis , digits.float , digits
|
|
distribution.name |
Name of distribution. |
type |
"hypothesis" for a Hypothesis Test graph, or "confidence" for a Confidence Interval graph. |
zaxis , z1axis
|
Logical or list. Should the |
cex.z , cex.xbar , cex.y , cex.prob , cex.top.axis , cex.left.axis , cex.pb.axis , cex.xlab , cex.ylab , cex.strip , cex.main
|
|
key.axis.padding |
tuning constant to create additional room above the
graph for a larger |
prob.labels |
logical. If |
xhalf.multiplier , yhalf.multiplier
|
Numerical tuning constants to control the width and height of the floating probability values. Empirically, we need a smaller value for the shiny app then we need for direct writing onto a graphic device. |
NTmethod |
Character string used when
For the normal approximation to the binomial
( For the default situation of In all cases except the |
power , beta
|
Logical. If |
The graphs produced by this single function cover most of the first semester
introductory Statistics course. The htest
method plots the
results of the stats::t.test
function.
NormalAndTplot
is built on xyplot
.
Most of the arguments detailed in xyplot
documentation work to
control the appearance of the plot.
"trellis"
object.
This function is built on lattice and latticeExtra.
It supersedes the similar function
normal.and.t.dist
built on base graphics that is used in many
displays in the book by Erich Neuwirth and me: R through Excel, Springer
(2009).
https://link.springer.com/book/10.1007/978-1-4419-0052-4. Many details,
particularly the
alternate color scheme and the concept of floating probability labels,
grew out of discussions that Erich and I have had since the book was
published.
The method for "htest"
objects incorporates ideas that Jay Kerns and I developed at the 2011 UseR! conference.
This version incorporates some ideas suggested by Moritz Heene.
Richard M. Heiberger ([email protected])
NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=100, sd=12, mean1=113, xbar=105, xlim=c(92, 120), n=20) NTplot(mean0=100, sd=12, mean1=113, xbar=105, xlim=c(92, 120), n=20, zaxis=TRUE, z1axis=TRUE) NTplot(mean0=100, sd=12, xbar=105, xlim=c(92, 108), n=20, ntcolors="stoplight") NTplot(xbar=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025) x <- rnorm(12, mean=.78) x.t <- t.test(x) NTplot(x.t) NTplot(x.t, type="confidence") x.tg <- t.test(x, alternative="greater") NTplot(x.tg) y <- rnorm(12, mean=-.05) xy.t <- t.test(x, y) NTplot(xy.t) NTplot(xy.t, type="confidence") ## Not run: if (interactive()) NTplot(shiny=TRUE) ## with any other arguments for initialization of the shiny app. ## End(Not run) ## Not run: ## The partially transparent colors are: black127="#0000007F" ## HH:::ColorWithAlpha("black") green127="#00FF007F" ## HH:::ColorWithAlpha("green") blue127 ="#0000FF7F" ## HH:::ColorWithAlpha("blue") ## this is the default set of colors that are assigned when ## ntcolors="original" or when ntcolors is not specified c(col.alpha = "blue", col.notalpha = "lightblue", col.beta = "red", col.power = "pink", col.pvalue = "green", col.pvaluetranslucent = green127, col.critical = "gray50", col.border = black127, col.text = "black", col.conf = "lightgreen") NTplot( ) NTplot(mean1 = 2, ) NTplot( xbar=1) NTplot(mean1 = 2, xbar=1) NTplot(type="confidence") ## this is the set of colors that are assigned when ntcolors="stoplight" c(col.alpha = "red", col.notalpha = "honeydew2", col.beta = "orange", col.power = "pink", col.pvalue = "blue", col.pvaluetranslucent = blue127, col.critical = "gray50", col.border = black127, col.text = "black", col.conf = "lightgreen") NTplot( ntcolors="stoplight") NTplot(mean1 = 2, ntcolors="stoplight") NTplot( xbar=1, ntcolors="stoplight") NTplot(mean1 = 2, xbar=1, ntcolors="stoplight") NTplot(type="confidence", ntcolors="stoplight") ## this is the set of colors that are assigned when ntcolors="BW" c(col.alpha = "gray35", col.notalpha = "gray85", col.beta = "gray15", col.power = "gray40", col.pvalue = "gray50", col.pvaluetranslucent = HH:::ColorWithAlpha("gray65"), col.critical = "gray15", col.border = "gray75", col.text = "black", col.conf = "gray45") NTplot( ntcolors="BW") NTplot(mean1 = 2, ntcolors="BW") NTplot( xbar=1, ntcolors="BW") NTplot(mean1 = 2, xbar=1, ntcolors="BW") NTplot(type="confidence", ntcolors="BW") ## End(Not run) ## Not run: ## mean1 and xbar NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=-2, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=2, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=-2, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## mean1 NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5)) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## xbar NTplot(mean0=0, mean1=NA, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=NA, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=NA, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=NA, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## t distribution ## mean1 and xbar NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=2, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## mean1 NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## xbar NTplot(mean0=0, mean1=NA, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## confidence intervals NTplot(mean0=0, xlim=c(-3, 4), type="confidence") NTplot(xbar=01, xlim=c(-3, 4), type="confidence") NTplot(mean0=0, xlim=c(-4, 3), type="confidence", alpha.left=.05, alpha.right=0) NTplot(mean0=0, xlim=c(-3, 3), type="confidence", alpha.left=.025, alpha.right=.025) NTplot(mean0=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025) NTplot(mean0=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025, distribution="t", df=10) ## End(Not run)
NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=100, sd=12, mean1=113, xbar=105, xlim=c(92, 120), n=20) NTplot(mean0=100, sd=12, mean1=113, xbar=105, xlim=c(92, 120), n=20, zaxis=TRUE, z1axis=TRUE) NTplot(mean0=100, sd=12, xbar=105, xlim=c(92, 108), n=20, ntcolors="stoplight") NTplot(xbar=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025) x <- rnorm(12, mean=.78) x.t <- t.test(x) NTplot(x.t) NTplot(x.t, type="confidence") x.tg <- t.test(x, alternative="greater") NTplot(x.tg) y <- rnorm(12, mean=-.05) xy.t <- t.test(x, y) NTplot(xy.t) NTplot(xy.t, type="confidence") ## Not run: if (interactive()) NTplot(shiny=TRUE) ## with any other arguments for initialization of the shiny app. ## End(Not run) ## Not run: ## The partially transparent colors are: black127="#0000007F" ## HH:::ColorWithAlpha("black") green127="#00FF007F" ## HH:::ColorWithAlpha("green") blue127 ="#0000FF7F" ## HH:::ColorWithAlpha("blue") ## this is the default set of colors that are assigned when ## ntcolors="original" or when ntcolors is not specified c(col.alpha = "blue", col.notalpha = "lightblue", col.beta = "red", col.power = "pink", col.pvalue = "green", col.pvaluetranslucent = green127, col.critical = "gray50", col.border = black127, col.text = "black", col.conf = "lightgreen") NTplot( ) NTplot(mean1 = 2, ) NTplot( xbar=1) NTplot(mean1 = 2, xbar=1) NTplot(type="confidence") ## this is the set of colors that are assigned when ntcolors="stoplight" c(col.alpha = "red", col.notalpha = "honeydew2", col.beta = "orange", col.power = "pink", col.pvalue = "blue", col.pvaluetranslucent = blue127, col.critical = "gray50", col.border = black127, col.text = "black", col.conf = "lightgreen") NTplot( ntcolors="stoplight") NTplot(mean1 = 2, ntcolors="stoplight") NTplot( xbar=1, ntcolors="stoplight") NTplot(mean1 = 2, xbar=1, ntcolors="stoplight") NTplot(type="confidence", ntcolors="stoplight") ## this is the set of colors that are assigned when ntcolors="BW" c(col.alpha = "gray35", col.notalpha = "gray85", col.beta = "gray15", col.power = "gray40", col.pvalue = "gray50", col.pvaluetranslucent = HH:::ColorWithAlpha("gray65"), col.critical = "gray15", col.border = "gray75", col.text = "black", col.conf = "gray45") NTplot( ntcolors="BW") NTplot(mean1 = 2, ntcolors="BW") NTplot( xbar=1, ntcolors="BW") NTplot(mean1 = 2, xbar=1, ntcolors="BW") NTplot(type="confidence", ntcolors="BW") ## End(Not run) ## Not run: ## mean1 and xbar NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=-2, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=2, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=-2, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## mean1 NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5)) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## xbar NTplot(mean0=0, mean1=NA, xbar=1.8, xlim=c(-3, 5)) NTplot(mean0=0, mean1=NA, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0) NTplot(mean0=0, mean1=NA, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025) NTplot(mean0=0, mean1=NA, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025) ## t distribution ## mean1 and xbar NTplot(mean0=0, mean1=2, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=2, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## mean1 NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=2, xbar=NA, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=-2, xbar=NA, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## xbar NTplot(mean0=0, mean1=NA, xbar=1.8, xlim=c(-3, 5), distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=-1.8, xlim=c(-5, 3), alpha.left=.05, alpha.right=0, distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=2.1, xlim=c(-3, 5), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) NTplot(mean0=0, mean1=NA, xbar=-2.1, xlim=c(-5, 3), alpha.left=.025, alpha.right=.025, distribution.name="t", df=4) ## confidence intervals NTplot(mean0=0, xlim=c(-3, 4), type="confidence") NTplot(xbar=01, xlim=c(-3, 4), type="confidence") NTplot(mean0=0, xlim=c(-4, 3), type="confidence", alpha.left=.05, alpha.right=0) NTplot(mean0=0, xlim=c(-3, 3), type="confidence", alpha.left=.025, alpha.right=.025) NTplot(mean0=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025) NTplot(mean0=95, sd=10, xlim=c(65, 125), type="confidence", alpha.left=.025, alpha.right=.025, distribution="t", df=10) ## End(Not run)
Construct a power graph based on the NTplot
. The exported function
powerplot
calls NormalAndTPower
to construct a power curve or beta curve (operating
characteristic curve) (or both) from its argument and catenates it to the original
graph. The unexported function NormalAndTPower
does the
construction.
powerplot(nt, ...) ## S3 method for class 'NormalAndTplot' powerplot(nt, power=TRUE, beta=FALSE, ..., hh=if (power && beta) c(6,2,2) else c(6,2)) NormalAndTPower(nt, which=c("power","beta"), digits=4, digits.top.axis=digits, digits.left=digits, col.power=attr(nt, "color")["col.power"], col.beta=attr(nt, "color")["col.beta"], cex.pb.axis=1, cex.left.axis=1, cex.xbar=1, lwd.reference=4, lwd.line=2, main=which, ...)
powerplot(nt, ...) ## S3 method for class 'NormalAndTplot' powerplot(nt, power=TRUE, beta=FALSE, ..., hh=if (power && beta) c(6,2,2) else c(6,2)) NormalAndTPower(nt, which=c("power","beta"), digits=4, digits.top.axis=digits, digits.left=digits, col.power=attr(nt, "color")["col.power"], col.beta=attr(nt, "color")["col.beta"], cex.pb.axis=1, cex.left.axis=1, cex.xbar=1, lwd.reference=4, lwd.line=2, main=which, ...)
nt |
For the generic |
power , beta
|
Logical. If |
which |
Which graph is to be displayed? |
... |
Additional arguments passed on to methods. |
hh |
The |
digits.top.axis , digits.left , digits , cex.pb.axis , cex.left.axis , cex.xbar
|
|
col.power , col.beta
|
Colors used for the crosshairs on the power and beta
panels.
The default values are the colors used for the power and beta regions of the
|
lwd.reference , lwd.line
|
|
main |
Main title for graph. |
"trellis"
object.
Richard M. Heiberger ([email protected])
nt <- NTplot(mean0=2, mean1=4, sd=3, n=20, xlim=c(-.1, 6.1), xbar=3.5) powerplot(nt) ## Not run: tt <- NTplot(mean0=2, mean1=4, sd=3, n=20, xlim=c(-.1, 6.1), xbar=3.5, df=4, distribution.name="t") powerplot(tt) ntc <- NTplot(xbar=2, sd=3, n=20, xlim=c(-.1, 4.1), type="confidence", alpha.left=.025, alpha.right=.025) ntc try(powerplot(ntc)) ## End(Not run)
nt <- NTplot(mean0=2, mean1=4, sd=3, n=20, xlim=c(-.1, 6.1), xbar=3.5) powerplot(nt) ## Not run: tt <- NTplot(mean0=2, mean1=4, sd=3, n=20, xlim=c(-.1, 6.1), xbar=3.5, df=4, distribution.name="t") powerplot(tt) ntc <- NTplot(xbar=2, sd=3, n=20, xlim=c(-.1, 4.1), type="confidence", alpha.left=.025, alpha.right=.025) ntc try(powerplot(ntc)) ## End(Not run)
Plots to illustrate Normal Approximation to the Binomial—hypothesis tests or confidence intervals.
normalApproxBinomial(p0= if (number.vars==1) .5 else 0, p1=NA, p2=NA, p.hat=if (number.vars==1) .75 else 0, n=1, xlim=if (number.vars==1) c(0,1) else c(-1,1), ylim=c(0, 5), type=c("hypothesis","confidence"), alpha.left=if (type=="hypothesis") 0 else .025, alpha.right=if (type=="hypothesis") .05 else .025, xlab=if (number.vars==1) "w = p = population proportion" else "w = p[1] - p[2] :: population proportions", ..., number.vars=if (!is.na(p1) && !is.na(p2)) 2 else 1)
normalApproxBinomial(p0= if (number.vars==1) .5 else 0, p1=NA, p2=NA, p.hat=if (number.vars==1) .75 else 0, n=1, xlim=if (number.vars==1) c(0,1) else c(-1,1), ylim=c(0, 5), type=c("hypothesis","confidence"), alpha.left=if (type=="hypothesis") 0 else .025, alpha.right=if (type=="hypothesis") .05 else .025, xlab=if (number.vars==1) "w = p = population proportion" else "w = p[1] - p[2] :: population proportions", ..., number.vars=if (!is.na(p1) && !is.na(p2)) 2 else 1)
p0 |
Null hypothesis value of |
p1 |
Alternate hypothesis value of |
p2 |
Second sample value of |
p.hat |
Observed value of |
n |
Number of observations (for example, number of coins tossed). |
xlim , ylim , xlab
|
Standard |
type |
"hypothesis" for a Hypothesis Test graph, or "confidence" for a Confidence Interval graph. |
... , alpha.left , alpha.right
|
Additional arguments forwarded to |
number.vars |
Number of variables. 1 for a one-sample test, 2 for two-sample tests and paired tests. |
This is a wrapper function for the plots in NTplot
.
"trellis"
object.
Richard M. Heiberger ([email protected])
NTplot(distribution.name="binomial", n=20, ylim=c(0,4.2), p1=.8) NTplot(distribution.name="binomial", n=20, type="confidence", ylim=c(0,4.2)) ## Not run: NTplot(distribution.name="binomial", n=20, zaxis=TRUE, z1axis=TRUE, p1=.8678, ylim=c(0, 5.2)) NTplot(p0=.4, p.hat=.65, p1=.7, distribution.name="binomial", n=15) NTplot(p.hat=.65, distribution.name="binomial", n=15, type="confidence") ## End(Not run) ## Not run: ## these are interactive and won't work in R CMD check if (interactive()) NTplot(distribution.name="binomial", n=20, ylim=c(0,4.2), p1=.8, shiny=TRUE) if (interactive()) NTplot(p0=.4, p.hat=.65, p1=.7, distribution.name="binomial", n=15, shiny=TRUE) if (interactive()) NTplot(p.hat=.65, distribution.name="binomial", n=15, type="confidence", shiny=TRUE) ## End(Not run)
NTplot(distribution.name="binomial", n=20, ylim=c(0,4.2), p1=.8) NTplot(distribution.name="binomial", n=20, type="confidence", ylim=c(0,4.2)) ## Not run: NTplot(distribution.name="binomial", n=20, zaxis=TRUE, z1axis=TRUE, p1=.8678, ylim=c(0, 5.2)) NTplot(p0=.4, p.hat=.65, p1=.7, distribution.name="binomial", n=15) NTplot(p.hat=.65, distribution.name="binomial", n=15, type="confidence") ## End(Not run) ## Not run: ## these are interactive and won't work in R CMD check if (interactive()) NTplot(distribution.name="binomial", n=20, ylim=c(0,4.2), p1=.8, shiny=TRUE) if (interactive()) NTplot(p0=.4, p.hat=.65, p1=.7, distribution.name="binomial", n=15, shiny=TRUE) if (interactive()) NTplot(p.hat=.65, distribution.name="binomial", n=15, type="confidence", shiny=TRUE) ## End(Not run)
Count the number of parameters in an ARIMA model specification.
When arima==FALSE
, just the AR and MA parameters are counted.
When arima==TRUE
, then the number of difference parameters are
also included.
npar.arma(x, arima=FALSE) npar.sarma(model, arima=FALSE) npar.rarma(arma, arima=FALSE)
npar.arma(x, arima=FALSE) npar.sarma(model, arima=FALSE) npar.rarma(arma, arima=FALSE)
x |
An |
model |
A |
arma |
A |
arima |
Logical. |
A scalar number giving the count.
Richard M. Heiberger ([email protected])
co2.arima <- if.R(s= arima.mle(co2, list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) ,r= arima(co2, order=c(0,1,1), seasonal=list(order=c(0,1,1), period=12)) ) npar.arma(co2.arima) npar.arma(co2.arima, arima=TRUE) npar.sarma(list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) npar.sarma(list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12)), arima=TRUE) if.R(s={}, r=npar.rarma(co2.arima$arma) ) if.R(s={}, r=npar.rarma(co2.arima$arma, arima=TRUE) )
co2.arima <- if.R(s= arima.mle(co2, list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) ,r= arima(co2, order=c(0,1,1), seasonal=list(order=c(0,1,1), period=12)) ) npar.arma(co2.arima) npar.arma(co2.arima, arima=TRUE) npar.sarma(list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12))) npar.sarma(list(list(order=c(0,1,1)), list(order=c(0,1,1), period=12)), arima=TRUE) if.R(s={}, r=npar.rarma(co2.arima$arma) ) if.R(s={}, r=npar.rarma(co2.arima$arma, arima=TRUE) )
Specify plots to illustrate Normal and t Hypothesis Tests or Confidence Intervals, including normal approximation to the binomial.
NTplot(mean0, ...) ## Default S3 method: NTplot(mean0=0, ..., shiny=FALSE, distribution.name = c("normal","z","t","binomial")) ## S3 method for class 'htest' NTplot(mean0, ..., shiny=FALSE, NTmethod="htest") ## S3 method for class 'power.htest' NTplot(mean0, ..., shiny=FALSE, xbar=NA, ## these input values are used mean1, n, df, sd, distribution.name, sub, ## these input values ignored alpha.left, alpha.right, number.vars) ## these input values ignored ## NTplot(NTplot(htest.object), n=20) ## allows override of arguments ## S3 method for class 'NormalAndTplot' NTplot(mean0, ..., shiny=FALSE)
NTplot(mean0, ...) ## Default S3 method: NTplot(mean0=0, ..., shiny=FALSE, distribution.name = c("normal","z","t","binomial")) ## S3 method for class 'htest' NTplot(mean0, ..., shiny=FALSE, NTmethod="htest") ## S3 method for class 'power.htest' NTplot(mean0, ..., shiny=FALSE, xbar=NA, ## these input values are used mean1, n, df, sd, distribution.name, sub, ## these input values ignored alpha.left, alpha.right, number.vars) ## these input values ignored ## NTplot(NTplot(htest.object), n=20) ## allows override of arguments ## S3 method for class 'NormalAndTplot' NTplot(mean0, ..., shiny=FALSE)
mean0 |
For the default method, |
xbar |
See |
... |
Other arguments, selected from the options for the
default method |
shiny |
Logical. If |
htest |
logical. |
mean1 , n , df , sd , sub , alpha.left , alpha.right , number.vars
|
These variables are ignored here. They
are captured so they won't interfere with similarly named variables
that are generated in the |
distribution.name |
Ignored by |
NTmethod |
Character string used when |
The graphs produced by this single function cover most of the first semester
introductory Statistics course.
All options of the t.test
, power.t.test
, and z.test
are accepted and displayed.
NTplot
is built on xyplot
.
Most of the arguments detailed in xyplot
documentation work to
control the appearance of the plot.
The shiny app (called when the argument shiny=TRUE
)
provides animated sliders for the means, standard
deviation, xlimits, significance levels, df, and n. The df and n are
rounded to integers for the sliders (relevant for htest
and
power.htest
objects). Checkboxes and Radio buttons are available
for
various display options
When you have a graph on the shiny window that you wish to keep, click on the "Display Options" tab, and then on the "Display Call" radio button. The main shiny window will show an R command which will reproduce the current plot. Pick it up with the mouse and drop it into an R console window.
To get out of the shiny window and return to an interactive R console,
move the cursor back to the console window and interrupt the shiny call, usually
by entering Ctrl-C
or ESC
.
"trellis"
object. The object can be plotted or fed back into the
NTplot
function with argument shiny=TRUE
to allow
interactive graphical investigation of the hypothesis test or confidence
interval.
The attributes of the object\
NTobj <- NTplot()
\
attr(NTobj, "scales")
and attr(NTobj, "prob")
make the
data values and probability values accessible for further R
computations.
The "call"
attribute
cat(attr(NT.object, "call"), "\n")
displays a statement that can be copied back into R to reproduce the graph.
The cat()
is needed to unescape embedded quotes.
The "call.list"
attribute
attr(NT.object, "call.list")
is a list that can be used with do.call
to reproduce the graph.
do.call(NTplot, attr(NT.object, "call.list"))
. This is usually
not needed by the user because the simpler statement
NTplot(NT.object)
does it for you.
This function is built on lattice and latticeExtra.
It supersedes the similar function
normal.and.t.dist
built on base graphics that is used in many
displays in the book by Erich Neuwirth and me: R through Excel, Springer
(2009).
https://link.springer.com/book/10.1007/978-1-4419-0052-4. Many details,
particularly the
alternate color scheme and the concept of floating probability labels,
grew out of discussions that Erich and I have had since the book was
published.
It incorporates ideas that Jay Kerns and I developed at the 2011 UseR! conference.
This version incorporates some ideas suggested by Moritz Heene.
Richard M. Heiberger ([email protected])
NormalAndTplot
, print.NormalAndTplot
.
x1 <- rnorm(12) x2 <- rnorm(12, mean=.5) NT.object <- NTplot(mean0=0, mean1=1) NT.object attr(NT.object, "scales") attr(NT.object, "prob") cat(attr(NT.object, "call"), "\n") ## the cat() is needed to unescape embedded quotes. NTplot(t.test(x1, x2)) NTplot(power.t.test(power = .90, delta = 1, alternative = "one.sided")) ## Not run: ## 22 distinct calls are shown in demo(NTplot, ask=FALSE) ## End(Not run) ## Not run: ## these are interactive and do not work in static checking of the code if (interactive()) NTplot(mean0=0, mean1=1, shiny=TRUE) if (interactive()) NTplot(shiny=TRUE, px.height=475) ## default value is 575 if (interactive()) NTplot(t.test(x1, x2), shiny=TRUE, mean1=1) if (interactive()) NTplot(power.t.test(power = .90, delta = 1, alternative = "one.sided"), shiny=TRUE) if (interactive()) NTplot(NT.object, shiny=TRUE) ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/NTplot", package="HH")) ## End(Not run)
x1 <- rnorm(12) x2 <- rnorm(12, mean=.5) NT.object <- NTplot(mean0=0, mean1=1) NT.object attr(NT.object, "scales") attr(NT.object, "prob") cat(attr(NT.object, "call"), "\n") ## the cat() is needed to unescape embedded quotes. NTplot(t.test(x1, x2)) NTplot(power.t.test(power = .90, delta = 1, alternative = "one.sided")) ## Not run: ## 22 distinct calls are shown in demo(NTplot, ask=FALSE) ## End(Not run) ## Not run: ## these are interactive and do not work in static checking of the code if (interactive()) NTplot(mean0=0, mean1=1, shiny=TRUE) if (interactive()) NTplot(shiny=TRUE, px.height=475) ## default value is 575 if (interactive()) NTplot(t.test(x1, x2), shiny=TRUE, mean1=1) if (interactive()) NTplot(power.t.test(power = .90, delta = 1, alternative = "one.sided"), shiny=TRUE) if (interactive()) NTplot(NT.object, shiny=TRUE) ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/NTplot", package="HH")) ## End(Not run)
Loop objects()
through all attached directories
(items in the search()
list) looking for a regular expression pattern.
objip(pattern, where = search(), all.names=FALSE, mode="any", class, ls.function=if (mode != "any" || !missing(class)) "ls.str" else "ls")
objip(pattern, where = search(), all.names=FALSE, mode="any", class, ls.function=if (mode != "any" || !missing(class)) "ls.str" else "ls")
pattern |
Character string containing a regular expression that is used to list only a subset of the objects. Only names matching 'pattern' are returned. |
where |
an object defining a database in the search list. |
all.names |
In R, a logical that is passed to the |
mode , class
|
See |
ls.function |
Either |
A list of 0 or more character vectors. Each character vector has the
name of one of the items in the search()
list. Each character
vector contains the names of the objects in the specified environment
which match the pattern
. If there are no matching names in an
environment, then the corresponding character vector is removed from the
result.
Richard M. Heiberger <[email protected]>
ls
,
objip("qq") objip("^qq") objip("qq$") ## Not run: ## R only objip("rowSums", all.names=TRUE) ## list all objects in the second and third attached packages search() objip()[2:3] ## End(Not run)
objip("qq") objip("^qq") objip("qq$") ## Not run: ## R only objip("rowSums", all.names=TRUE) ## list all objects in the second and third attached packages search() objip()[2:3] ## End(Not run)
Calculate or plot the odds ratio for a 2x2 table of counts. The plot shows the confidence intervals on the probability of row2 for fixed odds ratio and specified probability for row1.
OddsRatio(x, alpha = 0.05) plotOddsRatio(x, ylab="prob(col1 | row1)", xlab="prob(col1 | row2)", alpha=c(.50, .05), col=trellis.par.get("superpose.line")$col, lwd=trellis.par.get("superpose.line")$lwd, lwd.reference=1, ...) plotOddsRatio.base(x, ylab = "prob(col1 | row1)", xlab = "prob(col1 | row2)", alpha = c(0.05, 0.5), legend.x=1.05, oma=c(0,0,0,5), ...)
OddsRatio(x, alpha = 0.05) plotOddsRatio(x, ylab="prob(col1 | row1)", xlab="prob(col1 | row2)", alpha=c(.50, .05), col=trellis.par.get("superpose.line")$col, lwd=trellis.par.get("superpose.line")$lwd, lwd.reference=1, ...) plotOddsRatio.base(x, ylab = "prob(col1 | row1)", xlab = "prob(col1 | row2)", alpha = c(0.05, 0.5), legend.x=1.05, oma=c(0,0,0,5), ...)
x |
2 x 2 table of counts |
alpha |
Significance levels of test.
|
xlab , ylab
|
x- and y-labels for the plot Sensible defaults are generated. |
col , lwd
|
Colors and linewidths to be used in the graph. |
lwd.reference |
linewidth for reference line. |
... |
other arguments, currently ignored. |
legend.x |
x position of left-hand side of legend. |
oma |
outer margin |
plotOddsRatio
returns a lattice object.
The older plotOddsRatio.base
draws a plot with base graphics and invisibly returns the same
list as OddsRatio
returns for the first value of alpha
.
OddsRatio
returns the list:
p1 , p2
|
proportion of each row total observed in the first column. |
omega1 , omega2
|
odds for each row, p/(1-p) |
psihat |
odds ratio, omega2/omega1 |
s.ln.psihat |
standard deviation of |
ci.ln.psihat |
confidence interval for |
ci.psihat |
confidence interval for |
prob1 |
|
odds1 |
|
odds2 |
odds for the second row needed to retain |
ci.odds2 |
confidence interval for |
prob2 |
|
ci.prob2 |
|
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(glasses) ## draw the iso-odds ratio plot with 50% CI and 95% CI, plotOddsRatio(glasses) ## return the 95% CI information OddsRatio(glasses) ## draw the iso-odds ratio plot with 50% CI and 95% CI, ## invisibly return the 95% CI information plotOddsRatio.base(glasses)
data(glasses) ## draw the iso-odds ratio plot with 50% CI and 95% CI, plotOddsRatio(glasses) ## return the 95% CI information OddsRatio(glasses) ## draw the iso-odds ratio plot with 50% CI and 95% CI, ## invisibly return the 95% CI information plotOddsRatio.base(glasses)
bwplot
of the data by group, of the group
means, and of the entire dataset. This is an approximate visualization
of the Mean Square lines from the ANOVA table for a one-way ANOVA model.
Displays a three-panel bwplot
of the data by group, of the group
means, and of the entire dataset. This is an approximate visualization
of the Mean Square lines from the ANOVA table for a one-way ANOVA model.
The groups are centered using medians by default. Means, and anything
else, is an option.
OneWayVarPlot(x, data, ..., main="Variability of Groups, Centers of Groups, and all Data", centerFunctionName="median", center=TRUE)
OneWayVarPlot(x, data, ..., main="Variability of Groups, Centers of Groups, and all Data", centerFunctionName="median", center=TRUE)
x |
Model formula with one response variable and one factor. |
data |
|
... |
Other arguments to be forwarded to the panel function. |
main |
|
centerFunctionName |
Name of centering function, with
|
center |
Logical. If |
Three-panel trellis
object.
Richard M. Heiberger <[email protected]>
data(batch) OneWayVarPlot(Calcium ~ Batch, data = batch)
data(batch) OneWayVarPlot(Calcium ~ Batch, data = batch)
Construct an orthogonal matrix which is an arbitrary completion of the column space of the input set of columns.
orthog.complete(x, normalize=TRUE, abs2.rows=1:nrow(x), Int=TRUE, drop.Int=Int) orthog.construct(y, x, x.rows, normalize=FALSE)
orthog.complete(x, normalize=TRUE, abs2.rows=1:nrow(x), Int=TRUE, drop.Int=Int) orthog.construct(y, x, x.rows, normalize=FALSE)
x |
For |
y |
matrix of coefficients specifying the linear combinations
estimated. This will usually be the |
normalize , abs2.rows , x.rows
|
The default normalizes the
sum of squares of the rows
in |
Int |
logical. Default |
drop.Int |
logical. The default is to drop the constant column and to keep all columns when the constant is not automatically generated. |
This function is based on qr.Q
. The input matrix x
has
n
rows and an arbitrary non-zero number of columns. The result
is an n
by n
orthogonal matrix. By default the first
column of the result is constant and is not returned. The second
column of the result is orthogonal to the first result column.
Together the first two result columns span the space of the constant
column and the first input column. The third result column is
orthogonal to the first two result columns and the the three result
columns together span the space of the constant column and the first
two inout columns. Similarly for the remaining result columns.
Result columns beyond the number of input columns are constructed as
an arbitrary orthogonal completion.
If the input columns are orthogonal to each other and to the constant column, then the result columns are rescaled versions of the input columns.
Optionally (drop.Int=FALSE
), the constant column can be returned.
By default the columns are scaled to have sum of squares equal 1. If
normalize="abs2"
, they are scaled to make the sum of all
positive value equal 1 and the sum of all negative values equal .
Together, the sum of the absolute values of each column is 2.
If the input is a set of columns from a contrast matrix for a design
that has multiple terms, the abs2.rows
argument is used to
specify which rows are to be included in the normalization. These
will normally be rows associated with one of the main effects.
Matrix of orthogonal columns.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0))) ) zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0)), drop.Int=FALSE) ) zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0)), normalize="abs2") ) ## used in MMC plots tmp <- data.frame(y=rnorm(12), a=factor(c("u","u","u","u", "v","v","v","v", "w","w","w","w"))) tmp.aov <- aov(y ~ a, data=tmp) lmat <- if.R( s=multicomp(tmp.aov, focus="a")$lmat, r={lmat.reduced <- t(glht(tmp.aov, linfct=mcp(a="Tukey"))$linfct) rbind(lmat.reduced, AU=-apply(lmat.reduced[-1,], 2, sum)) }) zapsmall(lmat) lmat.complete <- orthog.complete(lmat, abs2.rows=-1, normalize="abs2", drop.Int=FALSE)[,1:3] zapsmall(lmat.complete) if.R(r=zapsmall(lmat.complete[-4,]), s={})
zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0))) ) zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0)), drop.Int=FALSE) ) zapsmall( orthog.complete(cbind("4-12"=c(-1,-1, 0, 2), "1-2" =c( 1,-1, 0, 0)), normalize="abs2") ) ## used in MMC plots tmp <- data.frame(y=rnorm(12), a=factor(c("u","u","u","u", "v","v","v","v", "w","w","w","w"))) tmp.aov <- aov(y ~ a, data=tmp) lmat <- if.R( s=multicomp(tmp.aov, focus="a")$lmat, r={lmat.reduced <- t(glht(tmp.aov, linfct=mcp(a="Tukey"))$linfct) rbind(lmat.reduced, AU=-apply(lmat.reduced[-1,], 2, sum)) }) zapsmall(lmat) lmat.complete <- orthog.complete(lmat, abs2.rows=-1, normalize="abs2", drop.Int=FALSE)[,1:3] zapsmall(lmat.complete) if.R(r=zapsmall(lmat.complete[-4,]), s={})
Panel functions for tsdiagplot
.
panel.acf(..., n.used) panel.std.resid(...) panel.gof(...)
panel.acf(..., n.used) panel.std.resid(...) panel.gof(...)
... |
standard arguments to panel functions. |
n.used |
number of lags. THis number is needed to calculate the
confidence interval which is |
Richard M. Heiberger ([email protected])
panel.axis.right
is almost identical to
panel.axis
.
axis.RightAdjustRight
is almost identical to axis.default
.
The only difference is that these functions right-justify right-axis tick labels.
panel.axis.right(side = c("bottom", "left", "top", "right"), at = pretty(scale.range), labels = TRUE, draw.labels = TRUE, check.overlap = FALSE, outside = FALSE, ticks = TRUE, half = !outside, which.half = switch(side, bottom = "lower", left = "upper", top = "upper", right = "lower"), tck = as.numeric(ticks), rot = if (is.logical(labels)) 0 else c(90, 0), text.col = axis.text$col, text.alpha = axis.text$alpha, text.cex = axis.text$cex, text.font = axis.text$font, text.fontfamily = axis.text$fontfamily, text.fontface = axis.text$fontface, text.lineheight = axis.text$lineheight, line.col = axis.line$col, line.lty = axis.line$lty, line.lwd = axis.line$lwd, line.alpha = axis.line$alpha) axis.RightAdjustRight(side = c("top", "bottom", "left", "right"), scales, components, as.table, labels = c("default", "yes", "no"), ticks = c("default", "yes", "no"), ..., prefix = lattice.lattice.getStatus("current.prefix"))
panel.axis.right(side = c("bottom", "left", "top", "right"), at = pretty(scale.range), labels = TRUE, draw.labels = TRUE, check.overlap = FALSE, outside = FALSE, ticks = TRUE, half = !outside, which.half = switch(side, bottom = "lower", left = "upper", top = "upper", right = "lower"), tck = as.numeric(ticks), rot = if (is.logical(labels)) 0 else c(90, 0), text.col = axis.text$col, text.alpha = axis.text$alpha, text.cex = axis.text$cex, text.font = axis.text$font, text.fontfamily = axis.text$fontfamily, text.fontface = axis.text$fontface, text.lineheight = axis.text$lineheight, line.col = axis.line$col, line.lty = axis.line$lty, line.lwd = axis.line$lwd, line.alpha = axis.line$alpha) axis.RightAdjustRight(side = c("top", "bottom", "left", "right"), scales, components, as.table, labels = c("default", "yes", "no"), ticks = c("default", "yes", "no"), ..., prefix = lattice.lattice.getStatus("current.prefix"))
side , at , labels , draw.labels , check.overlap , outside , ticks , half , which.half
|
See |
tck , rot , text.col , text.alpha , text.cex , text.font , text.fontfamily
|
See |
text.fontface , text.lineheight , line.col , line.lty , line.lwd , line.alpha
|
See |
scales , components , as.table , ... , prefix
|
See |
Deepayan Sarkar [email protected]
wrote
panel.axis
and axis.default
.
David Winsemius wrote the modification panel.axis.right
.
Richard Heiberger [email protected]
wrote the modification axis.RightAdjustRight
.
Richard Heiberger is maintaining this
distribution of both functions.
Panel function for bwplot
that give the user
control over the placement of the boxes. When used with a positioned
factor, the boxes are placed according to the position associated with
the factor.
panel.bwplot.intermediate.hh(x, y, horizontal = TRUE, pch, col, lwd, ...)
panel.bwplot.intermediate.hh(x, y, horizontal = TRUE, pch, col, lwd, ...)
x , y , pch , col , lwd , horizontal
|
see
|
... |
Extra arguments, if any, for 'panel.bwplot'. |
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R, Second Edition. Springer Texts in Statistics. Springer. ISBN 978-1-4939-2121-8.
panel.xyplot
,
xyplot
, interaction2wt
,
position
## see examples at ## Not run: demo("bwplot.examples", package="HH") ## End(Not run)
## see examples at ## Not run: demo("bwplot.examples", package="HH") ## End(Not run)
Panel function for bwplot that displays an entire box (central dot, box,
umbrella, outliers) in the same color, coded by the groups argument.
The function is based on panel.superpose
.
panel.bwplot.superpose(x, y, ..., groups=groups, col=rep(trellis.par.get("superpose.symbol")$col, length=length(groups)), pch=trellis.par.get("box.dot")$pch, panel.groups=panel.bwplot.groups) panel.bwplot.groups(..., col, pch, fill, fill.alpha=NULL, group.number)
panel.bwplot.superpose(x, y, ..., groups=groups, col=rep(trellis.par.get("superpose.symbol")$col, length=length(groups)), pch=trellis.par.get("box.dot")$pch, panel.groups=panel.bwplot.groups) panel.bwplot.groups(..., col, pch, fill, fill.alpha=NULL, group.number)
x , y
|
Standard arguments to a lattice panel function.
When |
... |
Additional lattice arguments. |
groups |
Factor to be used for color coding entire boxes: central dot, rectangle, umbrella, and outlier symbol. |
col |
Colors to be assigned to the levels of the group. The default colors
are taken from |
pch |
Standard lattice arguments.
The |
fill , fill.alpha
|
These are related to the similarly named arguments in |
panel.groups , group.number
|
See |
panel.bwplot.superpose
is the user-level function.
panel.bwplot.groups
is the panel.groups
function called by panel.superpose
.
Richard M. Heiberger <[email protected]>
position
, panel.bwplot.intermediate.hh
,
panel.superpose
tmp <- data.frame(Response=rnorm(20), Group=factor(rep(LETTERS[1:3], c(5,7,8)))) bwplot(Group ~ Response, data=tmp, main="Default panel.bwplot, groups ignored", groups=Group) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose", groups=Group, panel=panel.bwplot.superpose) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose with fill specified", groups=Group, panel=panel.bwplot.superpose, fill.alpha=.33) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose, with color specified", groups=Group, panel=panel.bwplot.superpose, col=c("forestgreen","blue", "brown")) Test <- data.frame(id=rep(letters, each=4), Week=rep(c(0,1,3,6), 26), Treatment=rep(factor(c("A","B"), levels=c("A","B")), each=52), y=rep(1:4, 52) + rep(4:5, each=52) + rnorm(104), stringsAsFactors=FALSE) Test$WeekTrt <- with(Test, interaction(Week, Treatment)) position(Test$Week) <- unique(Test$Week) position(Test$WeekTrt) <- as.vector(outer(position(Test$Week), c(-.2, .2), `+`)) tapply(Test$y, Test[c("Week", "Treatment")], median) bwplot( y ~ WeekTrt, groups = Treatment, data = Test, main="default panel.bwplot, groups ignored") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7))), main="Minimal use of panel.bwplot.superpose") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7), at=position(Test$Week))), box.width=.3, xlab="Week", pch=c(17, 16), key=list(col=trellis.par.get()$superpose.symbol$col[1:2], border=TRUE, title="Treatment", cex.title=1, columns=2, text=list(levels(Test$Treatment)), points=list(pch=c(17, 16))), par.settings=list(plot.symbol=list(pch=c(17, 16), cex=.5)), main="panel.bwplot.superpose with additional annotations") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7), at=position(Test$Week))), box.width=.3, xlab="Week", pch=c(17, 16), key=list(col=trellis.par.get()$superpose.symbol$col[1:2], border=TRUE, title="Treatment", cex.title=1, columns=2, text=list(levels(Test$Treatment)), points=list(pch=c(17, 16))), par.settings=list(plot.symbol=list(pch=c(17, 16), cex=.5)), main="panel.bwplot.superpose with fill and more complex panel.groups", panel.groups = function(...) { panel.stripplot(...) panel.bwplot.groups(...) }, fill.alpha=.33, jitter.data = TRUE)
tmp <- data.frame(Response=rnorm(20), Group=factor(rep(LETTERS[1:3], c(5,7,8)))) bwplot(Group ~ Response, data=tmp, main="Default panel.bwplot, groups ignored", groups=Group) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose", groups=Group, panel=panel.bwplot.superpose) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose with fill specified", groups=Group, panel=panel.bwplot.superpose, fill.alpha=.33) bwplot(Group ~ Response, data=tmp, main="panel.bwplot.superpose, with color specified", groups=Group, panel=panel.bwplot.superpose, col=c("forestgreen","blue", "brown")) Test <- data.frame(id=rep(letters, each=4), Week=rep(c(0,1,3,6), 26), Treatment=rep(factor(c("A","B"), levels=c("A","B")), each=52), y=rep(1:4, 52) + rep(4:5, each=52) + rnorm(104), stringsAsFactors=FALSE) Test$WeekTrt <- with(Test, interaction(Week, Treatment)) position(Test$Week) <- unique(Test$Week) position(Test$WeekTrt) <- as.vector(outer(position(Test$Week), c(-.2, .2), `+`)) tapply(Test$y, Test[c("Week", "Treatment")], median) bwplot( y ~ WeekTrt, groups = Treatment, data = Test, main="default panel.bwplot, groups ignored") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7))), main="Minimal use of panel.bwplot.superpose") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7), at=position(Test$Week))), box.width=.3, xlab="Week", pch=c(17, 16), key=list(col=trellis.par.get()$superpose.symbol$col[1:2], border=TRUE, title="Treatment", cex.title=1, columns=2, text=list(levels(Test$Treatment)), points=list(pch=c(17, 16))), par.settings=list(plot.symbol=list(pch=c(17, 16), cex=.5)), main="panel.bwplot.superpose with additional annotations") bwplot( y ~ WeekTrt, groups = Treatment, data = Test, panel=panel.bwplot.superpose, scales=list(x=list(limits=c(-1, 7), at=position(Test$Week))), box.width=.3, xlab="Week", pch=c(17, 16), key=list(col=trellis.par.get()$superpose.symbol$col[1:2], border=TRUE, title="Treatment", cex.title=1, columns=2, text=list(levels(Test$Treatment)), points=list(pch=c(17, 16))), par.settings=list(plot.symbol=list(pch=c(17, 16), cex=.5)), main="panel.bwplot.superpose with fill and more complex panel.groups", panel.groups = function(...) { panel.stripplot(...) panel.bwplot.groups(...) }, fill.alpha=.33, jitter.data = TRUE)
Extension to S-Plus trellis to allow transposed plots. All x - and y-components of the trellis object are interchanged. This function is not needed in R as lattice has a horizontal argument in its definitions.
panel.bwplott(x, y, box.ratio = 1, font = box.dot$font, pch = box.dot$pch, cex = box.dot$cex, col = box.dot$col, ..., transpose=FALSE)
panel.bwplott(x, y, box.ratio = 1, font = box.dot$font, pch = box.dot$pch, cex = box.dot$cex, col = box.dot$col, ..., transpose=FALSE)
x , y , box.ratio , font , pch , cex , col , ...
|
See
|
transpose |
logical. If |
The function is used for its side effect of drawing boxplots in a trellis panel.
This function is not needed in R. If it is used and
Richard M. Heiberger <[email protected]>
trellis panel function, with labeled rows and columns and without strip labels. Designed for use with the ladder of powers plot.
panel.cartesian(x, y, x.label=unique(panel.labels[,"x"]), y.label=unique(panel.labels[,"y"]), group.label.side="", axis3.line=1, xg.label, yg.label, g.cex=.7, rescale=list(x=TRUE,y=TRUE), ..., browser.on=FALSE)
panel.cartesian(x, y, x.label=unique(panel.labels[,"x"]), y.label=unique(panel.labels[,"y"]), group.label.side="", axis3.line=1, xg.label, yg.label, g.cex=.7, rescale=list(x=TRUE,y=TRUE), ..., browser.on=FALSE)
x , y
|
x and y as for any other panel function |
x.label |
labels for the columns of the scatterplot matrix |
y.label |
labels for the rows of the scatterplot matrix |
axis3.line |
The |
group.label.side |
|
xg.label |
group labels for rows of the scatterplot matrix |
yg.label |
group labels for rows of the scatterplot matrix |
g.cex |
|
rescale |
alternate way to get something similar to |
... |
other arguments |
browser.on |
logical, normally |
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(rent) ## Weisberg's file alr162 rent.lm <- lm(rnt.alf ~ rnt.till + cow.dens + lime, data=rent) rent$resid.rent <- resid(rent.lm) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=2.4, scales=list( relation="same", alternating=FALSE, labels=FALSE, ticks=FALSE), between=list(x=1, y=3)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list( relation="same", alternating=FALSE, labels=FALSE, ticks=FALSE), rescale=list(x=FALSE, y=FALSE), between=list(x=1, y=3)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list( relation="free", alternating=FALSE, labels=FALSE, ticks=FALSE), between=list(x=1, y=3)) tmp <- xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", y.label="resid", group.label.side="top", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list(alternating=FALSE, labels=FALSE, ticks=FALSE), rescale=list(x=FALSE, y=FALSE), between=list(x=4, y=5)) if.R(r=tmp$par.settings <- list(layout.widths=list(right.padding=4)), s={}) tmp
data(rent) ## Weisberg's file alr162 rent.lm <- lm(rnt.alf ~ rnt.till + cow.dens + lime, data=rent) rent$resid.rent <- resid(rent.lm) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=2.4, scales=list( relation="same", alternating=FALSE, labels=FALSE, ticks=FALSE), between=list(x=1, y=3)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list( relation="same", alternating=FALSE, labels=FALSE, ticks=FALSE), rescale=list(x=FALSE, y=FALSE), between=list(x=1, y=3)) xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", x.label="", y.label="", group.label.side="", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list( relation="free", alternating=FALSE, labels=FALSE, ticks=FALSE), between=list(x=1, y=3)) tmp <- xysplom(resid.rent ~ rnt.till + cow.dens | lime, data=rent, layout=c(2,2), xlab="", ylab="", y.label="resid", group.label.side="top", par.strip.text=list(cex=1.2), panel=panel.cartesian, axis3.line=3.6, scales=list(alternating=FALSE, labels=FALSE, ticks=FALSE), rescale=list(x=FALSE, y=FALSE), between=list(x=4, y=5)) if.R(r=tmp$par.settings <- list(layout.widths=list(right.padding=4)), s={}) tmp
This is the default panel function for ci.plot
.
panel.ci.plot(x, y, newdata, newfit = newfit, ...)
panel.ci.plot(x, y, newdata, newfit = newfit, ...)
x |
Observed values of predictor variable. |
y |
Observed values of response variable. |
newdata |
|
newfit |
|
... |
other arguments passed to |
Richard M. Heiberger <[email protected]>
Confidence interval panel for MMC tiebreaker plots, or confidence interval plot.
panel.confintMMC(x, y, subscripts, ..., col, lwd, lty, lower, upper, contrast.name, right.text.cex = 0.8, contrast.height=FALSE)
panel.confintMMC(x, y, subscripts, ..., col, lwd, lty, lower, upper, contrast.name, right.text.cex = 0.8, contrast.height=FALSE)
x |
means |
y |
When called from |
subscripts |
Index into the |
... |
Additional arguments are ignored. |
col , lty , lwd
|
Standard lattice arguments. |
lower |
Vector of lower bounds for the intervals. |
upper |
Vector of upper bounds for the intervals. |
contrast.name |
Names of the contrasts. |
right.text.cex |
The right axis has non-standard controls. |
contrast.height |
Logical. The alternate |
Richard M. Heiberger <[email protected]>
See mmc
for the references and examples.
Dotplot with evenly spaced tiebreakers. Multiple hits on a specific x value are stacked.
panel.dotplot.tb(x, y, factor=.1, jitter.data=TRUE, horizontal=TRUE, max.freq=max(sapply(subsets, length)), ...)
panel.dotplot.tb(x, y, factor=.1, jitter.data=TRUE, horizontal=TRUE, max.freq=max(sapply(subsets, length)), ...)
x , y
|
See |
factor |
jitter factor, see |
jitter.data , horizontal
|
Always |
max.freq |
maximum number of observation at any combination of
response values, factor levels, and group levels.
If the formula includes one or more conditioning factors, then the
user is responsible for providing a value for |
... |
Other arguments for |
Creates (possibly grouped) Dotplot of x against y. y is the ‘factor’.
If the formula includes one or more conditioning factors, then the
user is responsible for providing a value for max.freq
.
The default behavior is a different max.freq
for each panel
in a multi-panel display.
Richard M. Heiberger
Maintainer: Richard M. Heiberger <[email protected]>
x <- c(1,1,2,2,2,5,4,2,1,5) y <- factor(letters[rep(1:2, 5)]) dotplot(x, panel=panel.dotplot.tb) dotplot(x, panel=panel.dotplot.tb, factor=.2) dotplot(y ~ x, panel=panel.dotplot.tb) dotplot(y ~ x, panel=panel.dotplot.tb, cex=1.5, factor=.15) quiz <- data.frame(scores=sample(10, 360, replace=TRUE), date=rep(rep(c("0902", "0916", "0930"), c(40,40,40)), 3), section=rep( c("Stat1-3", "Stat1-5", "Stat1-8"), c(120,120,120))) dotplot(date ~ scores | section, data=quiz, panel=panel.dotplot.tb, factor=.5) dotplot(date ~ scores | section, data=quiz, panel=panel.dotplot.tb, factor=.5, layout=c(1,3), between=list(y=1), main='Three quizzes for three sections of Stat 1') ## If the formula includes one or more conditioning factors, then the ## user is responsible for providing a value for the argument max.freq ## a <- rep(1, 10) z <- c(1,1,2,2,2,3,2,3,1,1) g <- LETTERS[c(1,1,1,1,1,2,2,2,2,2)] print(split=c(1,1,2,1), more=TRUE, dotplot( a ~ z | g, panel=panel.dotplot.tb, factor=.6, cex=1.5, layout=c(2,1), main="different scaling in each panel") ) print(split=c(2,1,2,1), more=FALSE, dotplot( a ~ z | g, panel=panel.dotplot.tb, max.freq=3, factor=.6, cex=1.5, layout=c(2,1), main="same scaling in each panel") )
x <- c(1,1,2,2,2,5,4,2,1,5) y <- factor(letters[rep(1:2, 5)]) dotplot(x, panel=panel.dotplot.tb) dotplot(x, panel=panel.dotplot.tb, factor=.2) dotplot(y ~ x, panel=panel.dotplot.tb) dotplot(y ~ x, panel=panel.dotplot.tb, cex=1.5, factor=.15) quiz <- data.frame(scores=sample(10, 360, replace=TRUE), date=rep(rep(c("0902", "0916", "0930"), c(40,40,40)), 3), section=rep( c("Stat1-3", "Stat1-5", "Stat1-8"), c(120,120,120))) dotplot(date ~ scores | section, data=quiz, panel=panel.dotplot.tb, factor=.5) dotplot(date ~ scores | section, data=quiz, panel=panel.dotplot.tb, factor=.5, layout=c(1,3), between=list(y=1), main='Three quizzes for three sections of Stat 1') ## If the formula includes one or more conditioning factors, then the ## user is responsible for providing a value for the argument max.freq ## a <- rep(1, 10) z <- c(1,1,2,2,2,3,2,3,1,1) g <- LETTERS[c(1,1,1,1,1,2,2,2,2,2)] print(split=c(1,1,2,1), more=TRUE, dotplot( a ~ z | g, panel=panel.dotplot.tb, factor=.6, cex=1.5, layout=c(2,1), main="different scaling in each panel") ) print(split=c(2,1,2,1), more=FALSE, dotplot( a ~ z | g, panel=panel.dotplot.tb, max.freq=3, factor=.6, cex=1.5, layout=c(2,1), main="same scaling in each panel") )
This is the panel function for interaction2wt
. The main diagonal
displays boxplots for the main effects of each factor. The
off-diagonals show the interaction plots for each pair of factors.
The i,j
panel shows the same factors as the j,i
but with
the trace- and x-factor roles interchanged.
panel.interaction2wt(x, y, subscripts, responselab, trace.values, factor.levels, factor.position, fun = mean, se, type="l", ..., box.ratio, simple=FALSE, simple.offset, simple.scale, simple.pch, data.x, col.by.row=TRUE, col =trellis.par.get("superpose.line")$col, lty =trellis.par.get("superpose.line")$lty, lwd =trellis.par.get("superpose.line")$lwd, alpha=trellis.par.get("superpose.line")$alpha ) strip.interaction2wt(which.given, which.panel, var.name, factor.levels, shingle.intervals, strip.names = c(TRUE, TRUE), style = 1, ...)
panel.interaction2wt(x, y, subscripts, responselab, trace.values, factor.levels, factor.position, fun = mean, se, type="l", ..., box.ratio, simple=FALSE, simple.offset, simple.scale, simple.pch, data.x, col.by.row=TRUE, col =trellis.par.get("superpose.line")$col, lty =trellis.par.get("superpose.line")$lty, lwd =trellis.par.get("superpose.line")$lwd, alpha=trellis.par.get("superpose.line")$alpha ) strip.interaction2wt(which.given, which.panel, var.name, factor.levels, shingle.intervals, strip.names = c(TRUE, TRUE), style = 1, ...)
panel.interaction2wt
arguments:
x |
levels of x-factor |
y |
Summary value of response variable at each level of x- and trace-factors. |
subscripts |
used to get the right set of response values for the summary statistics on the off-diagonals |
responselab |
Character name of response variable, defaults to the name of the response variable. |
trace.values |
levels of trace-factor |
fun |
Summary function, defaults to |
se |
standard errors to be passed to |
,
type |
See |
,
box.ratio |
passed to |
,
... |
extra arguments, primarily color,
to be passed to |
factor.position |
|
simple |
logical. If |
simple.offset , simple.scale
|
named list of offset and scale for the
response and trace factors. |
simple.pch |
Named list containing plotting characters for each
level of one or more of the factors. |
data.x |
|
col.by.row |
logical. If |
col , lty , lwd , alpha
|
Arguments to
|
strip.interaction2wt
arguments
which.given , which.panel , var.name , factor.levels , shingle.intervals
|
see documentation
for |
.
strip.names |
Force |
style |
force |
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
interaction2wt
,
panel.bwplot.intermediate.hh
## Not run: tmp <- data.frame(y=rnorm(48), A=factor(rep(1:2, 24)), B=factor(rep(rep(1:3, each=2), 8)), C=factor(rep(rep(1:4, each=6), 2))) interaction2wt(y ~ A+B+C, data=tmp, key.in=list(x=-3), ## key.in is ignored by R xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, key.in=list(x=-2), xlim=c(.4, 4.5)) position(tmp$B) <- c(1, 2.4, 3.8) interaction2wt(y ~ B+C, data=tmp, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(A=c(1:2), B=c(3:5), C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(A=c(1:2)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(B=c(16,17,18)), key.in=list(x=-2), xlim=c(.4, 4.5), se=TRUE) ## End(Not run)
## Not run: tmp <- data.frame(y=rnorm(48), A=factor(rep(1:2, 24)), B=factor(rep(rep(1:3, each=2), 8)), C=factor(rep(rep(1:4, each=6), 2))) interaction2wt(y ~ A+B+C, data=tmp, key.in=list(x=-3), ## key.in is ignored by R xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, key.in=list(x=-2), xlim=c(.4, 4.5)) position(tmp$B) <- c(1, 2.4, 3.8) interaction2wt(y ~ B+C, data=tmp, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(A=c(1:2), B=c(3:5), C=c(16,17,18,19)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ C+B, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(A=c(1:2)), key.in=list(x=-2), xlim=c(.4, 4.5)) interaction2wt(y ~ B+C, data=tmp, simple=TRUE, simple.scale=list(B=.18, C=.27), box.ratio=.2, simple.pch=list(B=c(16,17,18)), key.in=list(x=-2), xlim=c(.4, 4.5), se=TRUE) ## End(Not run)
isomeans grid for MMC plots.
panel.isomeans(ybar, lty.iso=7, col.iso='darkgray', lwd.iso=1, lty.contr0=2, col.contr0='darkgray', lwd.contr0=1, ..., col, lwd, lty ## capture potentially ambiguous name )
panel.isomeans(ybar, lty.iso=7, col.iso='darkgray', lwd.iso=1, lty.contr0=2, col.contr0='darkgray', lwd.contr0=1, ..., col, lwd, lty ## capture potentially ambiguous name )
ybar |
Vector of means. |
lty.iso , col.iso , lwd.iso
|
color, line type, line width for the isomeans grid. |
lty.contr0 , col.contr0 , lwd.contr0
|
color, line type, line width for the vertical contrast=0 line. |
... |
ignore any additional arguments |
col , lwd , lty
|
ignore these arguments. They are captured here to avoid
ambiguity with |
Richard M. Heiberger <[email protected]>
See mmc
for the references and examples.
panel.barchart2
is based on panel.barchart
The changes are
* the heights in each horizontal stacked bar are constant.
* the widths in each vertical stacked bar are constant.
* the panel.barchart heights and widths are based on the box.width argument.
* the panel.barchart2 heights and widths when stack==TRUE
are also based
on the new stackWidth
argument.
panel.likert
calls panel.barchart2
scaling of stackWidth
:stackWidth <- stackWidth/mean(stackWidth) ## and maybe smaller with another /2
panel.barchart2(x, y, box.ratio = 1, box.width = box.ratio/(1 + box.ratio), horizontal = TRUE, origin = NULL, reference = TRUE, stack = FALSE, groups = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, ..., identifier = "barchart", stackWidth=NULL) panel.likert(..., horizontal=TRUE, reference.line.col="gray65")
panel.barchart2(x, y, box.ratio = 1, box.width = box.ratio/(1 + box.ratio), horizontal = TRUE, origin = NULL, reference = TRUE, stack = FALSE, groups = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, ..., identifier = "barchart", stackWidth=NULL) panel.likert(..., horizontal=TRUE, reference.line.col="gray65")
x , y , box.ratio , box.width , horizontal , origin , reference , stack , groups , col
|
See |
border , lty , lwd , identifier
|
See |
... |
Extra arguments, if any, for |
stackWidth |
Heights in each horizontal stacked bar, when
stack=TRUE, are constant and specified by this argument. We
recommend starting with |
reference.line.col |
See |
Richard M. Heiberger <[email protected]>
Function based on S-Plus panel.pairs
to add the subpanel.scales
and
panel.cex
arguments. In R, this is an alias for panel.pairs
.
panel.pairs.hh(x, y, z, subscripts, pscales, subpanel = panel.splom, varnames = dimnames(x)[[2]], ..., subpanel.scales, panel.cex=par()$cex)
panel.pairs.hh(x, y, z, subscripts, pscales, subpanel = panel.splom, varnames = dimnames(x)[[2]], ..., subpanel.scales, panel.cex=par()$cex)
x , y , z , subscripts , pscales , subpanel , varnames , ...
|
See
in S-Plus. |
subpanel.scales |
Controls the size of the tick labels in the diagonal panel. |
panel.cex |
Controls the size of the variable names in the diagonal panel. |
"trellis" object
.
Richard M. Heiberger <[email protected]>
splom
in S-Plus.
if.R(s={ longley <- data.frame(longley.x, Employed = longley.y) },r={ data(longley) }) if.R(s= splom( ~ longley, pch=16, cex=.55, superpanel=panel.pairs.hh, subpanel.scales=list(cex=.8), pscales=2, panel.cex=.8) ,r= splom( ~ longley, pch=16, pscales=2, varname.cex=.8, axis.text.cex=.5) )
if.R(s={ longley <- data.frame(longley.x, Employed = longley.y) },r={ data(longley) }) if.R(s= splom( ~ longley, pch=16, cex=.55, superpanel=panel.pairs.hh, subpanel.scales=list(cex=.8), pscales=2, panel.cex=.8) ,r= splom( ~ longley, pch=16, pscales=2, varname.cex=.8, axis.text.cex=.5) )
panel method for xysplom. It has a corr
argument that is
removed
before sending the information on to panel.xyplot.
panel.xysplom(corr, ...)
panel.xysplom(corr, ...)
corr |
logical. If |
... |
Remaining arguments to |
Richard M. Heiberger <[email protected]>
The partial correlation of x and y conditioning on z is the ordinary correlation of the residuals from the regression of x on z and the regression of y on z.
partial.corr(vars, cond)
partial.corr(vars, cond)
vars |
matrix of data.frame of all the variables to be correlated. |
cond |
matrix of data.frame of all the variables to be conditioned on. |
matrix of partial correlations of the numeric variables in the argument
vars
conditioning on the numeric variables in cond
.
Richard M. Heiberger <[email protected]>
if.R(r= partial.corr(longley[,1:3], longley[,4:6]) ,s= partial.corr(longley.x[,1:3], longley.x[,4:6]) )
if.R(r= partial.corr(longley[,1:3], longley[,4:6]) ,s= partial.corr(longley.x[,1:3], longley.x[,4:6]) )
Construct a "pdf"
file from a "latex"
file. See latex
for concepts.
pdf.latex(latex.object, ..., file, overwrite = TRUE, copy.mode = TRUE, copy.date = TRUE)
pdf.latex(latex.object, ..., file, overwrite = TRUE, copy.mode = TRUE, copy.date = TRUE)
latex.object |
Result from a call to |
... |
Optional arguments to |
file |
File name in |
overwrite |
If the file already exists, |
copy.mode , copy.date
|
If |
Filename of class "dvi"
Richard M. Heiberger <[email protected]>
## you will normally need these options. See ?Hmisc::latex for details. options(latexcmd='pdflatex') options(dviExtension='pdf') options(xdvicmd='open') ## Macintosh, Windows, SMP linux ## Not run: ## these examples place files in your current working directory ## matrix tmp <- array(1:20, c(4,5), list(LETTERS[1:4], LETTERS[5:9])) tmp pdf.latex(latex(tmp)) ## for matrix, accept the default structure.tex and structure.pdf filenames. pdf.latex(latex(tmp, title="tmp")) ## specify name of .tex and .pdf file. ## 3D array tmp3 <- array(1:40, c(4,5,2), list(LETTERS[1:4], LETTERS[5:9], LETTERS[10:11])) tmp3 pdf.latex(latex(tmp3)) ## for array, the default base filename is the ## name of the argument, hence tmp3.tex and tmp3.pdf pdf.latex(latex(tmp3, title="somethingelse")) ## or specify somethingelse ## End(Not run)
## you will normally need these options. See ?Hmisc::latex for details. options(latexcmd='pdflatex') options(dviExtension='pdf') options(xdvicmd='open') ## Macintosh, Windows, SMP linux ## Not run: ## these examples place files in your current working directory ## matrix tmp <- array(1:20, c(4,5), list(LETTERS[1:4], LETTERS[5:9])) tmp pdf.latex(latex(tmp)) ## for matrix, accept the default structure.tex and structure.pdf filenames. pdf.latex(latex(tmp, title="tmp")) ## specify name of .tex and .pdf file. ## 3D array tmp3 <- array(1:40, c(4,5,2), list(LETTERS[1:4], LETTERS[5:9], LETTERS[10:11])) tmp3 pdf.latex(latex(tmp3)) ## for array, the default base filename is the ## name of the argument, hence tmp3.tex and tmp3.pdf pdf.latex(latex(tmp3, title="somethingelse")) ## or specify somethingelse ## End(Not run)
Discrete Uniform Distribution
pdiscunif(q, size) qdiscunif(p, size) ddiscunif(q, size) rdiscunif(n, size)
pdiscunif(q, size) qdiscunif(p, size) ddiscunif(q, size) rdiscunif(n, size)
size |
parameter of distribution. Numbers from 1 to size are equally likely. |
q |
Quantiles. |
p |
Probability. |
n |
number of items in the random sample. |
Richard M. Heiberger <[email protected]>
q <- seq(-.5, 7.5, .5) pp <- pdiscunif(q, 6) ## xyplot(pp ~ q, ## scales=list( ## x=list(at=floor(min(q)):ceiling(max(q))), ## y=list(at=seq(0, 1, .1)))) qq <- qdiscunif(pp, 6) dd <- ddiscunif(q, 6) cbind(q, pp, qq, dd) rdiscunif(12, 6)
q <- seq(-.5, 7.5, .5) pp <- pdiscunif(q, 6) ## xyplot(pp ~ q, ## scales=list( ## x=list(at=floor(min(q)):ceiling(max(q))), ## y=list(at=seq(0, 1, .1)))) qq <- qdiscunif(pp, 6) dd <- ddiscunif(q, 6) cbind(q, pp, qq, dd) rdiscunif(12, 6)
Helper functions for regr2.plot
.
perspPlane(x, y, z, persp.out, ...) perspFloor(x, y, z, persp.out, ...) perspBack.wall.x(x, y, z, persp.out, ...) perspBack.wall.y(x, y, z, persp.out, ...)
perspPlane(x, y, z, persp.out, ...) perspFloor(x, y, z, persp.out, ...) perspBack.wall.x(x, y, z, persp.out, ...) perspBack.wall.y(x, y, z, persp.out, ...)
x , y , z
|
Arguments to |
persp.out |
Result from previous call to |
... |
Additional arguments to |
Richard M. Heiberger <[email protected]>
Oneway analysis of variance makes the assumption that the variances of
the groups are equal.
Brown and Forsyth, 1974 present the recommended test of this assumption.
The Brown and Forsyth test statistic is the statistic resulting
from an ordinary one-way analysis of variance on the
absolute deviations from the median. The
hovPlot
function
graphs the components of the Brown and Forsyth test statistic.
hovPlot(x, data=NULL, method = "bf", ## x is a formula transpose = TRUE, ...) ## users will normally use the formula above and will not call the ## method directly. hovPlot.bf(x, group, ## x is the response variable y.name = deparse(substitute(x)), group.name = deparse(substitute(group)), transpose = TRUE, ...) ## users will normally use the formula above and will not call the ## panel function directly. panel.hov(..., transpose = TRUE)
hovPlot(x, data=NULL, method = "bf", ## x is a formula transpose = TRUE, ...) ## users will normally use the formula above and will not call the ## method directly. hovPlot.bf(x, group, ## x is the response variable y.name = deparse(substitute(x)), group.name = deparse(substitute(group)), transpose = TRUE, ...) ## users will normally use the formula above and will not call the ## panel function directly. panel.hov(..., transpose = TRUE)
x |
Formula appropriate for oneway anova in |
data |
data.frame |
method |
Character string defining method. At this time the only recognized method is "bf" for the Brown-Forsyth method. |
transpose |
Always |
group |
factor. |
y.name |
name of response variable, defaults to variable name in formula. |
group.name |
name of factor, defaults to variable name in formula. |
... |
additional arguments. |
"trellis"
object with three panels containing boxplots for each
group: The observed data "y"
, the data with the median
subtracted "y-med(y)"
, and the absolute deviations from the
median "abs(y-med(y))"
The Brown and Forsyth test statistic is
the statistic resulting from an ordinary one-way analysis of
variance on the data points in the third panel.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Brown, M.~B. and Forsyth, A.~B. (1974). Robust tests for equality of variances. Journal of the American Statistical Association, 69:364–367.
data(turkey) hov(wt.gain ~ diet, data=turkey) hovPlot(wt.gain ~ diet, data=turkey)
data(turkey) hov(wt.gain ~ diet, data=turkey) hovPlot(wt.gain ~ diet, data=turkey)
MMC (Mean–mean Multiple Comparisons) plot. The plot
method documented
here is no longer recommended for R; use mmcplot
instead.
This method is still necessary for S-Plus.
## S3 method for class 'mmc.multicomp' plot(x, xlab="contrast value", ylab=none$ylabel, focus=none$focus, main= main.method.phrase, main2=main2.method.phrase, main.method.phrase= paste("multiple comparisons of means of", ylab), main2.method.phrase=paste("simultaneous ", 100*(1-none$alpha),"% confidence limits, ", method, " method", sep="" ), ry.mmc=TRUE, key.x=par()$usr[1]+ diff(par()$usr[1:2])/20, key.y=par()$usr[3]+ diff(par()$usr[3:4])/3, method=if (is.null(mca)) lmat$method else mca$method, print.lmat=(!is.null(lmat)), print.mca=(!is.null(mca) && (!print.lmat)), iso.name=TRUE, x.offset=0, col.mca.signif="red", col.mca.not.signif="black", lty.mca.signif=1, lty.mca.not.signif=6, lwd.mca.signif=1, lwd.mca.not.signif=1, col.lmat.signif="blue", col.lmat.not.signif="black", lty.lmat.signif=1, lty.lmat.not.signif=6, lwd.lmat.signif=1, lwd.lmat.not.signif=1, lty.iso=7, col.iso="darkgray", lwd.iso=1, lty.contr0=2, col.contr0="darkgray", lwd.contr0=1, decdigits.ybar=2, ... )
## S3 method for class 'mmc.multicomp' plot(x, xlab="contrast value", ylab=none$ylabel, focus=none$focus, main= main.method.phrase, main2=main2.method.phrase, main.method.phrase= paste("multiple comparisons of means of", ylab), main2.method.phrase=paste("simultaneous ", 100*(1-none$alpha),"% confidence limits, ", method, " method", sep="" ), ry.mmc=TRUE, key.x=par()$usr[1]+ diff(par()$usr[1:2])/20, key.y=par()$usr[3]+ diff(par()$usr[3:4])/3, method=if (is.null(mca)) lmat$method else mca$method, print.lmat=(!is.null(lmat)), print.mca=(!is.null(mca) && (!print.lmat)), iso.name=TRUE, x.offset=0, col.mca.signif="red", col.mca.not.signif="black", lty.mca.signif=1, lty.mca.not.signif=6, lwd.mca.signif=1, lwd.mca.not.signif=1, col.lmat.signif="blue", col.lmat.not.signif="black", lty.lmat.signif=1, lty.lmat.not.signif=6, lwd.lmat.signif=1, lwd.lmat.not.signif=1, lty.iso=7, col.iso="darkgray", lwd.iso=1, lty.contr0=2, col.contr0="darkgray", lwd.contr0=1, decdigits.ybar=2, ... )
x |
|
xlab |
|
ylab |
name of response variable |
focus |
define the factor to compute contrasts of. |
main , main2
|
main and second line of title of plot |
main.method.phrase , main2.method.phrase
|
default expressions for title of plot |
ry.mmc |
range of values on the y-axis. It is similar to
|
key.x , key.y
|
location of the key displayed when |
method |
method used to construct contrasts and confidence
intervals. See the |
print.lmat |
logical. If |
print.mca |
logical. If |
iso.name |
logical. If |
x.offset |
amount to move the vertical 0 line to the left or right to reduce overprinting of labels and plotted lines. |
col.mca.signif , lty.mca.signif , lwd.mca.signif
|
color, line type, line width for significant pairwise contrasts. |
col.mca.not.signif , lty.mca.not.signif , lwd.mca.not.signif
|
color, line type, line width for non-significant pairwise contrasts. |
col.lmat.signif , lty.lmat.signif , lwd.lmat.signif
|
color, line type, line width for significant user-specified contrasts. |
col.lmat.not.signif , lty.lmat.not.signif , lwd.lmat.not.signif
|
color, line type, line width for non-significant user-specified contrasts. |
lty.iso , col.iso , lwd.iso
|
color, line type, line width for the isomeans grid. |
lty.contr0 , col.contr0 , lwd.contr0
|
color, line type, line width for the vertical contrast=0 line. |
decdigits.ybar |
number of decimal digits in the left-axis labels. |
... |
other arguments, currently ignored. |
plot.mmc.multicomp
chooses sensible defaults for its many
arguments. They will often need manual adjustment. The examples show
several types of adjustments. We have changed the centering and scaling
to avoid overprinting of label information. By default the significant
contrasts are shown in a more intense color than the nonsignificant
contrasts.
We have an option to reduce the color intensity of the isomeans grid.
When there is overprinting of labels (a consequence of level means being
close together), a tiebreaker plot may be needed. See ?MMC
for
an example.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, Richard M. and Holland, Burt (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
Hsu, J. and Peruggia, M. (1994). "Graphical representations of Tukey's multiple comparison method." Journal of Computational and Graphical Statistics, 3:143–161.
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) ## See ?MMC to see why these contrasts are chosen catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.mmc <- if.R(r={mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat)} ,s={multicomp.mmc(catalystm1.aov, focus.lmat=catalystm.lmat, plot=FALSE)} ) ## Not run: ## pairwise contrasts, default settings plot(catalystm.mmc, print.lmat=FALSE) ## End(Not run) ## Centering, scaling, emphasize significant contrasts. ## Needed in R with 7in x 7in default plot window. ## Not needed in S-Plus with 4x3 aspect ratio of plot window. plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), print.lmat=FALSE) ## user-specified contrasts plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58)) ## reduce intensity of isomeans grid, number isomeans grid lines plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), lty.iso=2, col.iso='darkgray', iso.name=FALSE) ## both pairwise contrasts and user-specified contrasts plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), lty.iso=2, col.iso='darkgray', print.mca=TRUE) ## Not run: ## newer mmcplot mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, type="lmat") ## End(Not run)
data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) ## See ?MMC to see why these contrasts are chosen catalystm.lmat <- cbind("AB-D" =c( 1, 1, 0,-2), "A-B" =c( 1,-1, 0, 0), "ABD-C"=c( 1, 1,-3, 1)) dimnames(catalystm.lmat)[[1]] <- levels(catalystm$catalyst) catalystm.mmc <- if.R(r={mmc(catalystm1.aov, linfct = mcp(catalyst = "Tukey"), focus.lmat=catalystm.lmat)} ,s={multicomp.mmc(catalystm1.aov, focus.lmat=catalystm.lmat, plot=FALSE)} ) ## Not run: ## pairwise contrasts, default settings plot(catalystm.mmc, print.lmat=FALSE) ## End(Not run) ## Centering, scaling, emphasize significant contrasts. ## Needed in R with 7in x 7in default plot window. ## Not needed in S-Plus with 4x3 aspect ratio of plot window. plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), print.lmat=FALSE) ## user-specified contrasts plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58)) ## reduce intensity of isomeans grid, number isomeans grid lines plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), lty.iso=2, col.iso='darkgray', iso.name=FALSE) ## both pairwise contrasts and user-specified contrasts plot(catalystm.mmc, x.offset=2.1, ry.mmc=c(50,58), lty.iso=2, col.iso='darkgray', print.mca=TRUE) ## Not run: ## newer mmcplot mmcplot(catalystm.mmc) mmcplot(catalystm.mmc, type="lmat") ## End(Not run)
Multiple comparisons plot that gives independent user control
over the appearance of the significant and not significant
comparisons.
In R, both plot.multicomp
plot.multicomp.hh
coerce their argument
to an "glht"
object and plots
that with the appropriate plot
method.
In R, plot.multicomp.adjusted
replaces the bounds
calculated by multcomp:::confint.glht
with bounds based on
a common standard error for a set of anova tables that are
partitioned for the simple effects on an analysis conditioned on
the levels of one of the factors.
In S-Plus,
plot.multicomp.hh
augments the standard plot.multicomp
to
give additional user arguments to control the appearance of the plot.
plotMatchMMC
uses the plot.multicomp.hh
code.
plotMatchMMC
must immediately follow a plot of an
mmc.multicomp
object and is applied to either the $mca
or $lmat
component of the mmc.multicomp
object.
plotMatchMMC
is used as a tiebreaker plot for the MMC
plot. plotMatchMMC
matches the horizontal scaling of the
MMC
plot and displays the individual contrasts in the same
order as the MMC
plot. See mmc
for examples.
These functions are no longer recommended. Use mmcplot
instead.
## S3 method for class 'multicomp' plot(x, ...) ## R only ## S3 method for class 'multicomp.hh' plot(x, ylabel = x$ylabel, href = 0, uniform = TRUE, plt.in = c(0.2, 0.9, 0.1, 0.9), x.label.adj=1, xrange.include=href, xlim, comparisons.per.page=21, col.signif=1, col.not.signif=1, lty.signif=4, lty.not.signif=4, lwd.signif=1, lwd.not.signif=1, ..., xlabel.print=TRUE, y.axis.side=2, ylabel.inside=FALSE) plotMatchMMC(x, ..., xlabel.print=FALSE, cex.axis=par()$cex.axis, col.signif='red', main="", ylabel.inside=FALSE, y.axis.side=4, adjusted=FALSE)
## S3 method for class 'multicomp' plot(x, ...) ## R only ## S3 method for class 'multicomp.hh' plot(x, ylabel = x$ylabel, href = 0, uniform = TRUE, plt.in = c(0.2, 0.9, 0.1, 0.9), x.label.adj=1, xrange.include=href, xlim, comparisons.per.page=21, col.signif=1, col.not.signif=1, lty.signif=4, lty.not.signif=4, lwd.signif=1, lwd.not.signif=1, ..., xlabel.print=TRUE, y.axis.side=2, ylabel.inside=FALSE) plotMatchMMC(x, ..., xlabel.print=FALSE, cex.axis=par()$cex.axis, col.signif='red', main="", ylabel.inside=FALSE, y.axis.side=4, adjusted=FALSE)
x |
A |
ylabel |
Y label on graph. |
y.axis.side |
Y labels are on the left by default when plotting a
|
... |
other arguments to |
ylabel.inside |
Logical value, if |
href |
reference line for the intervals. The default is 0. S-Plus only. |
xrange.include |
|
uniform |
S-Plus only. Logical value, if |
plt.in |
S-Plus only. Value for |
x.label.adj |
S-Plus only. This is the |
xlim |
x-range of the plot. |
comparisons.per.page |
The default S-Plus |
lty.signif , lwd.signif
|
Line type, and line width for significant comparisons. S-Plus only. |
col.signif |
Color for significant comparisons. S-Plus only for
|
col.not.signif , lty.not.signif , lwd.not.signif
|
Color, line type, and line width for non-significant comparisons. S-Plus only. |
xlabel.print |
logical. When |
cex.axis |
|
main |
Main title for plot. |
adjusted |
Logical. When |
plot.multicomp
plots a "multicomp"
object. In S-Plus, this
masks the standard plot.multicomp
in order to provide additional
arguments for controlling the appearance. It defaults to the standard
appearance. In R, it coerces its argument to a "glht"
object and plots
that with the appropriate plot
method.
The multiple comparisons calculations in R and S-Plus use
completely different packages.
Multiple comparisons in R are based on glht
.
Multiple comparisons in S-Plus are based on multicomp
.
The MMC plot in the HH package is the same in both systems. The details of getting the plot differ.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Heiberger, R. M. and Holland, B. (2006). "Mean–mean multiple comparison displays for families of linear contrasts." Journal of Computational and Graphical Statistics, 15:937–955.
## data and ANOVA data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) catalystm.mca <- if.R(r=glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")), s=multicomp(catalystm1.aov, plot=FALSE)) if.R(s=plot(catalystm.mca), r=plot(confint(catalystm.mca, calpha=qtukey(.95, 4, 12)/sqrt(2)))) ## calpha is strongly recommended in R with a large number of levels ## See ?MMC for details.
## data and ANOVA data(catalystm) catalystm1.aov <- aov(concent ~ catalyst, data=catalystm) summary(catalystm1.aov) catalystm.mca <- if.R(r=glht(catalystm1.aov, linfct = mcp(catalyst = "Tukey")), s=multicomp(catalystm1.aov, plot=FALSE)) if.R(s=plot(catalystm.mca), r=plot(confint(catalystm.mca, calpha=qtukey(.95, 4, 12)/sqrt(2)))) ## calpha is strongly recommended in R with a large number of levels ## See ?MMC for details.
The default values for plotting a factor x
are the integers
1:length(levels(x))
. These functions provide a way of
specifying alternate plotting locations for the levels.
position(x) position(x) <- value ## S3 method for class 'positioned' is.numeric(x, ...) ## S3 method for class 'positioned' as.numeric(x, ...) ## S3 method for class 'positioned' x[..., drop=FALSE] ## S3 method for class 'positioned' is.na(x) as.positioned(x) as.position(x) is.positioned(x) positioned(x, ..., value) ## S3 method for class 'positioned' print(x, ...) ## S3 method for class 'positioned' unique(x, incomparables = FALSE, ...) unpositioned(x, ...)
position(x) position(x) <- value ## S3 method for class 'positioned' is.numeric(x, ...) ## S3 method for class 'positioned' as.numeric(x, ...) ## S3 method for class 'positioned' x[..., drop=FALSE] ## S3 method for class 'positioned' is.na(x) as.positioned(x) as.position(x) is.positioned(x) positioned(x, ..., value) ## S3 method for class 'positioned' print(x, ...) ## S3 method for class 'positioned' unique(x, incomparables = FALSE, ...) unpositioned(x, ...)
x |
numeric vector or factor |
value |
numerical values to be
associated with |
... |
other arguments. |
drop |
See
|
incomparables |
See
|
position(x) <- value
first forces its argument to be an ordered
factor and then assigns the value
to the "position"
attribute of the ordered factor.
The result is assigned class "positioned"
and returned.
position(x)
returns the position values associated with
levels(x)
. If x
is a positioned factor, then
the "position"
attribute is returned.
If x
is a factor, then the integers
1:length(levels(x))
are returned. For anything else,
as.numeric(x)
is returned.
as.position(x)
returns a numeric vector the length of the
original vector. If x
inherits from "factor"
,
then the values in the vector are the values in
position(x)
subscripted by the levels of the factor.
If x
is numeric, then x
itself is returned.
unpositioned(x)
removes the "position"
attribute and
removes the "positioned"
value from the the class
of
the object.
Richard M. Heiberger <[email protected]>
## ordered with character levels defaults to ## integer position of specified levels tmp <- ordered(c("mm","cm","m","m","mm","cm"), levels=c("mm","cm","m")) ## size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## position is assigned to ordered in specified order tmp <- ordered(c("cm","mm","m","m","mm","cm"), levels=c("mm","cm","m")) ## size order levels(tmp) position(tmp) <- c(-3, -2, 0) ## log10 assigned in size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## numeric stays numeric tmp <- c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## factor with numeric levels, position is integer position in size order tmp <- factor(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## ordered with numeric levels, position is numeric value in size order tmp <- ordered(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## factor with numeric levels ## position is assigned in size order tmp <- factor(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) levels(tmp) position(tmp) <- c(-3, -2, 0) ## log10 assigned in size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## boxplots coded by week tmp <- data.frame(Y=rnorm(40, rep(c(20,25,15,22), 10), 5), week=ordered(rep(1:4, 10))) position(tmp$week) <- c(1, 2, 4, 8) bwplot(Y ~ week, horizontal=FALSE, scales=list(x=list(limits=c(0,9), at=position(tmp$week), labels=position(tmp$week))), data=tmp, panel=panel.bwplot.intermediate.hh) #### You probably don't want to use the next two examples. #### You need to be aware of their behavior. ## ## factor with character levels defaults to ## integer position of sorted levels. ## you probably DON'T want to do this! tmp <- factor(c("cm","mm","m","m","mm","cm")) ## default alphabetic order tmp as.numeric(tmp) levels(tmp) ## you probably DON'T want to do this! position(tmp) ## you probably DON'T want to do this! as.numeric(tmp) ## ## position is assigned to factor in default alphabetic order. ## you probably DON'T want to do this! tmp <- factor(c("cm","mm","m","m","mm","cm")) levels(tmp) position(tmp) <- c(-3, -2, 0) ## assigned in default alphabetic order tmp as.numeric(tmp) levels(tmp) ## you probably DON'T want to do this! position(tmp) ## you probably DON'T want to do this! as.numeric(tmp)
## ordered with character levels defaults to ## integer position of specified levels tmp <- ordered(c("mm","cm","m","m","mm","cm"), levels=c("mm","cm","m")) ## size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## position is assigned to ordered in specified order tmp <- ordered(c("cm","mm","m","m","mm","cm"), levels=c("mm","cm","m")) ## size order levels(tmp) position(tmp) <- c(-3, -2, 0) ## log10 assigned in size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## numeric stays numeric tmp <- c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## factor with numeric levels, position is integer position in size order tmp <- factor(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## ordered with numeric levels, position is numeric value in size order tmp <- ordered(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## factor with numeric levels ## position is assigned in size order tmp <- factor(c(0.010, 0.001, 1.000, 1.000, 0.001, 0.010)) levels(tmp) position(tmp) <- c(-3, -2, 0) ## log10 assigned in size order tmp as.numeric(tmp) levels(tmp) position(tmp) as.position(tmp) as.positioned(tmp) positioned(tmp) unpositioned(tmp) unique(tmp) ## boxplots coded by week tmp <- data.frame(Y=rnorm(40, rep(c(20,25,15,22), 10), 5), week=ordered(rep(1:4, 10))) position(tmp$week) <- c(1, 2, 4, 8) bwplot(Y ~ week, horizontal=FALSE, scales=list(x=list(limits=c(0,9), at=position(tmp$week), labels=position(tmp$week))), data=tmp, panel=panel.bwplot.intermediate.hh) #### You probably don't want to use the next two examples. #### You need to be aware of their behavior. ## ## factor with character levels defaults to ## integer position of sorted levels. ## you probably DON'T want to do this! tmp <- factor(c("cm","mm","m","m","mm","cm")) ## default alphabetic order tmp as.numeric(tmp) levels(tmp) ## you probably DON'T want to do this! position(tmp) ## you probably DON'T want to do this! as.numeric(tmp) ## ## position is assigned to factor in default alphabetic order. ## you probably DON'T want to do this! tmp <- factor(c("cm","mm","m","m","mm","cm")) levels(tmp) position(tmp) <- c(-3, -2, 0) ## assigned in default alphabetic order tmp as.numeric(tmp) levels(tmp) ## you probably DON'T want to do this! position(tmp) ## you probably DON'T want to do this! as.numeric(tmp)
The default values for plotting a factor x
are the integers
1:length(levels(x))
. This class and its functions provide a way of
specifying alternate plotting locations for the levels.
A virtual Class: No objects may be created from it.
Class "ordered"
, directly.
Class "factor"
, by class "ordered", distance 2.
Class "oldClass"
, by class "ordered", distance 3.
No methods defined with class "positioned" in the signature.
S3-type methods are
"[.positioned"
,
as.double.positioned
,
as.numeric.positioned
,
as.positioned
,
is.numeric.positioned
,
is.positioned
,
positioned
,
print.positioned
,
unique.positioned
.
Although interaction.positioned
should be a method, it isn't
because interaction
is not a generic and can't easily be made one
since the name interaction.plot
conflicts.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
latticeresids
object.
Print a latticeresids
object.
## S3 method for class 'latticeresids' print(x, ..., A321.left=0, A321.bottom=0.27, A4.left=0, A4.top=0.30, position=list( A321=c(A321.left, A321.bottom, 1, 1 ), A4 =c(A4.left, 0, 1, A4.top)), panel.width=NULL, which=1:4)
## S3 method for class 'latticeresids' print(x, ..., A321.left=0, A321.bottom=0.27, A4.left=0, A4.top=0.30, position=list( A321=c(A321.left, A321.bottom, 1, 1 ), A4 =c(A4.left, 0, 1, A4.top)), panel.width=NULL, which=1:4)
x |
A |
A321.left , A321.bottom , A4.left , A4.top , position
|
The first three rows are on the same |
panel.width |
the |
which |
Vector of row numbers which are to be printed. If not
all four printed, consider adjusting the |
... |
Other arguments for |
The four trellis objects, one for each type of plot, are printed as a single four-row lattice object.
Richard M. Heiberger <[email protected]>
Print method for Normal and t plots from NTplot.
## S3 method for class 'NormalAndTplot' print(x, tablesOnPlot=TRUE, plot=TRUE, scales=FALSE, prob=FALSE, call=FALSE, ..., cex.table=.7, digits=attr(x, "call.list")$digits, position.2=.17)
## S3 method for class 'NormalAndTplot' print(x, tablesOnPlot=TRUE, plot=TRUE, scales=FALSE, prob=FALSE, call=FALSE, ..., cex.table=.7, digits=attr(x, "call.list")$digits, position.2=.17)
x |
A |
tablesOnPlot |
Logical. If |
plot |
Logical. If |
scales , prob
|
Logical. If |
call |
Logical. If |
... |
Other arguments are ignored. |
cex.table , digits
|
|
position.2 |
When |
The argument is returned invisibly.
Richard M. Heiberger ([email protected])
Print a "tsdiagplot"
object.
## S3 method for class 'tsdiagplot' print(x, ..., portrait=FALSE) print1.tsdiagplot(x) print2.tsdiagplot(x)
## S3 method for class 'tsdiagplot' print(x, ..., portrait=FALSE) print1.tsdiagplot(x) print2.tsdiagplot(x)
x |
a |
... |
Optional arguments to |
portrait |
logical. If |
A "tsdiagplot"
object is a collection of several
"trellis"
objects. We provide two options for printing them.
Richard M. Heiberger ([email protected])
Print two conformable trellis plots in adjacent columns with user control of widths. Left y tick-labels and left.strip are removed from the right-hand plot.
as.TwoTrellisColumns5(left, ## left is the left trellis object right, ## right is the right trellis object ## Both left and right must have identical ## settings for number and size of vertical panels, ## left-axis labels, number of lines in main, sub, legend. ..., pw=c(.3, .30, .01, .30, .09), px=list( LL=c(0, pwc[1]), LP=pwc[1:2], ML=pwc[2:3], RP=pwc[3:4], RL=pwc[4:5]), pwc=cumsum(pw), strip.left=TRUE, y.tck=c(0,0) ) ## S3 method for class 'TwoTrellisColumns5' print(x, px=attr(x, "px"), ...) leftLabels.trellis(x) rightLabels.trellis(x) panelOnly.trellis(x, strip.left=FALSE, y.tck=0) mainSubLegend.trellis(x) emptyRightAxis(x)
as.TwoTrellisColumns5(left, ## left is the left trellis object right, ## right is the right trellis object ## Both left and right must have identical ## settings for number and size of vertical panels, ## left-axis labels, number of lines in main, sub, legend. ..., pw=c(.3, .30, .01, .30, .09), px=list( LL=c(0, pwc[1]), LP=pwc[1:2], ML=pwc[2:3], RP=pwc[3:4], RL=pwc[4:5]), pwc=cumsum(pw), strip.left=TRUE, y.tck=c(0,0) ) ## S3 method for class 'TwoTrellisColumns5' print(x, px=attr(x, "px"), ...) leftLabels.trellis(x) rightLabels.trellis(x) panelOnly.trellis(x, strip.left=FALSE, y.tck=0) mainSubLegend.trellis(x) emptyRightAxis(x)
left , right
|
Conformable |
x |
|
px |
These are used |
pw , pwc
|
|
strip.left |
See |
y.tck |
A vector of one or two numeric values.
This will be used as the |
... |
Other arguments are ignored. |
as.TwoTrellisColumns5
constructs a "TwoTrellisColumns5"
object, which is a list of five trellis objects named "LL", "LP",
"ML", "RP", "RL"
. LL
is the left labels from the left
input object. LP
is the panels from the left
input object.
ML
is the middle labels from the left
object; these are
the main
title, sub
title, and legend
. RP
is the panels from the right
input object. RL
is the
right labels from the right
input object.
print.TwoTrellisColumns5
is a print method for a
"TwoTrellisColumns5"
object. It takes left-to-right positioning
information from the "px"
attribute of its argument x
or
from an input argument. The numbers are used as the "x"
information for the position
argument to the print.trellis
method.
emptyLeftAxis,
leftLabels.trellis,
rightLabels.trellis,
panelOnly.trellis,
mainSubLegend.trellis,
emptyLeftStrip,
emptyRightAxis
are functions which blank out the various components of the trellis
argument and retains their vertical spacing.
A "TwoTrellisColumns5"
object, consisting of a list
containing the constructed left, middle, and right trellis objects,
and an attribute containing the px
value.
Richard M. Heiberger <[email protected]>
likert
for the details on the motivating example.
## These are based on the Professional Challenges example in ?likert data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## initial ordering of Question factor PCC <- likert(Question ~ . | Subtable, ProfChal, ylab=NULL, rightAxis=TRUE, layout=c(1,6), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.7), scales=list(y=list(relation="free")), main="Is your job professionally challenging?") ## initial ordering of Question factor PCP <- likert(Question ~ . | Subtable, ProfChal, ylab=NULL, as.percent=TRUE, layout=c(1,6), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.7), scales=list(y=list(relation="free")), main="Is your job professionally challenging?") ## Not run: ## default equal widths of the two panels as.TwoTrellisColumns5(PCP, PCC) ## 11in x 7in ## make left panel twice as wide as right panel as.TwoTrellisColumns5(PCP, PCC, pw=c(.3, .4, .01, .2, .09)) ## 11in x 7in ## -------------------- ## sum to 1.00 ## make left panel twice as wide as right panel, and control position of main and legend as.TwoTrellisColumns5(PCP, PCC, ## 11in x 7in px=list( LL=c(.00, .30), LP=c(.30, .70), ML=c(.60, .61), ## arbitrary, ## visually center the labels and legend RP=c(.71, .91), RL=c(.91, 1.00))) ## End(Not run) ## Size that works in default 7x7 window. 7x7 is not recommended for ## this example because most of the space is used for labeling and not ## much for the panels containing the data. Use the px values for the ## 11x7 illustrated above in the dontrun section. as.TwoTrellisColumns5(PCP, PCC, ## 7in x 7in px=list( LL=c(.00, .50), LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, ## visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00))) ## Ordering the rows by the lengths of the positive bars and also ## put percents and counts on the same plot. ## The easiest way is to use the LikertPercentCountColumns function: LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Not run: ## Ordering the rows by the lengths of the positive bars and also ## putting percents and counts on the same plot requires coordination. ## The easiest way is to order the original tables of counts by the ## order of the percent plot. percentPlot <- likert(Question ~ . | Subtable, ProfChal, as.percent=TRUE, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## percentPlot pct.order <- percentPlot$y.limits[[1]] ProfChal2 <- ProfChal ProfChal2$Question <- factor(ProfChal2$Question, levels=rev(pct.order)) countPlot <- likert(Question ~ . | Subtable, ProfChal2, layout=c(1,6), rightAxis=TRUE, scales=list(y=list(relation="free"), x=list(at=c(0, 250, 500))), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), main="Is your job professionally challenging?") ## countPlot levels(ProfChal$Subtable)[6] <- "Attitude\ntoward\nProfessional\nRecognition" ## Restore original label ## Size that works in default 7x7 window. 7x7 is not recommended for ## this example because most of the space is used for labeling and not ## much for the panels containing the data. Use the px values for the ## 11x7 illustrated above in the dontrun section. as.TwoTrellisColumns5(percentPlot, countPlot, ## 7in x 7in px=list( LL=c(.00, .50), LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, ## visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00))) ## End(Not run)
## These are based on the Professional Challenges example in ?likert data(ProfChal) levels(ProfChal$Subtable)[6] <- "Prof Recog" ## reduce length of label ## initial ordering of Question factor PCC <- likert(Question ~ . | Subtable, ProfChal, ylab=NULL, rightAxis=TRUE, layout=c(1,6), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.7), scales=list(y=list(relation="free")), main="Is your job professionally challenging?") ## initial ordering of Question factor PCP <- likert(Question ~ . | Subtable, ProfChal, ylab=NULL, as.percent=TRUE, layout=c(1,6), strip=FALSE, strip.left=strip.custom(bg="gray97"), par.strip.text=list(cex=.7), scales=list(y=list(relation="free")), main="Is your job professionally challenging?") ## Not run: ## default equal widths of the two panels as.TwoTrellisColumns5(PCP, PCC) ## 11in x 7in ## make left panel twice as wide as right panel as.TwoTrellisColumns5(PCP, PCC, pw=c(.3, .4, .01, .2, .09)) ## 11in x 7in ## -------------------- ## sum to 1.00 ## make left panel twice as wide as right panel, and control position of main and legend as.TwoTrellisColumns5(PCP, PCC, ## 11in x 7in px=list( LL=c(.00, .30), LP=c(.30, .70), ML=c(.60, .61), ## arbitrary, ## visually center the labels and legend RP=c(.71, .91), RL=c(.91, 1.00))) ## End(Not run) ## Size that works in default 7x7 window. 7x7 is not recommended for ## this example because most of the space is used for labeling and not ## much for the panels containing the data. Use the px values for the ## 11x7 illustrated above in the dontrun section. as.TwoTrellisColumns5(PCP, PCC, ## 7in x 7in px=list( LL=c(.00, .50), LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, ## visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00))) ## Ordering the rows by the lengths of the positive bars and also ## put percents and counts on the same plot. ## The easiest way is to use the LikertPercentCountColumns function: LikertPercentCountColumns(Question ~ . | Subtable, ProfChal, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## Not run: ## Ordering the rows by the lengths of the positive bars and also ## putting percents and counts on the same plot requires coordination. ## The easiest way is to order the original tables of counts by the ## order of the percent plot. percentPlot <- likert(Question ~ . | Subtable, ProfChal, as.percent=TRUE, layout=c(1,6), scales=list(y=list(relation="free")), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), positive.order=TRUE, main="Is your job professionally challenging?") ## percentPlot pct.order <- percentPlot$y.limits[[1]] ProfChal2 <- ProfChal ProfChal2$Question <- factor(ProfChal2$Question, levels=rev(pct.order)) countPlot <- likert(Question ~ . | Subtable, ProfChal2, layout=c(1,6), rightAxis=TRUE, scales=list(y=list(relation="free"), x=list(at=c(0, 250, 500))), ylab=NULL, between=list(y=0), strip.left=strip.custom(bg="gray97"), strip=FALSE, par.strip.text=list(cex=.7), main="Is your job professionally challenging?") ## countPlot levels(ProfChal$Subtable)[6] <- "Attitude\ntoward\nProfessional\nRecognition" ## Restore original label ## Size that works in default 7x7 window. 7x7 is not recommended for ## this example because most of the space is used for labeling and not ## much for the panels containing the data. Use the px values for the ## 11x7 illustrated above in the dontrun section. as.TwoTrellisColumns5(percentPlot, countPlot, ## 7in x 7in px=list( LL=c(.00, .50), LP=c(.50, .70), ML=c(.50, .51), ## arbitrary, ## visually center the labels and legend RP=c(.71, .87), RL=c(.87, 1.00))) ## End(Not run)
push and pop a grid viewport, turn clipping off, change scale.
push.vp.hh(scale = 100) pop.vp.hh()
push.vp.hh(scale = 100) pop.vp.hh()
scale |
argument to the |
Used in panel.cartesian
to ease labeling the rows
and columns of a scatterplot matrix.
An object of class "unit"
.
Richard M. Heiberger <[email protected]>
viewport
, unit
,
panel.cartesian
Prints a likert plot in the traditional format for a population pyramid, with the Left and Right sides in separate panels, with the x-tick marks on the left side made positive, and with the y-axis in the Middle.
## S3 method for class 'pyramidLikert' print(x, ..., panel.width=.48, px=list( L=c(0, panel.width), R=c(1-panel.width, 1), M=c(panel.width, 1-panel.width)), keepLegend=(length(x$legend$bottom$args$text) > 2), xlab.top=list( L=list(x$legend$bottom$args$text[1]), R=list(x$legend$bottom$args$text[2]), M=list(x$ylab, just=1))) as.pyramidLikert(x, ..., panel.width=.48, px=list( L=c(0, panel.width), R=c(1-panel.width, 1), M=c(panel.width, 1-panel.width)), keepLegend=(length(x$legend$bottom$args$text) > 2), xlab.top=list( L=list(x$legend$bottom$args$text[1]), R=list(x$legend$bottom$args$text[2]), M=list(x$ylab, just=1)))
## S3 method for class 'pyramidLikert' print(x, ..., panel.width=.48, px=list( L=c(0, panel.width), R=c(1-panel.width, 1), M=c(panel.width, 1-panel.width)), keepLegend=(length(x$legend$bottom$args$text) > 2), xlab.top=list( L=list(x$legend$bottom$args$text[1]), R=list(x$legend$bottom$args$text[2]), M=list(x$ylab, just=1))) as.pyramidLikert(x, ..., panel.width=.48, px=list( L=c(0, panel.width), R=c(1-panel.width, 1), M=c(panel.width, 1-panel.width)), keepLegend=(length(x$legend$bottom$args$text) > 2), xlab.top=list( L=list(x$legend$bottom$args$text[1]), R=list(x$legend$bottom$args$text[2]), M=list(x$ylab, just=1)))
x |
a single-panel |
... |
Other arguments are ignored. |
panel.width |
Numeric scalar between 0 and 0.5. Common width of left and right panels. The default
value .48 value works well for the |
px |
|
keepLegend |
If |
xlab.top |
A vector of three labels. The default is designed for a population triangle with two levels (usually, Male on one side and Female on the other). The Left and Right labels are taken from the first two labels in the legend. The Middle value is the variable name for the y-axis. |
This is a print method for population triangles. It is designed for a
likert plot with one left-side level and one right-side level.
It works for any single-panel "trellis"
object, in the sense
that it produces a plot.
The input argument x
.
Richard M. Heiberger <[email protected]>
data(USAge.table) ## from latticeExtra USA79 <- USAge.table[75:1, 2:1, "1979"]/1000000 PL <- plot(as.likert(USA79), main="Population of United States 1979 (ages 0-74)", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)) ) PL as.pyramidLikert(PL) likert(USAge.table[75:1, 2:1, c("1939","1959","1979")]/1000000, main="Population of United States 1939,1959,1979 (ages 0-74)", sub="Look for the Baby Boom", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)), strip.left=FALSE, strip=TRUE, layout=c(3,1), between=list(x=.5)) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/PopulationPyramid", package="HH")) ## End(Not run) ## For additional examples, see demo(PoorChildren, package="HH")
data(USAge.table) ## from latticeExtra USA79 <- USAge.table[75:1, 2:1, "1979"]/1000000 PL <- plot(as.likert(USA79), main="Population of United States 1979 (ages 0-74)", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)) ) PL as.pyramidLikert(PL) likert(USAge.table[75:1, 2:1, c("1939","1959","1979")]/1000000, main="Population of United States 1939,1959,1979 (ages 0-74)", sub="Look for the Baby Boom", xlab="Count in Millions", ylab="Age", scales=list( y=list( limits=c(0,77), at=seq(1,76,5), labels=seq(0,75,5), tck=.5)), strip.left=FALSE, strip=TRUE, layout=c(3,1), between=list(x=.5)) ## Not run: ## run the shiny app if (interactive()) shiny::runApp(system.file("shiny/PopulationPyramid", package="HH")) ## End(Not run) ## For additional examples, see demo(PoorChildren, package="HH")
Extend matrix reshaping functions to trellis objects. See the details section for comparisons with similar functions in the lattice package.
transpose(x) ## S3 method for class 'trellis' transpose(x) ## Default S3 method: transpose(x) ## S3 method for class 'trellis' aperm(a, perm, ...) ## S3 method for class 'trellis' rbind(..., deparse.level=1, combineLimits=TRUE, useOuterStrips=TRUE) ## S3 method for class 'trellis' cbind(..., deparse.level=1, combineLimits=TRUE, useOuterStrips=TRUE)
transpose(x) ## S3 method for class 'trellis' transpose(x) ## Default S3 method: transpose(x) ## S3 method for class 'trellis' aperm(a, perm, ...) ## S3 method for class 'trellis' rbind(..., deparse.level=1, combineLimits=TRUE, useOuterStrips=TRUE) ## S3 method for class 'trellis' cbind(..., deparse.level=1, combineLimits=TRUE, useOuterStrips=TRUE)
... , x , a
|
A set of |
perm |
Permutation vector, see |
combineLimits , useOuterStrips
|
logical. If |
deparse.level |
See |
transpose.trellis
tries to capture and modify all potentially relevant
trellis components. transpose.trellis
is more comprehensive
than the similar
t.trellis
which adjusts only the
perm.cond
component.
aperm.trellis
does not attempt to check all potentially relevant
trellis components.
It does not adjust layout.heights
, layout.widths
, or
between
It may show strange axis
positions or strip positions for any non-standard arrangement, for example,
for any trellis object that has already been
through latticeExtra::combineLimits
.
trellis object constructed from arguments with new dim and layout.
Richard M. Heiberger <[email protected]>
F <- xyplot((1:15) ~ (1:15) | rep(factor(letters[3:5]), each=5)) G <- xyplot((1:18) ~ (1:18) | rep(factor(letters[3:5]), each=6)) rbind(AAA=F, BBB=G) cbind(AAA=F, BBB=G) tmp <- data.frame(y=1:24, x=1:24, a=rep(letters[1:2], each=12), b=rep(letters[3:5], each=4, times=2), c=rep(letters[6:9], times=6)) t3 <- xyplot(y ~ x | c*b*a, data=tmp, panel=function(x, y, ...) panel.text(x, y, y), scales=list(alternating=FALSE)) ## t3 t3u <- update(t3, layout=c(4*3, 2), between=list(x=c(0,0,0,1)), main="t3") useOuterStripsT2L1(t3u) ## Not run: ## update(t3, layout=c(24, 1)) t3.321 <- aperm(t3, c(3,2,1)) update(t3.321, main="t3.321", layout=c(6,4), between=list(x=c(0,1))) ## 2*3,4 try(transpose(t3)) ## requires a one- or two-dimensional trellis object. t3.123 <- aperm(t3, c(1,2,3)) ## identity operation t3.132 <- aperm(t3, c(1,3,2)) t3.213 <- aperm(t3, c(2,1,3)) t3.231 <- aperm(t3, c(2,3,1)) t3.312 <- aperm(t3, c(3,1,2)) t3.321 <- aperm(t3, c(3,2,1)) u3.123 <- update(t3.123, main="t3.123", layout=c(12,2), between=list(x=c(0,0,0,1))) ## 4*3,2 u3.132 <- update(t3.132, main="t3.132", layout=c(8,3), between=list(x=c(0,0,0,1))) ## 4*2,3 u3.213 <- update(t3.213, main="t3.213", layout=c(3,8), between=list(y=c(0,0,0,1)), par.strip.text=list(cex=.8)) ## 3,4*2 u3.231 <- update(t3.231, main="t3.231", layout=c(6,4), between=list(x=c(0,0,1))) ## 2*3,4 u3.312 <- update(t3.312, main="t3.312", layout=c(2,12), between=list(y=c(0,0,0,1)), par.strip.text=list(cex=.6)) ## 2,3*4 u3.321 <- update(t3.321, main="t3.321", layout=c(6,4), between=list(x=c(0,1))) ## 2*3,4 u5 <- tempfile("u5", fileext = ".pdf") pdf(u5, width=17, height=22) print(u3.123, split=c(1,1,2,3), more=TRUE) print(u3.132, split=c(2,1,2,3), more=TRUE) print(u3.213, split=c(1,2,2,3), more=TRUE) print(u3.231, split=c(2,2,2,3), more=TRUE) print(u3.312, split=c(1,3,2,3), more=TRUE) print(u3.321, split=c(2,3,2,3), more=FALSE) dev.off() try(transpose(t3.123)) ## layout is a matrix, but dim is not. ## End(Not run) ## Not run: t2 <- xyplot(y ~ x | b*c, data=tmp, panel=function(x, y, ...) panel.text(x, y, y), scales=list(alternating=FALSE)) t2 ## aperm(t2, 1:2) ## identity transpose(t2) aperm(t2, 2:1) t1a <- xyplot(y ~ x | b, data=tmp[tmp$a=="a",]) t1b <- xyplot(y ~ x | b, data=tmp[tmp$a=="b",]) t1a t1b rbind(t1a, t1b) rbind(AAA=t1a, BBB=t1b) cbind(t1a, t1b) cbind(AAA=t1a, BBB=t1b) ## End(Not run)
F <- xyplot((1:15) ~ (1:15) | rep(factor(letters[3:5]), each=5)) G <- xyplot((1:18) ~ (1:18) | rep(factor(letters[3:5]), each=6)) rbind(AAA=F, BBB=G) cbind(AAA=F, BBB=G) tmp <- data.frame(y=1:24, x=1:24, a=rep(letters[1:2], each=12), b=rep(letters[3:5], each=4, times=2), c=rep(letters[6:9], times=6)) t3 <- xyplot(y ~ x | c*b*a, data=tmp, panel=function(x, y, ...) panel.text(x, y, y), scales=list(alternating=FALSE)) ## t3 t3u <- update(t3, layout=c(4*3, 2), between=list(x=c(0,0,0,1)), main="t3") useOuterStripsT2L1(t3u) ## Not run: ## update(t3, layout=c(24, 1)) t3.321 <- aperm(t3, c(3,2,1)) update(t3.321, main="t3.321", layout=c(6,4), between=list(x=c(0,1))) ## 2*3,4 try(transpose(t3)) ## requires a one- or two-dimensional trellis object. t3.123 <- aperm(t3, c(1,2,3)) ## identity operation t3.132 <- aperm(t3, c(1,3,2)) t3.213 <- aperm(t3, c(2,1,3)) t3.231 <- aperm(t3, c(2,3,1)) t3.312 <- aperm(t3, c(3,1,2)) t3.321 <- aperm(t3, c(3,2,1)) u3.123 <- update(t3.123, main="t3.123", layout=c(12,2), between=list(x=c(0,0,0,1))) ## 4*3,2 u3.132 <- update(t3.132, main="t3.132", layout=c(8,3), between=list(x=c(0,0,0,1))) ## 4*2,3 u3.213 <- update(t3.213, main="t3.213", layout=c(3,8), between=list(y=c(0,0,0,1)), par.strip.text=list(cex=.8)) ## 3,4*2 u3.231 <- update(t3.231, main="t3.231", layout=c(6,4), between=list(x=c(0,0,1))) ## 2*3,4 u3.312 <- update(t3.312, main="t3.312", layout=c(2,12), between=list(y=c(0,0,0,1)), par.strip.text=list(cex=.6)) ## 2,3*4 u3.321 <- update(t3.321, main="t3.321", layout=c(6,4), between=list(x=c(0,1))) ## 2*3,4 u5 <- tempfile("u5", fileext = ".pdf") pdf(u5, width=17, height=22) print(u3.123, split=c(1,1,2,3), more=TRUE) print(u3.132, split=c(2,1,2,3), more=TRUE) print(u3.213, split=c(1,2,2,3), more=TRUE) print(u3.231, split=c(2,2,2,3), more=TRUE) print(u3.312, split=c(1,3,2,3), more=TRUE) print(u3.321, split=c(2,3,2,3), more=FALSE) dev.off() try(transpose(t3.123)) ## layout is a matrix, but dim is not. ## End(Not run) ## Not run: t2 <- xyplot(y ~ x | b*c, data=tmp, panel=function(x, y, ...) panel.text(x, y, y), scales=list(alternating=FALSE)) t2 ## aperm(t2, 1:2) ## identity transpose(t2) aperm(t2, 2:1) t1a <- xyplot(y ~ x | b, data=tmp[tmp$a=="a",]) t1b <- xyplot(y ~ x | b, data=tmp[tmp$a=="b",]) t1a t1b rbind(t1a, t1b) rbind(AAA=t1a, BBB=t1b) cbind(t1a, t1b) cbind(AAA=t1a, BBB=t1b) ## End(Not run)
Plot x
and y
,
with optional fitted line and display of squared residuals.
By default the least squares line is calculated and used.
Any other straight line
can be specified by placing its coefficients in coef.model
.
Any other fitted model can be calculated by specifying the model
argument.
Any other function of one variable can be specified in the
alt.function
argument. At most one of the arguments
model
, coef.model
, alt.function
can be specified.
regr1.plot(x, y, model=lm(y~x), coef.model, alt.function, main="put a useful title here", xlab=deparse(substitute(x)), ylab=deparse(substitute(y)), jitter.x=FALSE, resid.plot=FALSE, points.yhat=TRUE, pch=16, ..., length.x.set=51, x.name, pch.yhat=16, cex.yhat=par()$cex*.7, err=-1)
regr1.plot(x, y, model=lm(y~x), coef.model, alt.function, main="put a useful title here", xlab=deparse(substitute(x)), ylab=deparse(substitute(y)), jitter.x=FALSE, resid.plot=FALSE, points.yhat=TRUE, pch=16, ..., length.x.set=51, x.name, pch.yhat=16, cex.yhat=par()$cex*.7, err=-1)
x |
x variable |
y |
y variable |
model |
Defaults to the simple linear model |
coef.model |
Defaults to the coefficients of the |
alt.function |
Any function of a single argument can be placed
here. |
main , xlab , ylab
|
arguments to |
jitter.x |
logical. If |
resid.plot |
If |
points.yhat |
logical. If |
... |
other arguments. |
length.x.set |
number of points used to plot the predicted values. |
x.name |
If the |
pch |
Plotting character for the observed points. |
pch.yhat |
Plotting character for the fitted points. |
cex.yhat |
|
err |
The default |
This plot is designed as a pedagogical example for introductory courses.
When resid.plot=="square"
, then we actually see the set of squares
for which the sum of their areas is minimized by the method of "least squares".
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Smith, W. and Gonick, L. (1993). The Cartoon Guide to Statistics. HarperCollins.
data(hardness) ## linear and quadratic regressions hardness.lin.lm <- lm(hardness ~ density, data=hardness) hardness.quad.lm <- lm(hardness ~ density + I(density^2), data=hardness) anova(hardness.quad.lm) ## quadratic term has very low p-value par(mfrow=c(1,2)) regr1.plot(hardness$density, hardness$hardness, resid.plot="square", main="squared residuals for linear fit", xlab="density", ylab="hardness", points.yhat=FALSE, xlim=c(20,95), ylim=c(0,3400)) regr1.plot(hardness$density, hardness$hardness, model=hardness.quad.lm, resid.plot="square", main="squared residuals for quadratic fit", xlab="density", ylab="hardness", points.yhat=FALSE, xlim=c(20,95), ylim=c(0,3400)) par(mfrow=c(1,1))
data(hardness) ## linear and quadratic regressions hardness.lin.lm <- lm(hardness ~ density, data=hardness) hardness.quad.lm <- lm(hardness ~ density + I(density^2), data=hardness) anova(hardness.quad.lm) ## quadratic term has very low p-value par(mfrow=c(1,2)) regr1.plot(hardness$density, hardness$hardness, resid.plot="square", main="squared residuals for linear fit", xlab="density", ylab="hardness", points.yhat=FALSE, xlim=c(20,95), ylim=c(0,3400)) regr1.plot(hardness$density, hardness$hardness, model=hardness.quad.lm, resid.plot="square", main="squared residuals for quadratic fit", xlab="density", ylab="hardness", points.yhat=FALSE, xlim=c(20,95), ylim=c(0,3400)) par(mfrow=c(1,1))
3D plot of z against x and y, with regression plane fit and display of squared residuals.
regr2.plot(x, y, z, main.in="put a useful title here", resid.plot=FALSE, plot.base.plane=TRUE, plot.back.planes=TRUE, plot.base.points=FALSE, eye=NULL, ## S-Plus theta=0, phi=15, r=sqrt(3), ticktype="detailed", ## R ...)
regr2.plot(x, y, z, main.in="put a useful title here", resid.plot=FALSE, plot.base.plane=TRUE, plot.back.planes=TRUE, plot.base.points=FALSE, eye=NULL, ## S-Plus theta=0, phi=15, r=sqrt(3), ticktype="detailed", ## R ...)
x , y , z
|
See
|
main.in |
|
resid.plot |
Argument to |
plot.base.plane , plot.back.planes , plot.base.points
|
Should these items be plotted? |
eye |
S-Plus only. See
|
theta , phi , r , ticktype
|
R only. See
|
... |
Other arguments to |
"Viewing Transformation" for projecting 3D coordinates (x,y,z)
into the 2D plane. See persp
for details.
This plot is designed as a pedagogical example for introductory
courses. When resid.plot=="square"
, then we actually see the
set of squares for which the sum of their areas is minimized by the
method of "least squares". The demo called in the examples section
shows the geometry of regression coefficients, the change in predicted
y when x1 is changed one unit holding all other x variables constant.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
Smith, W. and Gonick, L. (1993). The Cartoon Guide to Statistics. HarperCollins.
resid.squares
, regr1.plot
, persp
data(fat) regr2.plot(fat[,"abdomin"], xlab="abdomin", fat[,"biceps"], ylab="biceps", fat[,"bodyfat"], zlab="bodyfat", resid.plot="square", eye=c(335.5, 115.65, 171.9), ## used only in S-Plus theta=140, phi=35, r=sqrt(15), ## used only in R box=is.R(), plot.back.planes=FALSE, main="Least-squares with two X-variables") ## Not run: demo("regr2", package="HH", ask=FALSE) ## run the file manually to see the individual steps. ## End(Not run)
data(fat) regr2.plot(fat[,"abdomin"], xlab="abdomin", fat[,"biceps"], ylab="biceps", fat[,"bodyfat"], zlab="bodyfat", resid.plot="square", eye=c(335.5, 115.65, 171.9), ## used only in S-Plus theta=140, phi=35, r=sqrt(15), ## used only in R box=is.R(), plot.back.planes=FALSE, main="Least-squares with two X-variables") ## Not run: demo("regr2", package="HH", ask=FALSE) ## run the file manually to see the individual steps. ## End(Not run)
Draw a plot of response vector y vs predictor variable x from a linear model object all of whose predictors are a function of x, with residuals indicated by lines or squares.
regrresidplot(x, y, resid.plot = FALSE, fit.line=TRUE, lm.object = lm(y ~ x), x.name = names(lm.object$model)[2], col = trellis.par.get()$plot.symbol$col, col.yhat = NULL, col.fit = "gray80", col.resid = "gray40", ...) panel.residSquare(x, y, yhat, resid.plot = FALSE, col = "black", ...)
regrresidplot(x, y, resid.plot = FALSE, fit.line=TRUE, lm.object = lm(y ~ x), x.name = names(lm.object$model)[2], col = trellis.par.get()$plot.symbol$col, col.yhat = NULL, col.fit = "gray80", col.resid = "gray40", ...) panel.residSquare(x, y, yhat, resid.plot = FALSE, col = "black", ...)
x |
Predictor variable. Must be a vector or a single column. |
y |
Response variable. Must be a vector or a single column. |
yhat |
Predicted value of y based on the model in |
resid.plot |
Logical or character. Should the residuals from |
fit.line |
Logical. Should the fitted regression line from |
lm.object |
Linear model object of y against some function of x. The default value
is the simple linear regression of |
x.name |
Name of $x$-variable to be used in the construction of the fitted values. |
col |
Color of observed points. |
col.yhat |
Color of fitted points. Default is |
col.fit |
Color of fitted line. |
col.resid |
Color of residuals, either lines or squares depending on the value of
|
... |
Additional arguments to the panel functions. |
regrresidplot
returns a "trellis"
object.
panel.residSquare
is a panel function with no useful returned value.
Richard M. Heiberger <[email protected]>
data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) AA <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50)) BB <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50), resid.plot="line") CC <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50), resid.plot="square") update(between=list(y=1), c("Residuals Not Displayed"=AA, "Residual Lines"=BB, "Residual Squares"=CC, layout=c(1,3)))
data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) AA <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50)) BB <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50), resid.plot="line") CC <- regrresidplot(fat$abdomin, fat$bodyfat, xlim=c(70,185), ylim=c(0,50), resid.plot="square") update(between=list(y=1), c("Residuals Not Displayed"=AA, "Residual Lines"=BB, "Residual Squares"=CC, layout=c(1,3)))
plot squared residuals in inches to match the y-dimension
resid.squares(x, y, y.hat, resid.plot = "square", ...)
resid.squares(x, y, y.hat, resid.plot = "square", ...)
x |
x values |
y |
observed y values |
y.hat |
predicted y values |
resid.plot |
If |
... |
Other graphics arguments. |
The goal is to get real squares on the screen or paper. The trick is to play games with the aspect ratio. We find the number of inches that each vertical residual occupies. We then find the number of x-units that corresponds to, and plot a rectangle with height=height in the y-data units and with width=the number of x-units that we just calculated.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(hardness) hardness.lin.lm <- lm(hardness ~ density, data=hardness) plot(hardness ~ density, data=hardness, xlim=c(22,73), ylim=c(0,3400)) abline(hardness.lin.lm) resid.squares(hardness$density, hardness$hardness, predict(hardness.lin.lm)) plot(hardness ~ density, data=hardness, xlim=c(22,73), ylim=c(0,3400)) abline(hardness.lin.lm) resid.squares(hardness$density, hardness$hardness, predict(hardness.lin.lm), resid.plot = "line")
data(hardness) hardness.lin.lm <- lm(hardness ~ density, data=hardness) plot(hardness ~ density, data=hardness, xlim=c(22,73), ylim=c(0,3400)) abline(hardness.lin.lm) resid.squares(hardness$density, hardness$hardness, predict(hardness.lin.lm)) plot(hardness ~ density, data=hardness, xlim=c(22,73), ylim=c(0,3400)) abline(hardness.lin.lm) resid.squares(hardness$density, hardness$hardness, predict(hardness.lin.lm), resid.plot = "line")
Residual plots for a linear model. Four sets of plots are produced: (1) response against each of the predictor variables, (2) residuals against each of the predictor variables, (3) partial residuals for each predictor against that predictor ("partial residuals plots", and (4) partial residuals against the residuals of each predictor regressed on the other predictors ("added variable plots").
residual.plots(lm.object, X=dft$x, layout=c(dim(X)[2],1), par.strip.text=list(cex=.8), scales.cex=.6, na.action=na.pass, y.relation="free", ...)
residual.plots(lm.object, X=dft$x, layout=c(dim(X)[2],1), par.strip.text=list(cex=.8), scales.cex=.6, na.action=na.pass, y.relation="free", ...)
lm.object |
An object inheriting from |
X |
The x matrix of predictor variables used in the linear model
|
layout , par.strip.text
|
trellis or lattice arguments. |
scales.cex |
|
na.action |
A function to filter missing data. See |
y.relation |
See |
... |
Other arguments for |
A list of four trellis objects, one for each of the four sets of
plots. The objects are named "y.X"
, "res.X"
"pres.X"
, "pres.Xj"
. The default "printing" of the
result will produce four pages of plots, one set per page. They are
often easier to read when all four sets appear as separate rows on one
page (this usually requires an oversize device), or two rows are
printed on each of two pages.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
if.R(s={ longley <- data.frame(longley.x, Employed = longley.y) },r={ data(longley) }) longley.lm <- lm( Employed ~ . , data=longley, x=TRUE, y=TRUE) ## 'x=TRUE, y=TRUE' are needed to pass the S-Plus CMD check. ## They may be needed if residual.plots() is inside a nested set of ## function calls. tmp <- residual.plots(longley.lm) ## print two rows per page print(tmp[[1]], position=c(0, 0.5, 1, 1.0), more=TRUE) print(tmp[[2]], position=c(0, 0.0, 1, 0.5), more=FALSE) print(tmp[[3]], position=c(0, 0.5, 1, 1.0), more=TRUE) print(tmp[[4]], position=c(0, 0.0, 1, 0.5), more=FALSE) ## print as a single trellis object ABCD <- do.call(rbind, lapply(tmp, as.vector)) dimnames(ABCD)[[1]] <- dimnames(tmp[[1]])[[1]] ABCD
if.R(s={ longley <- data.frame(longley.x, Employed = longley.y) },r={ data(longley) }) longley.lm <- lm( Employed ~ . , data=longley, x=TRUE, y=TRUE) ## 'x=TRUE, y=TRUE' are needed to pass the S-Plus CMD check. ## They may be needed if residual.plots() is inside a nested set of ## function calls. tmp <- residual.plots(longley.lm) ## print two rows per page print(tmp[[1]], position=c(0, 0.5, 1, 1.0), more=TRUE) print(tmp[[2]], position=c(0, 0.0, 1, 0.5), more=FALSE) print(tmp[[3]], position=c(0, 0.5, 1, 1.0), more=TRUE) print(tmp[[4]], position=c(0, 0.0, 1, 0.5), more=FALSE) ## print as a single trellis object ABCD <- do.call(rbind, lapply(tmp, as.vector)) dimnames(ABCD)[[1]] <- dimnames(tmp[[1]])[[1]] ABCD
Construct four sets of regression plots. Response variable $Y$ against each $X_j$, residuals $e$ against each $X_j$, partial residuals plots of $e^j$ against each $X_j$, added variable plots of $e^j$ against the residuals of each $X_j$ adjusted for the other $X$ columns. The slopes shown in the panels of both bottom rows are equal to the regression coefficients.
residual.plots.lattice(lm.object, X=dft$x, layout=c(dim(X)[2],1), par.strip.text=list(cex=.8), scales.cex=.6, na.action=na.pass, y.relation="same", ...)
residual.plots.lattice(lm.object, X=dft$x, layout=c(dim(X)[2],1), par.strip.text=list(cex=.8), scales.cex=.6, na.action=na.pass, y.relation="same", ...)
lm.object |
|
X |
Identify the variables in each of the x, y, group positions in a formula object.
See |
layout , par.strip.text , ...
|
lattice arguments. See |
scales.cex |
|
na.action |
See |
y.relation |
|
"trellis"
object.
Richard M. Heiberger <[email protected]>
residual.plots
, print.latticeresids
data(longley) longley.lm <- lm( Employed ~ . , data=longley, x=TRUE, y=TRUE) residual.plots.lattice(longley.lm) ## Not run: longleyResid <- tempfile("longleyResid", fileext = ".pdf") pdf(longleyResid, height=9, width=14) print(residual.plots.lattice(longley.lm, pch=19), A4.left=.0125, panel.width=list(5,"cm")) dev.off() ## End(Not run)
data(longley) longley.lm <- lm( Employed ~ . , data=longley, x=TRUE, y=TRUE) residual.plots.lattice(longley.lm) ## Not run: longleyResid <- tempfile("longleyResid", fileext = ".pdf") pdf(longleyResid, height=9, width=14) print(residual.plots.lattice(longley.lm, pch=19), A4.left=.0125, panel.width=list(5,"cm")) dev.off() ## End(Not run)
Draw plots of resid ~ y.hat
and sqrt(abs(resid)) ~ y.hat
.
This is a pair of lattice functions that duplicate the first and third
panels of stats:::plot.lm
.
residVSfitted(linearmodel, groups = (e >= 0), ...) scaleLocation(linearmodel, groups = (e >= 0), ...)
residVSfitted(linearmodel, groups = (e >= 0), ...) scaleLocation(linearmodel, groups = (e >= 0), ...)
linearmodel |
|
groups |
This is the standard |
... |
Additional arguments to |
"trellis"
object.
Richard M. Heiberger <[email protected]>
data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) A <- residVSfitted(fat.lm, pch=c(25,24), fill=trellis.par.get("superpose.symbol")$col[1:2]) B <- scaleLocation(fat.lm, pch=c(25,24), fill=trellis.par.get("superpose.symbol")$col[1:2]) BA <- c("Scale-Location"=B, "Residuals vs Fitted"=update(A, scales=list(y=list(at=-100, alternating=3))), layout=c(1,2)) BA BAu <- update(BA, ylab=c(B$ylab, A$ylab), ylab.right=c(B$ylab.right, A$ylab.right), xlab.top=NULL, between=list(y=1), par.settings=list(layout.widths=list(ylab.right=6)) ) C <- diagQQ(fat.lm) D <- diagplot5new(fat.lm) print(BAu, split=c(1,1,2,1), more=TRUE) print(update(c("Normal Q-Q"=C), xlab.top=NULL, strip=TRUE), ## split=c(2,1,2,2), position=c(.5, .54, 1, 1), ## .54 is function of device and size more=TRUE) print(update(D, xlab.top=NULL, strip=strip.custom(factor.levels=D$xlab.top), par.strip.text=list(lines=1.3)), ## split=c(2,2,2,2), position=c(.5, 0, 1, .57), ## .57 is function of device and size more=FALSE) ## the .54 and .57 work nicely with the default quartz window on Mac OS X.
data(fat) fat.lm <- lm(bodyfat ~ abdomin, data=fat) A <- residVSfitted(fat.lm, pch=c(25,24), fill=trellis.par.get("superpose.symbol")$col[1:2]) B <- scaleLocation(fat.lm, pch=c(25,24), fill=trellis.par.get("superpose.symbol")$col[1:2]) BA <- c("Scale-Location"=B, "Residuals vs Fitted"=update(A, scales=list(y=list(at=-100, alternating=3))), layout=c(1,2)) BA BAu <- update(BA, ylab=c(B$ylab, A$ylab), ylab.right=c(B$ylab.right, A$ylab.right), xlab.top=NULL, between=list(y=1), par.settings=list(layout.widths=list(ylab.right=6)) ) C <- diagQQ(fat.lm) D <- diagplot5new(fat.lm) print(BAu, split=c(1,1,2,1), more=TRUE) print(update(c("Normal Q-Q"=C), xlab.top=NULL, strip=TRUE), ## split=c(2,1,2,2), position=c(.5, .54, 1, 1), ## .54 is function of device and size more=TRUE) print(update(D, xlab.top=NULL, strip=strip.custom(factor.levels=D$xlab.top), par.strip.text=list(lines=1.3)), ## split=c(2,2,2,2), position=c(.5, 0, 1, .57), ## .57 is function of device and size more=FALSE) ## the .54 and .57 work nicely with the default quartz window on Mac OS X.
This function is a wrapper for several of the functions in the
latticeExtra
package.
ResizeEtc(c.list, condlevelsName, x.same, y.same, layout, strip=TRUE, strip.left=TRUE, strip.values, strip.left.values, strip.par, strip.left.par, ## only the second is effective ## when both are specified resize.height, resize.width, main, ...)
ResizeEtc(c.list, condlevelsName, x.same, y.same, layout, strip=TRUE, strip.left=TRUE, strip.values, strip.left.values, strip.par, strip.left.par, ## only the second is effective ## when both are specified resize.height, resize.width, main, ...)
c.list |
combination of two or more trellis objects
from |
condlevelsName |
Name of the dimname of the items in the |
x.same , y.same
|
If |
layout |
Standard lattice |
strip , strip.left
|
standard lattice arguments described in |
strip.values , strip.left.values
|
strip names for the panels. Only the second is effective when both are specified. |
strip.par , strip.left.par
|
|
resize.height , resize.width
|
|
main |
Main title for resulting combined plot. |
... |
Other arguments to |
"trellis"
object combining each of the individual plots in the
c.list
argument according to the specifications in the other arguments.
Richard M. Heiberger <[email protected]>
## see the examples in ?HH:::plot.likert require(grid) require(lattice) require(latticeExtra) require(HH) ## This is the same example as in ?HH:::plot.likert ## Here, it is done with explicit use of ResizeEtc. data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question AA <- likert(tmp[1,], box.width=unit(.4,"cm"), positive.order=TRUE) BB <- likert(tmp[2:6,], box.width=unit(.4,"cm"), positive.order=TRUE) CC <- likert(tmp[7:10,], box.width=unit(.4,"cm"), positive.order=TRUE) DD <- likert(tmp[11:12,], box.width=unit(.4,"cm"), positive.order=TRUE) EE <- likert(tmp[13:14,], box.width=unit(.4,"cm"), positive.order=TRUE) FF <- likert(tmp[15:16,], box.width=unit(.4,"cm"), positive.order=TRUE) BB ## print(AA, more=TRUE, split=c(1,1,3,2)) ## print(BB, more=TRUE, split=c(2,1,3,2)) ## print(CC, more=TRUE, split=c(3,1,3,2)) ## print(DD, more=TRUE, split=c(1,2,3,2)) ## print(EE, more=TRUE, split=c(2,2,3,2)) ## print(FF, more=FALSE, split=c(3,2,3,2)) ResizeEtc(c.list=c(AA,BB,CC,DD,EE,FF), layout=c(1,6), main="Not yet good enough") Group <- levels(ProfChal$Subtable) ResizeEtc(c.list=c(AA,BB,CC,DD,EE,FF), condlevelsName='Group', x.same=TRUE, layout=c(1,6), strip.left.values=Group, strip.left.par=list(cex=.7, lines=5), resize.height=c(1,5,4,2,2,2)+.5, main=list("Is your job professionally challenging?", x=unit(.65, "npc")))
## see the examples in ?HH:::plot.likert require(grid) require(lattice) require(latticeExtra) require(HH) ## This is the same example as in ?HH:::plot.likert ## Here, it is done with explicit use of ResizeEtc. data(ProfChal) tmp <- data.matrix(ProfChal[,1:5]) rownames(tmp) <- ProfChal$Question AA <- likert(tmp[1,], box.width=unit(.4,"cm"), positive.order=TRUE) BB <- likert(tmp[2:6,], box.width=unit(.4,"cm"), positive.order=TRUE) CC <- likert(tmp[7:10,], box.width=unit(.4,"cm"), positive.order=TRUE) DD <- likert(tmp[11:12,], box.width=unit(.4,"cm"), positive.order=TRUE) EE <- likert(tmp[13:14,], box.width=unit(.4,"cm"), positive.order=TRUE) FF <- likert(tmp[15:16,], box.width=unit(.4,"cm"), positive.order=TRUE) BB ## print(AA, more=TRUE, split=c(1,1,3,2)) ## print(BB, more=TRUE, split=c(2,1,3,2)) ## print(CC, more=TRUE, split=c(3,1,3,2)) ## print(DD, more=TRUE, split=c(1,2,3,2)) ## print(EE, more=TRUE, split=c(2,2,3,2)) ## print(FF, more=FALSE, split=c(3,2,3,2)) ResizeEtc(c.list=c(AA,BB,CC,DD,EE,FF), layout=c(1,6), main="Not yet good enough") Group <- levels(ProfChal$Subtable) ResizeEtc(c.list=c(AA,BB,CC,DD,EE,FF), condlevelsName='Group', x.same=TRUE, layout=c(1,6), strip.left.values=Group, strip.left.par=list(cex=.7, lines=5), resize.height=c(1,5,4,2,2,2)+.5, main=list("Is your job professionally challenging?", x=unit(.65, "npc")))
This is a method for ResizeEtc
intended for use with
"likert"
plots that allows positive values on the
negative side of the axis.
## S3 method for class 'likertPlot' ResizeEtc(c.list, x, x.pl.nonames, horizontal, ...)
## S3 method for class 'likertPlot' ResizeEtc(c.list, x, x.pl.nonames, horizontal, ...)
c.list |
combination of two or more trellis objects
from |
x |
List of two-dimensional objects with the same columns. See
|
x.pl.nonames |
List of |
horizontal |
Standard argument for |
... |
Other arguments to |
The result is a "trellis"
object. It is essentially the same
object
returned by ResizeEtc
with possibly adjusted x tick-labels to put
positive labels on the negative axis. If horizontal==FALSE
,
then the possible adjusted labels are the y tick-labels.
Richard M. Heiberger <[email protected]>
Row and columns percents.
rowPcts(x, ...) colPcts(x, ...)
rowPcts(x, ...) colPcts(x, ...)
x |
numerical matrix |
... |
Additional arguments for |
Calculate percents by row or column. The rowSums
or
colSums
are stored in the Sums
attribute of the result.
Richard M. Heiberger <[email protected]>
tmp <- matrix(1:12, 3, 4, dimnames=list(c("A","B","C"), c(letters[4:7]))) tmp rowPcts(tmp) colPcts(tmp)
tmp <- matrix(1:12, 3, 4, dimnames=list(c("A","B","C"), c(letters[4:7]))) tmp rowPcts(tmp) colPcts(tmp)
Time series plot.
seqplot(xts, ...) ## Default S3 method: seqplot(xts, pch.seq=letters, groups=as.numeric(cycle(xts)), a=NULL, b=NULL, h=NULL, v=NULL, ylab=deparse(substitute(xts)), xlab="Time", lwd=1, lty=c(1,3), type="b", col=trellis.par.get("superpose.symbol")$col, col.line="gray60", ...) ## S3 method for class 'ts' seqplot(xts, pch.seq=letters, groups=as.numeric(cycle(xts)), x.at=pretty(time(xts)[groups==min(groups)]), x.labels, ylab=deparse(substitute(xts)), ...)
seqplot(xts, ...) ## Default S3 method: seqplot(xts, pch.seq=letters, groups=as.numeric(cycle(xts)), a=NULL, b=NULL, h=NULL, v=NULL, ylab=deparse(substitute(xts)), xlab="Time", lwd=1, lty=c(1,3), type="b", col=trellis.par.get("superpose.symbol")$col, col.line="gray60", ...) ## S3 method for class 'ts' seqplot(xts, pch.seq=letters, groups=as.numeric(cycle(xts)), x.at=pretty(time(xts)[groups==min(groups)]), x.labels, ylab=deparse(substitute(xts)), ...)
xts |
Time series |
pch.seq |
sequence of |
groups |
Numeric vector used to choose the plotting characters over cycles. |
a , b , h , v
|
Arguments to |
ylab , xlab , lwd , lty , type
|
standard trellis arguments. |
x.at , x.labels
|
shortcut for |
col |
Color of dots in sequence plot. The default is to make the
choose a number of colors to match the frequency of the time series |
col.line |
Color of connecting lines. The default is |
... |
Additional arguments to |
Richard M. Heiberger ([email protected])
seqplot(co2)
seqplot(co2)
seqplot
with confidence bands for the forecast region.
seqplotForecast(xts, forecast, multiplier = 1.96, series = deparse(substitute(observed)), ylim, CI.percent=round((1-2*(1-pnorm(multiplier)))*100,2), main = paste( series, " with forecast + ", CI.percent, "% CI", sep=""), xlab=NULL, ylab=NULL, ...) ## x.at, xlim
seqplotForecast(xts, forecast, multiplier = 1.96, series = deparse(substitute(observed)), ylim, CI.percent=round((1-2*(1-pnorm(multiplier)))*100,2), main = paste( series, " with forecast + ", CI.percent, "% CI", sep=""), xlab=NULL, ylab=NULL, ...) ## x.at, xlim
xts |
This is the observed series |
forecast |
forecast values based on the model |
multiplier |
Half-width of confidence interval in standard normal units. Defaults to 1.96. |
CI.percent |
Width of confidence band. Defaults to the standard
normal, two-sided value associated with the multiplier (95 percent
for the default |
series |
Name of time series will be used to construct the main title for the plot. |
ylim , xlab , ylab , main
|
standard trellis parameters |
... |
additional arguments to |
Richard M. Heiberger ([email protected])
Turn off the coloring in the trellis strip labels. Color 0 is the background color.
strip.background0()
strip.background0()
Richard M. Heiberger <[email protected]>
Functions based on strip.default
for use with the
useOuterScales
function. See useOuterScales
for more
information.
strip.useOuterStrips.first(which.given, which.panel, var.name, ...) strip.useOuterStrips.last(which.given, which.panel, var.name, ...) strip.left.useOuterStrips(which.given, which.panel, var.name, ...) strip.top2(which.given, which.panel, var.name, ...) strip.top1(which.given, which.panel, var.name, ...) strip.left2(which.given, which.panel, var.name, ...) strip.left1(which.given, which.panel, var.name, ...)
strip.useOuterStrips.first(which.given, which.panel, var.name, ...) strip.useOuterStrips.last(which.given, which.panel, var.name, ...) strip.left.useOuterStrips(which.given, which.panel, var.name, ...) strip.top2(which.given, which.panel, var.name, ...) strip.top1(which.given, which.panel, var.name, ...) strip.left2(which.given, which.panel, var.name, ...) strip.left1(which.given, which.panel, var.name, ...)
which.given , which.panel , var.name , ...
|
See |
The appropriate function is chosen by specifying arguments to
useOuterScales
.
strip.useOuterStrips.first
places strip labels at the top of the
first row of lattice panels. Used when as.table==TRUE
.
strip.useOuterStrips.last
places strip labels at the top of the
first row of lattice panels. Used when as.table==FALSE
.
strip.left.useOuterStrips
places strip labels at the left of the
first column of lattice panels.
strip.top2
places row strip labels at the top of each panel.
strip.top1
places column strip labels at the top of each panel.
strip.left2
places row strip labels at the left of each panel.
strip.left1
places column strip labels at the left of each panel.
See strip.default
.
Richard M. Heiberger <[email protected]>
## See examples in ?useOuterScales
## See examples in ?useOuterScales
strip function that is able to place the correlation and/or regression coefficient into the strip label.
strip.xysplom(which.given, which.panel, var.name, factor.levels, shingle.intervals, par.strip.text = trellis.par.get("add.text"), strip.names = c(TRUE, TRUE), style = 1, ...)
strip.xysplom(which.given, which.panel, var.name, factor.levels, shingle.intervals, par.strip.text = trellis.par.get("add.text"), strip.names = c(TRUE, TRUE), style = 1, ...)
which.given , which.panel , var.name , factor.levels , shingle.intervals
|
arguments to |
par.strip.text , strip.names , style , ...
|
more arguments to
|
The function looks for the specific factor names
c("corr","beta","corr.beta")
. If it finds them, it goes up the
calling sequence to locate the data for the panel. Then it calculates
the correlation and/of regression coefficient and inserts the
calculated value(s) as the value for the strip label.
Richard M. Heiberger <[email protected]>
Calculates the mean, standard deviation, and number of observations in each group of a data.frame that has one continuous variable and two factors.
sufficient(x, yname = dimnames(x)[[2]][[1]], factor.names.keep = dimnames(x)[[2]][-c(1, 2)])
sufficient(x, yname = dimnames(x)[[2]][[1]], factor.names.keep = dimnames(x)[[2]][-c(1, 2)])
x |
|
yname |
Character name of response variable. |
factor.names.keep |
Character vector containing the names of two
factors in the |
Data.frame containing five columns and as many rows as are implied by
the crossing of the two factors. Each row contains the mean in a
column with the name yname
and its factor values in columns
named with the name in factor.names.keep
. The standard deviation of
the observations in the group are in the column "sd"
and the number
of observations in the group is in the column "nobs"
.
Richard M. Heiberger <[email protected]>
summary and print and subscript methods for tsdiagplot and related objects.
## S3 method for class 'arma.loop' summary(object, ...) ## S3 method for class 'arma.loop.list' summary(object, ...) ## S3 method for class 'arma.loop' print(x, ...) ## S3 method for class 'arma.loop.list' print(x, ...) ## S3 method for class 'tsacfplots' print(x, ts.pos=c(.00, .00, .70, 1.00), acf.pos=c(.65, .10, 1.00, .90), ..., portrait=FALSE, ts.pos.portrait=c(0, .3, 1, 1), acf.pos.portrait=c(.1, 0, .9, .35)) ## S3 method for class 'arma.loop' x[..., drop = TRUE] ## S3 method for class 'diag.arma.loop' x[..., drop = TRUE]
## S3 method for class 'arma.loop' summary(object, ...) ## S3 method for class 'arma.loop.list' summary(object, ...) ## S3 method for class 'arma.loop' print(x, ...) ## S3 method for class 'arma.loop.list' print(x, ...) ## S3 method for class 'tsacfplots' print(x, ts.pos=c(.00, .00, .70, 1.00), acf.pos=c(.65, .10, 1.00, .90), ..., portrait=FALSE, ts.pos.portrait=c(0, .3, 1, 1), acf.pos.portrait=c(.1, 0, .9, .35)) ## S3 method for class 'arma.loop' x[..., drop = TRUE] ## S3 method for class 'diag.arma.loop' x[..., drop = TRUE]
x , object
|
object to be summarized or printed or subscripted. |
ts.pos , acf.pos , ts.pos.portrait , acf.pos.portrait
|
Default positions for |
portrait |
logical. If |
... |
additional arguments |
a
drop |
See
|
Richard M. Heiberger ([email protected])
arma.loop
, tsacfplots
, tsdiagplot
Change colors in a likert plot to shades of Black and White. This
function is tailored for a likert
plot, an example of a
"trellis"
object. likert
is based on
panel.bwplot
. There are other places in the structure of
a more general "trellis"
object where colors are stored.
The specifics for this plot is (1) that the colors for negative values in
the plot are in reverse order and (2) the color for a neutral-position panel appears on
both the positive and negative side. The default values are for
three items on the negative side, two on the positive side, and no
neutral.
See the examples for an example with a neutral.
ToBW.likert(x, colLegendOrder=c("gray70", "gray20", "gray60", "gray75", "gray45"), ## ^Ask Refu ^Imp | Impt Essn ## colBarchartOrder=colLegendOrder[c(3,2,1,4,5)], ## ^Imp Refu ^Ask | Impt Essn columns=5) ## negative colors are in reverse order in the BarchartOrder
ToBW.likert(x, colLegendOrder=c("gray70", "gray20", "gray60", "gray75", "gray45"), ## ^Ask Refu ^Imp | Impt Essn ## colBarchartOrder=colLegendOrder[c(3,2,1,4,5)], ## ^Imp Refu ^Ask | Impt Essn columns=5) ## negative colors are in reverse order in the BarchartOrder
x |
|
colLegendOrder |
Revised value of |
colBarchartOrder |
Revised value of both |
columns |
Revised value of |
"trellis"
object, identical to the input object except for the colors.
Richard M. Heiberger <[email protected]>
tmp <- array(1:20, c(4, 5), list(letters[1:4], c("NotAsked","VeryNegative","Negative","Positive","VeryPositive"))) tmp Ltmp <- likert(tmp, ReferenceZero=3.5, col=c("gray85", likertColor(4)), as.percent=TRUE) Ltmp ToBW.likert(Ltmp) ## with neutral tmp2 <- array(1:20, c(4, 5), list(letters[1:4], c("VeryNegative","Negative","Neutral","Positive","VeryPositive"))) tmp2 Ltmp2 <- likert(tmp2, ReferenceZero=3, col=likertColor(5), as.percent=TRUE, main="Neutral") Ltmp2 ToBW.likert(Ltmp2, colLegendOrder=c("gray20", "gray60", "gray85", "gray75", "gray45"), ## Neu|tral colBarchartOrder=c("gray85", "gray60", "gray20", "gray85", "gray75", "gray45") ## Neutral left Neutral right ) update(main="Wrong way to handle neutral", ToBW.likert(Ltmp2, colLegendOrder=c("gray20", "gray60", "gray85", "gray75", "gray45")) )
tmp <- array(1:20, c(4, 5), list(letters[1:4], c("NotAsked","VeryNegative","Negative","Positive","VeryPositive"))) tmp Ltmp <- likert(tmp, ReferenceZero=3.5, col=c("gray85", likertColor(4)), as.percent=TRUE) Ltmp ToBW.likert(Ltmp) ## with neutral tmp2 <- array(1:20, c(4, 5), list(letters[1:4], c("VeryNegative","Negative","Neutral","Positive","VeryPositive"))) tmp2 Ltmp2 <- likert(tmp2, ReferenceZero=3, col=likertColor(5), as.percent=TRUE, main="Neutral") Ltmp2 ToBW.likert(Ltmp2, colLegendOrder=c("gray20", "gray60", "gray85", "gray75", "gray45"), ## Neu|tral colBarchartOrder=c("gray85", "gray60", "gray20", "gray85", "gray75", "gray45") ## Neutral left Neutral right ) update(main="Wrong way to handle neutral", ToBW.likert(Ltmp2, colLegendOrder=c("gray20", "gray60", "gray85", "gray75", "gray45")) )
Reshape a 3-way array to a 2-way data.frame that can can be used with a
trellis conditioning formula to get the three-way behavior.
Used with likertWeighted()
.
toCQxR(x, C = 1, R = 2, Q = 3)
toCQxR(x, C = 1, R = 2, Q = 3)
x |
Three-way array, with dimensions "Classification", "Responses", "Questions" in some order. |
C , R , Q
|
Integers, one each of 1,2,3; positions of the three dimensions. |
Data.frame with CQ rows and Q + N columns, where N is either 1 or 2 for
the number of condition variables in the formula for likertWeighted
.
Richard M. Heiberger <[email protected]>
tmp3 <- array(1:40, c(4,5,2), list(LETTERS[1:4], LETTERS[5:9], LETTERS[10:11])) tmp3 toCQxR(tmp3)
tmp3 <- array(1:40, c(4,5,2), list(LETTERS[1:4], LETTERS[5:9], LETTERS[10:11])) tmp3 toCQxR(tmp3)
Coordinated time series and ACF and PCF plots.
tsacfplots(x, ylab=deparse(substitute(x)), x.name=ylab[[1]], main=paste("Series:", x.name), lag.at=NULL, lag.max=NULL, lag.units=NULL, lag.0=TRUE, ...) acf.pacf.plot(x, ylab=NULL, series=deparse(substitute(x)), main=paste("ACF and PACF:", series), lag.max, lag.units=frequency(x), lag.at=pretty(apacf$lag), lag.labels=lag.at*lag.units, lag.0=TRUE, strip=TRUE, strip.left=FALSE, ...)
tsacfplots(x, ylab=deparse(substitute(x)), x.name=ylab[[1]], main=paste("Series:", x.name), lag.at=NULL, lag.max=NULL, lag.units=NULL, lag.0=TRUE, ...) acf.pacf.plot(x, ylab=NULL, series=deparse(substitute(x)), main=paste("ACF and PACF:", series), lag.max, lag.units=frequency(x), lag.at=pretty(apacf$lag), lag.labels=lag.at*lag.units, lag.0=TRUE, strip=TRUE, strip.left=FALSE, ...)
x |
time series |
ylab , main
|
standard trellis arguments. |
x.name , series
|
Character string, name for the time series. |
lag.at |
Location of ticks for the acf and pacf plots. |
lag.labels |
Labels for ticks for the acf and pacf plots. |
lag.max |
Maximum lag used in the acf and pacf plots. |
lag.units |
Units for time series, defaults to |
lag.0 |
Logical. If |
strip , strip.left
|
Standard lattice arguments described in
|
... |
Additional arguments to |
The acf and pacf plots are scaled identically.
"tsacfplots"
object containing two "trellis"
objects.
Richard M. Heiberger ([email protected])
tsacfplots(co2) acf.pacf.plot(co2)
tsacfplots(co2) acf.pacf.plot(co2)
Times series diagnostic plots for a structured set of ARIMA models.
tsdiagplot(x, p.max=2, q.max=p.max, model=c(p.max, 0, q.max), ## S-Plus order=c(p.max, 0, q.max), ## R lag.max=36, gof.lag=lag.max, armas=arma.loop(x, order=order, series=deparse(substitute(x)), ...), diags=diag.arma.loop(armas, x, lag.max=lag.max, gof.lag=gof.lag), ts.diag=rearrange.diag.arma.loop(diags), lag.units=ts.diag$tspar["frequency"], lag.lim=range(pretty(ts.diag$acf$lag))*lag.units, lag.x.at=pretty(ts.diag$acf$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, lag.0=TRUE, main, lwd=0, ...) acfplot(rdal, type="acf", main=paste("ACF of std.resid:", rdal$series, " model:", rdal$model), lag.units=rdal$tspar["frequency"], lag.lim=range(pretty(rdal[[type]]$lag)*lag.units), lag.x.at=pretty(rdal[[type]]$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, lag.0=TRUE, xlim=xlim.function(lag.lim/lag.units), ...) aicsigplot(z, z.name=deparse(substitute(z)), series.name="ts", model=NULL, xlab="", ylab=z.name, main=paste(z.name, series.name, model), layout=c(1,2), between=list(x=1,y=1), ...) residplot(rdal, main=paste("std.resid:", rdal$series, " model:", rdal$model), ...) gofplot(rdal, main=paste("P-value for gof:", rdal$series, " model:", rdal$model), lag.units=rdal$tspar["frequency"], lag.lim=range(pretty(rdal$gof$lag)*lag.units), lag.x.at=pretty(rdal$gof$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, xlim=xlim.function(lag.lim/lag.units), pch=16, ...)
tsdiagplot(x, p.max=2, q.max=p.max, model=c(p.max, 0, q.max), ## S-Plus order=c(p.max, 0, q.max), ## R lag.max=36, gof.lag=lag.max, armas=arma.loop(x, order=order, series=deparse(substitute(x)), ...), diags=diag.arma.loop(armas, x, lag.max=lag.max, gof.lag=gof.lag), ts.diag=rearrange.diag.arma.loop(diags), lag.units=ts.diag$tspar["frequency"], lag.lim=range(pretty(ts.diag$acf$lag))*lag.units, lag.x.at=pretty(ts.diag$acf$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, lag.0=TRUE, main, lwd=0, ...) acfplot(rdal, type="acf", main=paste("ACF of std.resid:", rdal$series, " model:", rdal$model), lag.units=rdal$tspar["frequency"], lag.lim=range(pretty(rdal[[type]]$lag)*lag.units), lag.x.at=pretty(rdal[[type]]$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, lag.0=TRUE, xlim=xlim.function(lag.lim/lag.units), ...) aicsigplot(z, z.name=deparse(substitute(z)), series.name="ts", model=NULL, xlab="", ylab=z.name, main=paste(z.name, series.name, model), layout=c(1,2), between=list(x=1,y=1), ...) residplot(rdal, main=paste("std.resid:", rdal$series, " model:", rdal$model), ...) gofplot(rdal, main=paste("P-value for gof:", rdal$series, " model:", rdal$model), lag.units=rdal$tspar["frequency"], lag.lim=range(pretty(rdal$gof$lag)*lag.units), lag.x.at=pretty(rdal$gof$lag)*lag.units, lag.x.labels={tmp <- lag.x.at tmp[as.integer(tmp)!=tmp] <- "" tmp}, xlim=xlim.function(lag.lim/lag.units), pch=16, ...)
x |
Time series vector. |
p.max , q.max
|
Maximum number of AR and MA arguments to use in the series of ARIMA models. |
model |
A valid S-Plus |
order |
A valid R The additional argument |
lag.max |
Maximum lag for the acf and pacf plots. |
gof.lag |
Maximum lag for the gof plots. |
armas |
An |
diags |
An |
ts.diag , rdal
|
A list constructed as a rearranged |
lag.units |
Units for time series, defaults to |
lag.lim |
scaling for |
lag.x.at , lag.x.labels
|
Location of ticks and labels for the acf and pacf plots. |
lag.0 |
Logical. If |
type |
|
z |
A matrix constructed as the |
z.name |
|
series.name |
Character string describing the time series. |
xlab , ylab , layout , between , pch , xlim , main , lwd
|
Standard trellis arguments. |
... |
Additional arguments. |
tsdiagplot
returns a "tsdiagplot"
object which is
a list of "trellis"
objects. It is printed with its own
print method.
The other functions return "trellis"
objects.
Richard M. Heiberger ([email protected])
"Displays for Direct Comparison of ARIMA Models" The American Statistician, May 2002, Vol. 56, No. 2, pp. 131-138. Richard M. Heiberger, Temple University, and Paulo Teles, Faculdade de Economia do Porto.
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
data(tser.mystery.X) X <- tser.mystery.X X.dataplot <- tsacfplots(X, lwd=1, pch.seq=16, cex=.7) X.dataplot X.loop <- if.R( s= arma.loop(X, model=list(order=c(2,0,2))) ,r= arma.loop(X, order=c(2,0,2)) ) X.dal <- diag.arma.loop(X.loop, x=X) X.diag <- rearrange.diag.arma.loop(X.dal) X.diagplot <- tsdiagplot(armas=X.loop, ts.diag=X.diag, lwd=1) X.diagplot X.loop X.loop[["1","1"]]
data(tser.mystery.X) X <- tser.mystery.X X.dataplot <- tsacfplots(X, lwd=1, pch.seq=16, cex=.7) X.dataplot X.loop <- if.R( s= arma.loop(X, model=list(order=c(2,0,2))) ,r= arma.loop(X, order=c(2,0,2)) ) X.dal <- diag.arma.loop(X.loop, x=X) X.diag <- rearrange.diag.arma.loop(X.dal) X.diagplot <- tsdiagplot(armas=X.loop, ts.diag=X.diag, lwd=1) X.diagplot X.loop X.loop[["1","1"]]
Update a multi-panel "trellis" object so that scales for axes are
displayed only on the bottom and left boundaries when printed, instead
of in every panel as is usual. This function succeeds even when xlim
across columns and ylim across rows are not identical. Multiple options
are available for strip labels. The default for strip labels is similar
to useOuterStrips
. Additional options
include outerStrips for each panel and interchanged row and column strip
locations. This is only meaningful when there are exactly two
conditioning variables.
useOuterScales(x, axis.xlab.padding=4, ylab.axis.padding=3, strip, strip.left, layout.widths.strip.left=.5, layout.heights.strip=.5, x.ticks=is.numeric(x$x.limits), y.ticks= is.numeric(x$y.limits) + if (!missing(strip.left) && ## FALSE is.logical(strip.left) && ## explicitly stated !strip.left ) 0 else 2.5, inner=FALSE, interchangeRC=FALSE)
useOuterScales(x, axis.xlab.padding=4, ylab.axis.padding=3, strip, strip.left, layout.widths.strip.left=.5, layout.heights.strip=.5, x.ticks=is.numeric(x$x.limits), y.ticks= is.numeric(x$y.limits) + if (!missing(strip.left) && ## FALSE is.logical(strip.left) && ## explicitly stated !strip.left ) 0 else 2.5, inner=FALSE, interchangeRC=FALSE)
x |
An object of class |
ylab.axis.padding , axis.xlab.padding , layout.heights.strip , layout.widths.strip.left
|
These values are passed to the layout.widths=list(ylab.axis.padding=ylab.axis.padding, strip.left=layout.widths.strip.left), layout.heights=list(axis.xlab.padding=axis.xlab.padding, strip=layout.heights.strip) See |
strip , strip.left
|
|
x.ticks , y.ticks
|
|
inner |
Logical with default |
interchangeRC |
Logical with default |
useOuterScales
modifies a "trellis"
object with
length(dim(x)) == 2
so that when plotted,
scales appear on only the top and left panels of the array of panels.
Strips appear as specified, by default
on the top and left boundaries of the panel layout.
If the original "trellis"
object x
includes non-default
strip
and strip.left
arguments, they will be ignored. To
provide customized strip behaviour, specify the custom strip
functions directly as arguments to useOuterStrips
.
An object of class "trellis"
; essentially the same as x
, but
with certain properties modified.
Richard M. Heiberger <[email protected]>
OuterScalesData <- data.frame(y=1:16, AA=rep(factor(letters[1:8]), 2), BB=rep(factor(LETTERS[12:13]), each=8), CC=rep(factor(rep(LETTERS[9:11], times=c(3,1,4))), 2)) OuterScalesData BC0 <- barchart(AA ~ y | BB * CC, data=OuterScalesData, origin=0, scales=list(x=list(limits=c(0,16.5)), y=list(relation="free")), between=list(x=1, y=1), main="0. barchart") ## Not run: BC0 ## End(Not run) BC1 <- update( resizePanels(BC0, h=c(3,1,4)), main="1. resizePanels") BC1 BC2 <- update( useOuterStrips(BC1), main="2. useOuterStrips") ## package:latticeExtra BC2 BC3 <- update( useOuterScales(BC1), main="3. useOuterScales") BC3 ## Not run: BC4 <- update( useOuterScales(BC1), ylab="ABC", main="4. useOuterScales, ylab") BC4 BC5 <- update( useOuterScales(update(BC1, as.table=TRUE)), main="5. useOuterScales, as.table") BC5 try(useOuterScales(BC1, interchangeRC=TRUE)) ## incompatible options ## End(Not run) BC6 <- update( useOuterScales(BC1, inner=TRUE), main="6. useOuterScales, inner") BC6 ## Not run: BC7 <- update( useOuterScales(BC1, inner=TRUE, interchangeRC=TRUE), main="7. useOuterScales, inner, interchangeRC") BC7 BC8 <- update( useOuterScales(BC1, strip=FALSE), xlab.top=c("L","M"), main="8. useOuterScales, strip=FALSE, xlab.top") BC8 BC9 <- update( useOuterScales(BC1, strip=strip.default), main="9. useOuterScales, strip=strip.default") BC9 try(print(useOuterScales(BC1, strip=date))) ## date is not a valid strip function BC10 <- update( useOuterScales(BC1, strip.left=FALSE), ylab=c("I","J","K"), main="10. useOuterScales, strip.left=FALSE, ylab") BC10 BC11 <- update( useOuterScales(BC1, strip.left=strip.default), main="11. useOuterScales, strip.left=strip.default") BC11 try(print(useOuterScales(BC1, strip.left=date))) ## date is not a valid strip function BC12 <- update( useOuterScales(BC1, inner=TRUE, interchangeRC=TRUE, strip.left=FALSE), xlab.top=c("L","M"), main= "12. useOuterScales, inner, \n interchangeRC=TRUE, strip.left=FALSE, \n xlab.top, strip.background", par.settings=list(strip.background=list(col="gray98"))) BC12 BC13 <- update( useOuterScales(update(BC1, as.table=TRUE), inner=TRUE, interchangeRC=TRUE, strip.left=FALSE), xlab.top=c("L","M"), main="13. useOuterScales, inner, \n interchangeRC=TRUE, strip.left=FALSE, \n xlab.top, as.table") BC13 BC14 <- update( useOuterScales(BC1, inner=TRUE, strip=FALSE, interchangeRC=TRUE), ylab=list(c("I","J","K"), rot=0), main="14. useOuterScales, inner, \n strip=FALSE, interchangeRC, \n ylab") BC14 BC15 <- update( useOuterScales(BC1, strip=FALSE, strip.left=FALSE), xlab.top=c("L","M"), ylab=list(c("I","J","K"), rot=0), main="15. useOuterScales, strip=FALSE, strip.left=FALSE, \n xlab, ylab") BC15 ## End(Not run) ## Not run: ## display 16 options for strip labels with outerScales useOuterScales16 <- tempfile("useOuterScales16", fileext = ".pdf") pdf(useOuterScales16, height=16, width=21) print(BC0, split=c(1,1,4,4), more=TRUE) print(BC1, split=c(2,1,4,4), more=TRUE) print(BC2, split=c(3,1,4,4), more=TRUE) print(BC3, split=c(4,1,4,4), more=TRUE) print(BC4, split=c(1,2,4,4), more=TRUE) print(BC5, split=c(2,2,4,4), more=TRUE) print(BC6, split=c(3,2,4,4), more=TRUE) print(BC7, split=c(4,2,4,4), more=TRUE) print(BC8, split=c(1,3,4,4), more=TRUE) print(BC9, split=c(2,3,4,4), more=TRUE) print(BC10, split=c(3,3,4,4), more=TRUE) print(BC11, split=c(4,3,4,4), more=TRUE) print(BC12, split=c(1,4,4,4), more=TRUE) print(BC13, split=c(2,4,4,4), more=TRUE) print(BC14, split=c(3,4,4,4), more=TRUE) print(BC15, split=c(4,4,4,4), more=FALSE) dev.off() ## End(Not run) ## Not run: ## Verify y.ticks default value depends on ## is.numeric(x$y.limits). ## and on whether strip.left=FALSE CB0 <- barchart(y ~ AA | CC * BB, data=OuterScalesData, origin=0, scales=list(y=list(limits=c(0,16.5)), x=list(relation="free")), between=list(x=1, y=1), main="CB0. barchart") CB0 CB1 <- update( resizePanels(CB0, w=c(3,1,4)), main="CB1. resizePanels") CB1 CB2 <- update( useOuterStrips(CB1), main="CB2. useOuterStrips") ## package:latticeExtra CB2 CB3 <- update( useOuterScales(CB1), main="CB3. useOuterScales, y.limits is numeric") CB3 CB4 <- update( useOuterScales(CB1, strip.left=FALSE), main="CB4. useOuterScales, y.limits is numeric, strip.left=FALSE") CB4 BC16 <- update( useOuterScales(BC1), main="BC16. useOuterScales, y.limits is not numeric") BC16 BC17 <- update( useOuterScales(BC1, strip.left=FALSE), main="BC17. useOuterScales, y.limits is not numeric, strip.left=FALSE") BC17 ## End(Not run) ## Not run: ## Verify x.ticks default value depends on ## is.numeric(x$x.limits). update(BC3, main="BC3. useOuterScales, x.limits is numeric") update(CB3, main="CB3. useOuterScales, x.limits is not numeric") ## End(Not run)
OuterScalesData <- data.frame(y=1:16, AA=rep(factor(letters[1:8]), 2), BB=rep(factor(LETTERS[12:13]), each=8), CC=rep(factor(rep(LETTERS[9:11], times=c(3,1,4))), 2)) OuterScalesData BC0 <- barchart(AA ~ y | BB * CC, data=OuterScalesData, origin=0, scales=list(x=list(limits=c(0,16.5)), y=list(relation="free")), between=list(x=1, y=1), main="0. barchart") ## Not run: BC0 ## End(Not run) BC1 <- update( resizePanels(BC0, h=c(3,1,4)), main="1. resizePanels") BC1 BC2 <- update( useOuterStrips(BC1), main="2. useOuterStrips") ## package:latticeExtra BC2 BC3 <- update( useOuterScales(BC1), main="3. useOuterScales") BC3 ## Not run: BC4 <- update( useOuterScales(BC1), ylab="ABC", main="4. useOuterScales, ylab") BC4 BC5 <- update( useOuterScales(update(BC1, as.table=TRUE)), main="5. useOuterScales, as.table") BC5 try(useOuterScales(BC1, interchangeRC=TRUE)) ## incompatible options ## End(Not run) BC6 <- update( useOuterScales(BC1, inner=TRUE), main="6. useOuterScales, inner") BC6 ## Not run: BC7 <- update( useOuterScales(BC1, inner=TRUE, interchangeRC=TRUE), main="7. useOuterScales, inner, interchangeRC") BC7 BC8 <- update( useOuterScales(BC1, strip=FALSE), xlab.top=c("L","M"), main="8. useOuterScales, strip=FALSE, xlab.top") BC8 BC9 <- update( useOuterScales(BC1, strip=strip.default), main="9. useOuterScales, strip=strip.default") BC9 try(print(useOuterScales(BC1, strip=date))) ## date is not a valid strip function BC10 <- update( useOuterScales(BC1, strip.left=FALSE), ylab=c("I","J","K"), main="10. useOuterScales, strip.left=FALSE, ylab") BC10 BC11 <- update( useOuterScales(BC1, strip.left=strip.default), main="11. useOuterScales, strip.left=strip.default") BC11 try(print(useOuterScales(BC1, strip.left=date))) ## date is not a valid strip function BC12 <- update( useOuterScales(BC1, inner=TRUE, interchangeRC=TRUE, strip.left=FALSE), xlab.top=c("L","M"), main= "12. useOuterScales, inner, \n interchangeRC=TRUE, strip.left=FALSE, \n xlab.top, strip.background", par.settings=list(strip.background=list(col="gray98"))) BC12 BC13 <- update( useOuterScales(update(BC1, as.table=TRUE), inner=TRUE, interchangeRC=TRUE, strip.left=FALSE), xlab.top=c("L","M"), main="13. useOuterScales, inner, \n interchangeRC=TRUE, strip.left=FALSE, \n xlab.top, as.table") BC13 BC14 <- update( useOuterScales(BC1, inner=TRUE, strip=FALSE, interchangeRC=TRUE), ylab=list(c("I","J","K"), rot=0), main="14. useOuterScales, inner, \n strip=FALSE, interchangeRC, \n ylab") BC14 BC15 <- update( useOuterScales(BC1, strip=FALSE, strip.left=FALSE), xlab.top=c("L","M"), ylab=list(c("I","J","K"), rot=0), main="15. useOuterScales, strip=FALSE, strip.left=FALSE, \n xlab, ylab") BC15 ## End(Not run) ## Not run: ## display 16 options for strip labels with outerScales useOuterScales16 <- tempfile("useOuterScales16", fileext = ".pdf") pdf(useOuterScales16, height=16, width=21) print(BC0, split=c(1,1,4,4), more=TRUE) print(BC1, split=c(2,1,4,4), more=TRUE) print(BC2, split=c(3,1,4,4), more=TRUE) print(BC3, split=c(4,1,4,4), more=TRUE) print(BC4, split=c(1,2,4,4), more=TRUE) print(BC5, split=c(2,2,4,4), more=TRUE) print(BC6, split=c(3,2,4,4), more=TRUE) print(BC7, split=c(4,2,4,4), more=TRUE) print(BC8, split=c(1,3,4,4), more=TRUE) print(BC9, split=c(2,3,4,4), more=TRUE) print(BC10, split=c(3,3,4,4), more=TRUE) print(BC11, split=c(4,3,4,4), more=TRUE) print(BC12, split=c(1,4,4,4), more=TRUE) print(BC13, split=c(2,4,4,4), more=TRUE) print(BC14, split=c(3,4,4,4), more=TRUE) print(BC15, split=c(4,4,4,4), more=FALSE) dev.off() ## End(Not run) ## Not run: ## Verify y.ticks default value depends on ## is.numeric(x$y.limits). ## and on whether strip.left=FALSE CB0 <- barchart(y ~ AA | CC * BB, data=OuterScalesData, origin=0, scales=list(y=list(limits=c(0,16.5)), x=list(relation="free")), between=list(x=1, y=1), main="CB0. barchart") CB0 CB1 <- update( resizePanels(CB0, w=c(3,1,4)), main="CB1. resizePanels") CB1 CB2 <- update( useOuterStrips(CB1), main="CB2. useOuterStrips") ## package:latticeExtra CB2 CB3 <- update( useOuterScales(CB1), main="CB3. useOuterScales, y.limits is numeric") CB3 CB4 <- update( useOuterScales(CB1, strip.left=FALSE), main="CB4. useOuterScales, y.limits is numeric, strip.left=FALSE") CB4 BC16 <- update( useOuterScales(BC1), main="BC16. useOuterScales, y.limits is not numeric") BC16 BC17 <- update( useOuterScales(BC1, strip.left=FALSE), main="BC17. useOuterScales, y.limits is not numeric, strip.left=FALSE") BC17 ## End(Not run) ## Not run: ## Verify x.ticks default value depends on ## is.numeric(x$x.limits). update(BC3, main="BC3. useOuterScales, x.limits is numeric") update(CB3, main="CB3. useOuterScales, x.limits is not numeric") ## End(Not run)
Three-factor generalization of latticeExtra::useOuterStrips
useOuterStripsT2L1(x, ..., strip.height=.4, strip.names=c(TRUE, TRUE))
useOuterStripsT2L1(x, ..., strip.height=.4, strip.names=c(TRUE, TRUE))
x |
A |
... |
Additional arguments to be forwarded to the
|
strip.height |
Height of each the strip for each factor. The
number of factors in the top and left strips may not be the same.
This argument is multiplied by the number of factors in each
location
and sent on to the lattice |
strip.names |
See |
A trellis
object with two factors in the top strip
and 1
factor in the strip.left
.
Richard M. Heiberger <[email protected]>
tmp <- data.frame(A=rep(factor(letters[1:2]), each=12), B=rep(factor(letters[3:5]), each=4, times=2), C=rep(factor(letters[6:9]), times=6), x=1:24, y=1:24) F <- xyplot(y ~ x | B*A*C, data=tmp, panel=function(x, y, labels, ...) { panel.text(x, y, matrix(1:24, 6, 4, byrow=TRUE)[panel.number()], ...) }, layout=c(6, 4), between=list(x=c(.5, .5, 1.5), y=1)) F useOuterStripsT2L1(F)
tmp <- data.frame(A=rep(factor(letters[1:2]), each=12), B=rep(factor(letters[3:5]), each=4, times=2), C=rep(factor(letters[6:9]), times=6), x=1:24, y=1:24) F <- xyplot(y ~ x | B*A*C, data=tmp, panel=function(x, y, labels, ...) { panel.text(x, y, matrix(1:24, 6, 4, byrow=TRUE)[panel.number()], ...) }, layout=c(6, 4), between=list(x=c(.5, .5, 1.5), y=1)) F useOuterStripsT2L1(F)
The VIF for predictor is
, where
is the
from a regression of predictor
against the remaining
predictors.
vif(xx, ...) ## Default S3 method: vif(xx, y.name, na.action = na.exclude, ...) ## xx is a data.frame ## S3 method for class 'formula' vif(xx, data, na.action = na.exclude, ...) ## xx is a formula ## S3 method for class 'lm' vif(xx, na.action = na.exclude, ...) ## xx is a "lm" object computed with x=TRUE
vif(xx, ...) ## Default S3 method: vif(xx, y.name, na.action = na.exclude, ...) ## xx is a data.frame ## S3 method for class 'formula' vif(xx, data, na.action = na.exclude, ...) ## xx is a formula ## S3 method for class 'lm' vif(xx, na.action = na.exclude, ...) ## xx is a "lm" object computed with x=TRUE
xx |
|
na.action |
See
|
... |
additional arguments. |
y.name |
Name of Y-variable to be excluded from the computations. |
data |
A data frame in which the variables specified in the formula will be found. If missing, the variables are searched for in the standard way. |
A simple diagnostic of collinearity is the
variance inflation factor, VIF
one for each regression coefficient (other than the intercept).
Since the condition of collinearity involves the predictors but not
the response, this measure is a function of the 's but not of
.
The VIF for predictor
is
, where
is the
from a regression of predictor
against the remaining
predictors. If
is close to 1, this means that predictor
is well explained by a linear function of the remaining predictors,
and, therefore, the presence of predictor
in the model is
redundant. Values of VIF exceeding 5 are considered evidence of
collinearity: The information carried by a predictor having such a VIF
is contained in a subset of the remaining predictors. If, however,
all of a model's regression coefficients differ significantly from 0
(
-value
.05), a somewhat larger VIF may be tolerable.
Vector of VIF values, one for each X-variable.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
lm
.
data(usair) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair, x=TRUE) vif(usair.lm) ## the lm object must be computed with x=TRUE vif(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) vif(usair) vif(usair, y.name="lnSO2")
data(usair) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair, x=TRUE) vif(usair.lm) ## the lm object must be computed with x=TRUE vif(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) vif(usair) vif(usair, y.name="lnSO2")
Calculate the residuals from the regression of each column of a data.frame against all the other columns.
X.residuals(x, ...) ## Default S3 method: X.residuals(x, y.name, na.action = na.exclude, ...) ## x is a data.frame ## S3 method for class 'formula' X.residuals(x, data, na.action = na.exclude, ...) ## x is a formula ## S3 method for class 'lm' X.residuals(x, na.action = na.exclude, ...) ## x is a "lm" object computed with x=TRUE
X.residuals(x, ...) ## Default S3 method: X.residuals(x, y.name, na.action = na.exclude, ...) ## x is a data.frame ## S3 method for class 'formula' X.residuals(x, data, na.action = na.exclude, ...) ## x is a formula ## S3 method for class 'lm' X.residuals(x, na.action = na.exclude, ...) ## x is a "lm" object computed with x=TRUE
x |
|
na.action |
See
|
... |
additional arguments. |
y.name |
Name of Y-variable to be excluded from the computations. |
data |
A data frame in which the variables specified in the formula will be found. If missing, the variables are searched for in the standard way. |
Data.frame of residuals, one column from each regression.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
lm
,
data(usair) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) X.residuals(usair.lm) X.residuals(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) X.residuals(usair) X.residuals(usair, y.name="lnSO2")
data(usair) usair$lnSO2 <- log(usair$SO2) usair$lnmfg <- log(usair$mfgfirms) usair$lnpopn <- log(usair$popn) usair.lm <- lm(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) X.residuals(usair.lm) X.residuals(lnSO2 ~ temp + lnmfg + wind + precip, data=usair) X.residuals(usair) X.residuals(usair, y.name="lnSO2")
scatterplot matrix with potentially different sets of variables on the rows and columns. The slope or regression coefficient for simple least squares regression can be displayed in the strip label for each panel.
xysplom(x, ...) ## S3 method for class 'formula' xysplom(x, data=NULL, na.action = na.pass, ...) ## Default S3 method: xysplom(x, y=x, group, relation="free", x.relation=relation, y.relation=relation, xlim.in=NULL, ylim.in=NULL, corr=FALSE, beta=FALSE, abline=corr||beta, digits=3, x.between=NULL, y.between=NULL, between.in=list(x=x.between, y=y.between), scales.in=list( x=list(relation=x.relation, alternating=FALSE), y=list(relation=y.relation, alternating=FALSE)), strip.in=strip.xysplom, pch=16, cex=.75, panel.input=panel.xysplom, ..., cartesian=TRUE, plot=TRUE)
xysplom(x, ...) ## S3 method for class 'formula' xysplom(x, data=NULL, na.action = na.pass, ...) ## Default S3 method: xysplom(x, y=x, group, relation="free", x.relation=relation, y.relation=relation, xlim.in=NULL, ylim.in=NULL, corr=FALSE, beta=FALSE, abline=corr||beta, digits=3, x.between=NULL, y.between=NULL, between.in=list(x=x.between, y=y.between), scales.in=list( x=list(relation=x.relation, alternating=FALSE), y=list(relation=y.relation, alternating=FALSE)), strip.in=strip.xysplom, pch=16, cex=.75, panel.input=panel.xysplom, ..., cartesian=TRUE, plot=TRUE)
x |
In the |
... |
other arguments to |
z
data |
data.frame |
na.action |
See
Defaults to |
y |
In the |
group |
In the |
relation , x.relation , y.relation , scales.in
|
Alternate ways to get to the
|
xlim.in , ylim.in
|
Alternate ways to get to the
|
corr , beta
|
Display the correlation and/or the regression
coefficient for |
abline |
logical. If |
digits |
number of significant digits for the correlation coefficient. |
x.between , y.between , between.in
|
Alternate ways to get to the
|
strip.in |
strip function that knows how to handle the |
pch , cex
|
arguments to |
panel.input |
panel function used by |
cartesian |
When |
plot |
Defaults to |
The argument plot=TRUE
is the normal setting and then the
function returns a "trellis"
object. When the argument
plot=FALSE
, the function returns the argument list that would
otherwise be sent to xyplot
. This list is interesting when the
function xysplom
was designed because the function works
by restructuring the input data and running xyplot
on the
restructured data.
When plot=TRUE
(the normal setting),
the "trellis"
object containing the graph.
When plot=FALSE
, the restructured data that must be sent to the
xyplot
function.
Richard M. Heiberger <[email protected]>
Heiberger, Richard M. and Holland, Burt (2015). Statistical Analysis and Data Display: An Intermediate Course with Examples in R. Second Edition. Springer-Verlag, New York. https://link.springer.com/book/10.1007/978-1-4939-2122-5
in R.
## xysplom syntax options tmp <- data.frame(y=rnorm(12), x=rnorm(12), z=rnorm(12), w=rnorm(12), g=factor(rep(1:2,c(6,6)))) tmp2 <- tmp[,1:4] xysplom(y + w ~ x , data=tmp, corr=TRUE, beta=TRUE, cartesian=FALSE, layout=c(1,2)) xysplom(y + x ~ z | g, data=tmp, layout=c(2,2)) xysplom(y + x ~ z | g, data=tmp, cartesian=FALSE) xysplom(w + y ~ x + z, data=tmp) xysplom(w + y ~ x + z | g, data=tmp, layout=c(2,4)) xysplom(w + y ~ x + z | g, data=tmp, cartesian=FALSE) ## Not run: ## xyplot in R has many similar capabilities with xysplom if.R(r= xyplot(w + z ~ x + y, data=tmp, outer=TRUE) ,s= {} ) ## End(Not run)
## xysplom syntax options tmp <- data.frame(y=rnorm(12), x=rnorm(12), z=rnorm(12), w=rnorm(12), g=factor(rep(1:2,c(6,6)))) tmp2 <- tmp[,1:4] xysplom(y + w ~ x , data=tmp, corr=TRUE, beta=TRUE, cartesian=FALSE, layout=c(1,2)) xysplom(y + x ~ z | g, data=tmp, layout=c(2,2)) xysplom(y + x ~ z | g, data=tmp, cartesian=FALSE) xysplom(w + y ~ x + z, data=tmp) xysplom(w + y ~ x + z | g, data=tmp, layout=c(2,4)) xysplom(w + y ~ x + z | g, data=tmp, cartesian=FALSE) ## Not run: ## xyplot in R has many similar capabilities with xysplom if.R(r= xyplot(w + z ~ x + y, data=tmp, outer=TRUE) ,s= {} ) ## End(Not run)
Compute the test of hypothesis and compute confidence interval on the mean of a population when the standard deviation of the population is known.
z.test(x, mu = 0, stdev, alternative = c("two.sided", "less", "greater"), sd = stdev, n=length(x), conf.level = 0.95, ...)
z.test(x, mu = 0, stdev, alternative = c("two.sided", "less", "greater"), sd = stdev, n=length(x), conf.level = 0.95, ...)
x |
Vector of data values or the mean of the data. |
mu |
Hypothesized mean of the population. |
stdev |
Known standard deviation of the population. |
alternative |
Direction of the alternative hypothesis. |
sd |
Alternative to |
n |
The sample size if |
conf.level |
Confidence level for the interval computation. |
... |
Additional arguments are silently ignored. |
Many introductory statistical texts introduce inference by using the Z
test and Z based confidence intervals based on knowing the population
standard deviation. Most statistical packages do not include
functions to do Z tests since the T test is usually more appropriate
for real world situations. This function is meant to be used during
that short period of learning when the student is learning about
inference using Z procedures, but has not learned the T based
procedures yet. Once the student has learned about the T
distribution the t.test
function should be used instead of this
one (but the syntax is very similar, so this function should be an
appropriate introductory step to learning t.test
).
An object of class htest
containing the results
This function should be used for learning only, real data should
generally use t.test
.
These files z.test.R
and z.test.Rd
are from
the recently orphaned package TeachingDemos_2.12.1
Greg Snow [email protected]
x <- rnorm(25, 100, 5) z.test(x, 99, 5)
x <- rnorm(25, 100, 5) z.test(x, 99, 5)