⚠️There's a newer version (0.99.56) of this package.Take me there.

Tools for Descriptive Statistics and Exploratory Data Analysis

DescTools is an extensive collection of miscellaneous basic statistics functions and comfort wrappers not available in the R basic system for efficient description of data. The author’s intention was to create a toolbox, which facilitates the (notoriously time consuming) first descriptive tasks in data analysis, consisting of calculating descriptive statistics, drawing graphical summaries and reporting the results. The package contains furthermore functions to produce documents using MS Word (or PowerPoint) and functions to import data from Excel.

A considerable part of the included functions can be found scattered in other packages and other sources written partly by Titans of R. The reason for collecting them here, was primarily to have them consolidated in ONE instead of dozens of packages (which themselves might depend on other packages, which are not needed at all), and to provide a common and consistent interface as far as function and arguments naming, NA handling, recycling rules etc. are concerned. Google style guides were used as naming rules (in absence of convincing alternatives). The ‘CamelStyle’ was consequently applied to functions borrowed from contributed R packages as well.

Feedback, feature requests, bug reports and other suggestions are welcome! Please report problems to GitHub issues tracker (preferred), Stack Overflow mentioning DescTools or directly to the maintainer.

Installation

You can install the released version of DescTools from CRAN with:

install.packages("DescTools")

And the development version from GitHub with:

if (!require("remotes")) install.packages("remotes")
remotes::install_github("AndriSignorell/DescTools")

Warning

Warning: This package is still under development. Although the code seems meanwhile quite stable, until release of version 1.0 you should be aware that everything in the package might be subject to change. Backward compatibility is not yet guaranteed. Functions may be deleted or renamed and new syntax may be inconsistent with earlier versions. By release of version 1.0 the “deprecated-defunct process” will be installed.

MS-Office

To make use of MS-Office features, you must have Office in one of its variants installed. All Wrd*, XL* and Pp* functions require the package RDCOMClient to be installed as well. Hence the use of these functions is restricted to Windows systems. RDCOMClient can be installed with:

install.packages("RDCOMClient", repos="http://www.omegahat.net/R")

The omegahat repository does not benefit from the same update service as CRAN. So you may be forced to install a package compiled with an earlier version, which usually is not a problem. Use e.g. for R 3.6.x/R 4.0.x:

url <- "http://www.omegahat.net/R/bin/windows/contrib/3.5.1/RDCOMClient_0.93-0.zip"
url <- "http://www.omegahat.net/R/bin/windows/contrib/4.0/RDCOMClient_0.94-0.zip"
install.packages(url, repos = NULL, type = "binary")

RDCOMClient does not exist for Mac or Linux, sorry.

Authors

Andri Signorell
Helsana Versicherungen AG, Health Sciences, Zurich
HWZ University of Applied Sciences in Business Administration Zurich.

R is a community project. This can be seen from the fact that this package includes R source code and/or documentation previously published by various authors and contributors. Special thanks go to Beat Bruengger, Mathias Frueh, Daniel Wollschlaeger for their valuable contributions and testing. The good things come from all these guys, any problems are likely due to my tweaking. Thank you all!

Maintainer: Andri Signorell

Examples

library(DescTools)
demo(describe, package = "DescTools")
demo(plots, package = "DescTools")

Copy Link

Version

Install

install.packages('DescTools')

Monthly Downloads

52,170

Version

0.99.50

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

September 6th, 2023

Functions in DescTools (0.99.50)

Agree

Raw Simple And Extended Percentage Agreement
AllDuplicated

Index Vector of All Values Involved in Ties
ABCCoords

Coordinates for "bottomright", etc.
Append

Append Elements to Objects
Arrow

Insert an Arrow Into a Plot
BreuschGodfreyTest

Breusch-Godfrey Test
Bg

Background of a Plot
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
Between, Outside

Operators To Check, If a Value Lies Within Or Outside a Given Range
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Cross

Vector Cross Product
AUC

Area Under the Curve
Asp

Get Aspect Ratio of the Current Plot
ConvUnit

Unit Conversion and Metrix Prefixes
CrossN

n-dimensional Vector Cross Product
Cor

Covariance and Correlation (Matrices)
BhapkarTest

Bhapkar Marginal Homogeneity Test
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DescToolsOptions

DescTools Options
BinTree

Binary Tree
AddMonthsYM

Add a Month to a Date in YearMonth Format
AddMonths

Add a Month to a Date
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
Base Conversions

Converts Numbers From Binmode, Octmode or Hexmode to Decimal and Vice Versa
Abind

Combine Multidimensional Arrays
AllIdentical

Test Multiple Objects for Exact Equality
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
Benford

Benford's Distribution
Dot

Scalar Product
Abstract

Display Compact Abstract of a Data Frame
DrawArc

Draw Elliptic Arc(s)
DurbinWatsonTest

Durbin-Watson Test
Atkinson

Atkinson Index - A Measure of Inequality.
Assocs

Association Measures
AxisBreak

Place a Break Mark on an Axis
Entropy

Shannon Entropy and Mutual Information
BarText

Place Value Labels on a Barplot
BinomCI

Confidence Intervals for Binomial Proportions
CoefVar

Coefficient of Variation
CochranQTest

Cochran's Q test
Format

Format Numbers and Dates
BoxedText

Add Text in a Box to a Plot
ColToRgb

Color to RGB Conversion
ColToHsv

R Color to HSV Conversion
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
Frac

Fractional Part and Maximal Digits of a Numeric Value
CatTable

Function to write a table
BinomDiffCI

Confidence Interval for a Difference of Binomials
BarnardTest

Barnard's Unconditional Test
GetNewXL

Create a New Excel Instance
HexToCol

Identify Closest Match to a Color Given by a Hexadecimal String
GetNewWrd

Create a New Word Instance
CorPart

Find the Correlations for a Set x of Variables With Set y Removed
ColorLegend

Add a ColorLegend to a Plot
CramerVonMisesTest

Cramer-von Mises Test for Normality
CollapseTable

Collapse Levels of a Table
CohenD

Cohen's Effect Size
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
BinomCIn

Sample Size for a Given Width of a Binomial Confidence Interval
CohenKappa

Cohen's Kappa and Weighted Kappa
BubbleLegend

Add a Legend to a Bubble Plot
Canvas

Canvas for Geometric Plotting
BrierScore

Brier Score for Assessing Prediction Accuracy
CCC

Concordance Correlation Coefficient
BartelsRankTest

Bartels Rank Test of Randomness
CorPolychor

Polychoric Correlation
CompleteColumns

Find Complete Columns
CronbachAlpha

Cronbach's Coefficient Alpha
ColToHex

Convert a Color or a RGB-color Into Hex String
ColToGrey

Convert Colors to Grey/Grayscale
Closest

Find the Closest Value
ConnLines

Add Connection Lines to a Barplot
Clockwise

Calculates Begin and End Angle From a List of Given Angles in Clockwise Mode
Cstat

C Statistic (Area Under the ROC Curve)
Contrasts

Pairwise Contrasts
ConDisPairs

Concordant and Discordant Pairs
BoxCox

Box Cox Transformation
ConoverTest

Conover's Test of Multiple Comparisons
GenRandGroups

Generate Random Groups
Conf

Confusion Matrix And Associated Statistics
CutQ

Create a Factor Variable Using the Quantiles of a Continuous Variable
BootCI

Simple Bootstrap Confidence Intervals
Herfindahl

Concentration Measures
Dummy

Generate Dummy Codes for a Factor
Association measures

Cramer's V, Pearson's Contingency Coefficient and Phi Coefficient
Yule's Q and Y, Tschuprow's T
GenPareto

The Generalized Pareto Distribution
Gumbel

The Gumbel Distribution
CourseData

Get HWZ Datasets
FixToTable

Convert a Text to a Table
Datasets for Simulation

Datasets for Probabilistic Simulation
Coalesce

Return the First Element Not Being NA
CochranArmitageTest

Cochran-Armitage Test for Trend
DrawRegPolygon

Draw Regular Polygon(s)
DivCoef

Rao's Diversity Coefficient
FisherZ

Fisher-Transformation for Correlation to z-Score
DigitSum

Calculate Digit Sum
HodgesLehmann

Hodges-Lehmann Estimator of Location
ExtrVal

Distributions of Maxima and Minima
HexToRgb

Convert a Hexstring Color to a Matrix With Three Red/Green/Blue Rows
ColumnWrap

Column Wrap
DrawEllipse

Draw an Ellipse
DrawCircle

Draw a Circle
HoeffD

Matrix of Hoeffding's D Statistics
Date Functions

Basic Date Functions
CountCompCases

Count Complete Cases
DoCall

Fast Alternative To The Internal do.call
Factorize

Prime Factorization of Integers
Desc

Describe Data
DrawBand

Draw Confidence Band
DegToRad

Convert Degrees to Radians and Vice Versa
DoBy

Evaluates a Function Groupwise
DrawBezier

Draw a Bezier Curve
Frechet

The Frechet Distribution
CombPairs

Get All Pairs Out of One or Two Sets of Elements
Freq

Frequency Table for a Single Variable
JarqueBeraTest

(Robust) Jarque Bera Test
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
IsValidHwnd

Check Windows Pointer
GeomSn

Geometric Series
IsDichotomous

Test If a Variable Contains Only Two Unique Values
Some numeric checks

Check a Vector For Being Numeric, Zero Or a Whole Number
HuberM

Safe (generalized) Huber M-Estimator of Location
ICC

Intraclass Correlations (ICC1, ICC2, ICC3 From Shrout and Fleiss)
IsEuclid

Is a Distance Matrix Euclidean?
GeomTrans

Geometric Transformations
DunnTest

Dunn's Test of Multiple Comparisons
MHChisqTest

Mantel-Haenszel Chi-Square Test
LeveneTest

Levene's Test for Homogeneity of Variance
DivCoefMax

Maximal value of Rao's diversity coefficient also called quadratic entropy
CountWorkDays

Count Work Days Between Two Dates
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
Divisors

Calculate Divisors
LOF

Local Outlier Factor
Mar and Mgp

Set Plot Margins and Distances
Lc

Lorenz Curve
Label, Unit

Label, Unit Attribute of an Object
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
EtaSq

Effect Size Calculations for ANOVAs
GCD, LCM

Greatest Common Divisor and Least Common Multiple
ErrBars

Add Error Bars to an Existing Plot
GetCalls

Return All Used Functions Within a Function
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
PDFManual

Get PDF Manual of a Package From CRAN
ImputeKnn

Fill in NA values with the values of the nearest neighbours
Gmean

Geometric Mean and Standard Deviation
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
LOCF

Last Observation Carried Forward
LinScale

Linear Scaling
MeanDiffCI

Confidence Interval For Difference of Means
DunnettTest

Dunnett's Test for Comparing Several Treatments With a Control
FctArgs

Retrieve a Function's Arguments
PMT

Periodic Payment of an Annuity.
Keywords

List Keywords For R Manual Pages
Mean

(Weighted) Arithmetic Mean
Gompertz

The Gompertz distribution
ExpFreq

Expected Frequencies
IQRw

The (weighted) Interquartile Range
MeanAD

Mean Absolute Deviation From a Center Point
MeanSE

Standard Error of Mean
LineToUser

Convert Line Coordinates To User Coordinates
Gini

Gini Coefficient
ORToRelRisk

Transform Odds Ratio to Relative Risk
LehmacherTest

Lehmacher's Test for Marginal Homogenity
OddsRatio

Odds Ratio Estimation and Confidence Intervals
Lambda

Goodman Kruskal Lambda
Fibonacci

Fibonacci Numbers
FindColor

Get Color on a Defined Color Range
Midx

Find the Midpoints of a Numeric Vector
MixColor

Compute the Convex Combination of Two Colors
MultinomCI

Confidence Intervals for Multinomial Proportions
Permn

Number and Samples for Permutations or Combinations of a Set
PercentRank

Percent Ranks
GenExtrVal

The Generalized Extreme Value Distribution
Hmean

Harmonic Mean and Its Confidence Interval
Extremes

Kth Smallest/Largest Values
List Variety Of Objects

List Objects, Functions Or Data in a Package
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
FindCorr

Determine Highly Correlated Variables
GoodmanKruskalGamma

Goodman Kruskal's Gamma
GTest

G-Test for Count Data
ParseFormula

Parse a Formula and Create a Model Frame
PlotBubble

Draw a Bubble Plot
NPV

Short Selection of Financial Mathematical Functions
HmsToSec

Convert h:m:s To/From Seconds
Phrase

Phrasing Results of t-Test
MAD

Median Absolute Deviation
PlotCandlestick

Plot Candlestick Chart
IsDate

Check If an Object Is of Type Date
IsOdd

Checks If An Integer Is Even Or Odd
DescTools Palettes

Some Custom Palettes
InDots

Is a Specific Argument in the Dots-Arguments?
PlotACF

Combined Plot of a Time Series and Its ACF and PACF
HotellingsT2Test

Hotelling's T2 Test
MADCI

Confidence Intervals for Median Absolute Deviations
IsPrime

IsPrime Property
GoodmanKruskalTau

Goodman Kruskal's Tau
Nf

As Numeric Factor
NemenyiTest

Nemenyi Test
Mode

Mode, Most Frequent Value(s)
KendallW

Kendall's Coefficient of Concordance W
MosesTest

Moses Test of Extreme Reactions
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
MoveAvg

Moving Average
KappaM

Kappa for m Raters
Measures of Accuracy

Measures of Accuracy
MultMerge

Merge Multiple Data Frames
KendallTauB

Kendall's \(\tau_{b}\)
PlotFdist

Frequency Distribution Plot
PlotBag

Bivariate Boxplot
PlotFaces

Chernoff Faces
PlotArea

Create an Area Plot
PearsonTest

Pearson Chi-Square Test for Normality
KendallTauA

Kendall's \(\tau_{a}\)
PageTest

Exact Page Test for Ordered Alternatives
LogSt

Started Logarithmic Transformation and Its Inverse
PairApply

Pairwise Calculations
PlotFun

Plot a Function
PlotDot

Cleveland's Dot Plots
PlotMarDens

Scatterplot With Marginal Densities
Logit

Generalized Logit and Inverse Logit Function
PlotLinesA

Plot Lines
PlotPairs

Extended Scatterplot Matrices
PlotLog

Logarithmic Plot
PlotPolar

Plot Values on a Circular Grid
PlotQQ

QQ-Plot for Any Distribution
PlotConDens

Plot Conditional Densities
MeanCIn

Sample Size for a Given Width of a Confidence Interval for a Mean
MeanCI

Confidence Interval for the Mean
PlotMosaic

Mosaic Plots
PlotTernary

Ternary or Triangular Plots
PlotECDF

Empirical Cumulative Distribution Function
PlotMultiDens

Plot Multiple Density Curves
PlotCorr

Plot a Correlation Matrix
MedianCI

Confidence Interval for the Median
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotMiss

Plot Missing Data
Outlier

Outlier
Order

Distributions of Order Statistics
PercTable

Percentage Table
Median

(Weighted) Median Value
PlotCashFlow

Cash Flow Plot
PlotVenn

Plot a Venn Diagram
ParseSASDatalines

Parse a SAS Dataline Command
PlotCirc

Plot Circular Plot
PasswordDlg

Password Dialog
PlotTreemap

Create a Treemap
PlotProbDist

Plot Probability Distribution
PlotPyramid

Draw a Back To Back Pyramid Plot
PtInPoly

Point in Polygon
PlotWeb

Plot a Web of Connected Points
PostHocTest

Post-Hoc Tests
Quantile

(Weighted) Sample Quantiles
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PseudoR2

Pseudo R2 Statistics
Primes

Find All Primes Less Than n
PoissonCI

Poisson Confidence Interval
PolarGrid

Plot a Grid in Polar Coordinates
PlotViolin

Plot Violins Instead of Boxplots
RSessionAlive

How Long Has the RSession Been Running?
QuantileCI

Confidence Interval for Any Quantile
reorder.factor

Reorder the Levels of a Factor
Quot

Lagged Quotients
RelRisk

Relative Risk
Recode

Recode a Factor
Recycle

Recyle a List of Elements
Rename

Change Names of a Named Object
Rank

Fast Sample Ranks
Range

(Robust) Range
Rev

Reverse Elements of a Vector, a Matrix, a Table, an Array or a Data.frame
RgbToCmy

Conversion Between RGB and CMYK
RevCode

Reverse Codes
pRevGumbel

"Reverse" Gumbel Distribution Functions
ColToOpaque

Equivalent Opaque Color for Transparent Color
RgbToCol

Find the Nearest Named R-Color to a Given RGB-Color
RevWeibull

The Reverse Weibull Distribution
RndPairs

Create Pairs of Correlated Random Numbers
RomanToInt

Convert Roman Numerals to Integers
RobScale

Robust Scaling With Median and Mad
Depreciation

Several Methods of Depreciation of an Asset
RoundTo

Round to Multiple
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
SaveAs

Saves an R Object Under a Different Name
SampleTwins

Sample Twins
Rotate

Rotate a Geometric Structure
RunsTest

Runs Test for Randomness
SD

(Weighted) Standard Deviation
Sample

Random Samples and Permutations
SendOutlookMail

Send a Mail Using Outlook as Mail Client
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
Some

Return Some Randomly Chosen Elements of an Object
SetAlpha

Add an Alpha Channel To a Color
SmoothSpline

Formula Interface For smooth.spline
Shade

Produce a Shaded Curve
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Measures of Shape

Skewness and Kurtosis
SomersDelta

Somers' Delta
SetNames

Set the Names in an Object
SignTest

Sign Test
SplitPath

Split Path In Drive, Path, Filename
SplitToDummy

Split Strings of a Vector and Provide Dummy Codes for Found Pieces
Stamp

Date/Time/Directory Stamp the Current Plot
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
Sort

Sort a Vector, a Matrix, a Table or a Data.frame
SpearmanRho

Spearman Rank Correlation
StdCoef

Standardized Model Coefficients
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrPad

Pad a String With Justification
SplitToCol

Split Data Frame String Column Into Multiple Columns
StrAlign

String Alignment
StrChop

Split a String into a Number of Sections of Defined Length
StrDist

Compute Distances Between Strings
StrCap

Capitalize the First Letter of a String
StrIsNumeric

Does a String Contain Only Numeric Data
Str

Compactly Display the Structure of any R Object
StrCountW

Count Words in a String
StrAbbr

String Abbreviation
StrExtract

Extract Part of a String
StrPos

Find Position of First Occurrence Of a String
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
StrTrunc

Truncate Strings and Add Ellipses If a String is Truncated.
StrSpell

Spell a String Using the NATO Phonetic or the Morse Alphabet
StripAttr

Remove Attributes from an Object
StrSplit

Split the Elements of a Character Vector
Strata

Stratified Sampling
StrTrim

Remove Leading/Trailing Whitespace From A String
StrRev

Reverse a String
StrVal

Extract All Numeric Values From a String
SysInfo

System Information
TextContrastColor

Choose Textcolor Depending on Background Color
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
TheilU

Theil's U Index of Inequality
TOne

Create Table One Describing Baseline Characteristics
TTestA

Student's t-Test Based on Sample Statistics
TextToTable

Converts String To a Table
StuartTauC

Stuart \(\tau_{c}\)
TMod

Comparison Table For Linear Models
TitleRect

Plot Boxed Annotation
TwoGroups

Describe a Variable by a Factor with Two Levels
ToLong, ToWide

Reshape a Vector From Long to Wide Shape Or Vice Versa
UnirootAll

Finds many (all) roots of one equation within an interval
UncertCoef

Uncertainty Coefficient
ToWrdB

Send Objects to Word and Bookmark Them
ToWrdPlot

Send a Plot to Word and Bookmark it
ToWrd

Send Objects to Word
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Untable

Recover Original Data From Contingency Table
Trim

Trim a Vector
VarCI

Confidence Intervals for the Variance
VarTest

ChiSquare Test for One Variance and F Test to Compare Two Variances
Unwhich

Inverse Which
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
Vigenere

Vigenere Cypher
VIF

Variance Inflation Factors
VanWaerdenTest

van der Waerden Test
Var

Variance
VonNeumannTest

Von Neumann's Successive Difference Test
WrdCellRange

Return the Cell Range Of a Word Table
WrdPageBreak

Insert a Page Break
VecRot

Vector Rotation (Shift Elements)
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WithOptions

Execute Function with Temporary Options
WrdStyle

Get or Set the Style in Word
WrdTableBorders

Draw Borders to a Word Table
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WrdCaption

Insert Caption to Word
XLGetRange

Import Data Directly From Excel
WrdMergeCells

Merges Cells Of a Defined Word Table Range
WrdFormatCells

Format Cells Of a Word Table
XLDateToPOSIXct

Convert Excel Dates to POSIXct
WrdFont

Get or Set the Font in Word
WrdTable

Insert a Table in a Word Document
WrdPlot

Insert Active Plot to Word
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
XLSaveAs

Save Excel File
ZTest

Z Test for Known Population Standard Deviation
d.pizza

Data pizza
ZeroIfNA

Replace NAs by 0
d.whisky

Classification of Scotch Single Malts
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
d.countries

ISO 3166-1 Country Codes
WrdSaveAs

Open and Save Word Documents
Zodiac

Calculate the Zodiac of a Date
XLView

Use MS-Excel as Viewer for a Data.Frame
d.diamonds

Data diamonds
DescTools Aliases

Some Aliases Set for Convenience
d.periodic

Periodic Table of Elements
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
as.matrix.xtabs

Convert xtabs To matrix
YuenTTest

Yuen t-Test For Trimmed Means
%nin%

Find Matching (or Non-Matching) Elements
%c%

Concatenates Two Strings Without Any Separator
rSum21

Random Numbers Adding Up to 1
matpow

Matrix Power
lines.loess

Add a Loess or a Spline Smoother
day.name

Build-in Constants Extension
%like%

Like Operator
power.chisq.test

Power Calculations for ChiSquared Tests
identify.formula

Identify Points In a Plot Using a Formula
lines.lm

Add a Linear Regression Line
split.formula

Formula Interface for Split
wdConst

Word VBA Constants