Learn R Programming

⚠️There's a newer version (0.99.60) 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

104,795

Version

0.99.45

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

May 9th, 2022

Functions in DescTools (0.99.45)

AddMonths

Add a Month to a Date
ABCCoords

Coordinates for "bottomright", etc.
Agree

Raw Simple And Extended Percentage Agreement
AddMonthsYM

Add a Month to a Date in YearMonth Format
AllIdentical

Test Multiple Objects for Exact Equality
Abind

Combine Multidimensional Arrays
AllDuplicated

Index Vector of All Values Involved in Ties
AxisBreak

Place a Break Mark on an Axis
Abstract

Display Compact Abstract of a Data Frame
BartelsRankTest

Bartels Rank Test of Randomness
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
BarnardTest

Barnard's Unconditional Test
BarText

Place Value Labels on a Barplot
Append

Append Elements to Objects
AUC

Area Under the Curve
Atkinson

Atkinson Index - A Measure of Inequality.
Assocs

Association Measures
Asp

Get Aspect Ratio of the Current Plot
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
BhapkarTest

Bhapkar Marginal Homogeneity Test
BinTree

Binary Tree
Arrow

Insert an Arrow Into a Plot
BreuschGodfreyTest

Breusch-Godfrey Test
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
BrierScore

Brier Score for Assessing Prediction Accuracy
BinomDiffCI

Confidence Interval for a Difference of Binomials
BubbleLegend

Add a Legend to a Bubble Plot
BootCI

Simple Bootstrap Confidence Intervals
Clockwise

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

Box Cox Transformation
BinomCI

Confidence Intervals for Binomial Proportions
CatTable

Function to write a table
BinomCIn

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

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
Bg

Background of a Plot
Between, Outside

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

Automatic Selection of Box Cox Transformation Parameter
BoxedText

Add Text in a Box to a Plot
CCC

Concordance Correlation Coefficient
CompleteColumns

Find Complete Columns
Base Conversions

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

Benford's Distribution
CohenD

Cohen's Effect Size
ConvUnit

Unit Conversion and Metrix Prefixes
CohenKappa

Cohen's Kappa and Weighted Kappa
Cor

Covariance and Correlation (Matrices)
Canvas

Canvas for Geometric Plotting
CochranQTest

Cochran's Q test
Coalesce

Return the First Element Not Being NA
Contrasts

Pairwise Contrasts
ConoverTest

Conover's Test of Multiple Comparisons
CoefVar

Coefficient of Variation
ColorLegend

Add a ColorLegend to a Plot
DivCoefMax

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

Concordant and Discordant Pairs
CochranArmitageTest

Cochran-Armitage Test for Trend
CollapseTable

Collapse Levels of a Table
CourseData

Get HWZ Datasets
Association measures

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

Count Complete Cases
CountWorkDays

Count Work Days Between Two Dates
ColToHsv

R Color to HSV Conversion
ColToRgb

Color to RGB Conversion
Cstat

C Statistic (Area Under the ROC Curve)
CutQ

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

Find the Closest Value
CrossN

n-dimensional Vector Cross Product
ColToGrey

Convert Colors to Grey/Grayscale
Cross

Vector Cross Product
DrawCircle

Draw a Circle
CramerVonMisesTest

Cramer-von Mises Test for Normality
CorPolychor

Polychoric Correlation
ColToHex

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

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

Draw an Ellipse
DunnettTest

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

Dunn's Test of Multiple Comparisons
ColumnWrap

Column Wrap
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
Divisors

Calculate Divisors
ExtrVal

Distributions of Maxima and Minima
DurbinWatsonTest

Durbin-Watson Test
DoBy

Evaluates a Function Groupwise
CronbachAlpha

Cronbach's Coefficient Alpha
DegToRad

Convert Degrees to Radians and Vice Versa
DescToolsOptions

DescTools Options
DoCall

Fast Alternative To The Internal do.call
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
Factorize

Prime Factorization of Integers
FindColor

Get Color on a Defined Color Range
ExpFreq

Expected Frequencies
Dot

Scalar Product
ErrBars

Add Error Bars to an Existing Plot
EtaSq

Effect Size Calculations for ANOVAs
FindCorr

Determine Highly Correlated Variables
GetNewXL

Create a New Excel Instance
DrawArc

Draw Elliptic Arc(s)
GetNewWrd

Create a New Word Instance
Entropy

Shannon Entropy and Mutual Information
Frechet

The Frechet Distribution
HexToRgb

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

Fisher-Transformation for Correlation to z-Score
HexToCol

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

Frequency Table for a Single Variable
GeomSn

Geometric Series
GeomTrans

Geometric Transformations
FixToTable

Convert a Text to a Table
Hmean

Harmonic Mean and Its Confidence Interval
GoodmanKruskalGamma

Goodman Kruskal's Gamma
Desc

Describe Data
HmsToSec

Convert h:m:s To/From Seconds
GTest

G-Test for Count Data
GoodmanKruskalTau

Goodman Kruskal's Tau
CombPairs

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

Hodges-Lehmann Estimator of Location
HoeffD

Matrix of Hoeffding's D Statistics
Fibonacci

Fibonacci Numbers
Conf

Confusion Matrix And Associated Statistics
DrawRegPolygon

Draw Regular Polygon(s)
GenExtrVal

The Generalized Extreme Value Distribution
Datasets for Simulation

Datasets for Probabilistic Simulation
Dummy

Generate Dummy Codes for a Factor
GetCalls

Return All Used Functions Within a Function
ConnLines

Add Connection Lines to a Barplot
FctArgs

Retrieve a Function's Arguments
InDots

Is a Specific Argument in the Dots-Arguments?
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
IsValidHwnd

Check Windows Pointer
Some numeric checks

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

The Gumbel Distribution
Herfindahl

Concentration Measures
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
IsDate

Check If an Object Is of Type Date
DivCoef

Rao's Diversity Coefficient
Date Functions

Basic Date Functions
DrawBand

Draw Confidence Band
DigitSum

Calculate Digit Sum
KendallTauB

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

Generate Random Groups
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Gini

Gini Coefficient
GenPareto

The Generalized Pareto Distribution
Gompertz

The Gompertz distribution
Keywords

List Keywords For R Manual Pages
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
Gmean

Geometric Mean and Standard Deviation
ImputeKnn

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

Safe (generalized) Huber M-Estimator of Location
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
KendallW

Kendall's Coefficient of Concordance W
LineToUser

Convert Line Coordinates To User Coordinates
LinScale

Linear Scaling
Lambda

Goodman Kruskal Lambda
ICC

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

Is a Distance Matrix Euclidean?
IsDichotomous

Test If a Variable Contains Only Two Unique Values
Lc

Lorenz Curve
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Mean

(Weighted) Arithmetic Mean
KappaM

Kappa for m Raters
DrawBezier

Draw a Bezier Curve
HotellingsT2Test

Hotelling's T2 Test
KendallTauA

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

Mean Absolute Deviation From a Center Point
MosesTest

Moses Test of Extreme Reactions
Frac

Fractional Part and Maximal Digits of a Numeric Value
Extremes

Kth Smallest/Largest Values
Format

Format Numbers and Dates
MultinomCI

Confidence Intervals for Multinomial Proportions
Mode

Mode, Most Frequent Value(s)
NPV

Short Selection of Financial Mathematical Functions
PercentRank

Percent Ranks
PercTable

Percentage Table
MHChisqTest

Mantel-Haenszel Chi-Square Test
List Variety Of Objects

List Objects, Functions Or Data in a Package
IQRw

The (weighted) Interquartile Range
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
Measures of Accuracy

Measures of Accuracy
JarqueBeraTest

(Robust) Jarque Bera Test
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
PDFManual

Get PDF Manual of a Package From CRAN
MADCI

Confidence Intervals for Median Absolute Deviations
Permn

Number and Samples for Permutations or Combinations of a Set
Outlier

Outlier
MAD

Median Absolute Deviation
PlotBag

Bivariate Boxplot
LOCF

Last Observation Carried Forward
LogSt

Started Logarithmic Transformation and Its Inverse
Median

(Weighted) Median Value
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
MedianCI

Confidence Interval for the Median
IsPrime

IsPrime Property
Logit

Generalized Logit and Inverse Logit Function
Mar and Mgp

Set Plot Margins and Distances
MixColor

Compute the Convex Combination of Two Colors
IsOdd

Checks If An Integer Is Even Or Odd
Midx

Find the Midpoints of a Numeric Vector
PlotACF

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

Moving Average
PlotArea

Create an Area Plot
PlotMarDens

Scatterplot With Marginal Densities
PlotBubble

Draw a Bubble Plot
PlotMiss

Plot Missing Data
RgbToCmy

Conversion Between RGB and CMYK
RSessionAlive

How Long Has the RSession Been Running?
Phrase

Phrasing Results of t-Test
PMT

Periodic Payment of an Annuity.
Quot

Lagged Quotients
MultMerge

Merge Multiple Data Frames
PairApply

Pairwise Calculations
PageTest

Exact Page Test for Ordered Alternatives
SampleTwins

Sample Twins
RgbToCol

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

Transform Odds Ratio to Relative Risk
NemenyiTest

Nemenyi Test
PlotCandlestick

Plot Candlestick Chart
LOF

Local Outlier Factor
Sample

Random Samples and Permutations
PlotCashFlow

Cash Flow Plot
Label, Unit

Label, Unit Attribute of an Object
ParseFormula

Parse a Formula and Create a Model Frame
SetNames

Set the Names in an Object
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
SpearmanRho

Spearman Rank Correlation
PlotFdist

Frequency Distribution Plot
PlotFun

Plot a Function
Shade

Produce a Shaded Curve
PlotTernary

Ternary or Triangular Plots
PlotTreemap

Create a Treemap
PseudoR2

Pseudo R2 Statistics
PtInPoly

Point in Polygon
RelRisk

Relative Risk
StrAlign

String Alignment
StrAbbr

String Abbreviation
StripAttr

Remove Attributes from an Object
RndPairs

Create Pairs of Correlated Random Numbers
Rename

Change Names of a Named Object
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotMultiDens

Plot Multiple Density Curves
PlotMosaic

Mosaic Plots
RobScale

Robust Scaling With Median and Mad
ParseSASDatalines

Parse a SAS Dataline Command
PlotPairs

Extended Scatterplot Matrices
PlotECDF

Empirical Cumulative Distribution Function
DescTools Palettes

Some Custom Palettes
SaveAs

Saves an R Object Under a Different Name
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
SplitToCol

Split Data Frame String Column Into Multiple Columns
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
ShapiroFranciaTest

Shapiro-Francia Test for Normality
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
LeveneTest

Levene's Test for Homogeneity of Variance
SplitToDummy

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

Plot Violins Instead of Boxplots
PlotDot

Cleveland's Dot Plots
PlotVenn

Plot a Venn Diagram
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
MeanCIn

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

Plot a Correlation Matrix
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
PlotFaces

Chernoff Faces
MeanCI

Confidence Interval for the Mean
MeanDiffCI

Confidence Interval For Difference of Means
StrExtract

Extract Part of a String
MeanSE

Standard Error of Mean
Order

Distributions of Order Statistics
PolarGrid

Plot a Grid in Polar Coordinates
StuartTauC

Stuart \(\tau_{c}\)
OddsRatio

Odds Ratio Estimation and Confidence Intervals
SysInfo

System Information
StrIsNumeric

Does a String Contain Only Numeric Data
PasswordDlg

Password Dialog
PearsonTest

Pearson Chi-Square Test for Normality
PlotCirc

Plot Circular Plot
Untable

Recover Original Data From Contingency Table
PlotConDens

Plot Conditional Densities
Recycle

Recyle a List of Elements
PostHocTest

Post-Hoc Tests
Recode

Recode a Factor
Primes

Find All Primes Less Than n
RoundTo

Round to Multiple
Range

(Robust) Range
RunsTest

Runs Test for Randomness
PlotPyramid

Draw a Back To Back Pyramid Plot
Unwhich

Inverse Which
TextToTable

Converts String To a Table
TheilU

Theil's U Index of Inequality
Sort

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

QQ-Plot for Any Distribution
SomersDelta

Somers' Delta
StrSpell

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

Split the Elements of a Character Vector
PlotWeb

Plot a Web of Connected Points
TTestA

Student's t-Test Based on Sample Statistics
PlotLinesA

Plot Lines
TextContrastColor

Choose Textcolor Depending on Background Color
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
TwoGroups

Describe a Variable by a Factor with Two Levels
UncertCoef

Uncertainty Coefficient
WithOptions

Execute Function with Temporary Options
PlotLog

Logarithmic Plot
UnirootAll

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

Get or Set the Font in Word
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
WrdFormatCells

Format Cells Of a Word Table
VarTest

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

Convert Excel Dates to POSIXct
d.whisky

Classification of Scotch Single Malts
%like%

Like Operator
identify.formula

Identify Points In a Plot Using a Formula
day.name

Build-in Constants Extension
XLGetRange

Import Data Directly From Excel
VecRot

Vector Rotation (Shift Elements)
PlotPolar

Plot Values on a Circular Grid
ZeroIfNA

Replace NAs by 0
Zodiac

Calculate the Zodiac of a Date
XLSaveAs

Save Excel File
Rank

Fast Sample Ranks
%nin%

Find Matching (or Non-Matching) Elements
RevCode

Reverse Codes
PoissonCI

Poisson Confidence Interval
as.matrix.xtabs

Convert xtabs To matrix
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
XLView

Use MS-Excel as Viewer for a Data.Frame
DescTools Aliases

Some Aliases Set for Convenience
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
matpow

Matrix Power
RevWeibull

The Reverse Weibull Distribution
Stamp

Date/Time/Directory Stamp the Current Plot
StrChop

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

Spread Out a Vector of Numbers To a Minimum Interval
ColToOpaque

Equivalent Opaque Color for Transparent Color
PlotProbDist

Plot Probability Distribution
StrCap

Capitalize the First Letter of a String
StrVal

Extract All Numeric Values From a String
QuantileCI

Confidence Interval for Any Quantile
Quantile

(Weighted) Sample Quantiles
reorder.factor

Reorder the Levels of a Factor
Strata

Stratified Sampling
pRevGumbel

"Reverse" Gumbel Distribution Functions
Some

Return Some Randomly Chosen Elements of an Object
SendOutlookMail

Send a Mail Using Outlook as Mail Client
SmoothSpline

Formula Interface For smooth.spline
SetAlpha

Add an Alpha Channel To a Color
TOne

Create Table One Describing Baseline Characteristics
ToWrdPlot

Send a Plot to Word and Bookmark it
TMod

Comparison Table For Linear Models
Trim

Trim a Vector
VIF

Variance Inflation Factors
Rev

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

van der Waerden Test
StdCoef

Standardized Model Coefficients
Str

Compactly Display the Structure of any R Object
RomanToInt

Convert Roman Numerals to Integers
WrdMergeCells

Merges Cells Of a Defined Word Table Range
WrdPageBreak

Insert a Page Break
WrdSaveAs

Open and Save Word Documents
StrCountW

Count Words in a String
Depreciation

Several Methods of Depreciation of an Asset
SD

(Weighted) Standard Deviation
Rotate

Rotate a Geometric Structure
StrRev

Reverse a String
StrDist

Compute Distances Between Strings
VonNeumannTest

Von Neumann's Successive Difference Test
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
WrdParagraphFormat

Get or Set the Paragraph Format in Word
YuenTTest

Yuen t-Test For Trimmed Means
WrdPlot

Insert Active Plot to Word
Vigenere

Vigenere Cypher
Measures of Shape

Skewness and Kurtosis
SignTest

Sign Test
SplitPath

Split Path In Drive, Path, Filename
SplitAt

Split a Vector Into Several Pieces at Given Positions
WrdStyle

Get or Set the Style in Word
StrPad

Pad a String With Justification
d.pizza

Data pizza
d.periodic

Periodic Table of Elements
lines.lm

Add a Linear Regression Line
ZTest

Z Test for Known Population Standard Deviation
lines.loess

Add a Loess or a Spline Smoother
wdConst

Word VBA Constants
StrPos

Find Position of First Occurrence Of a String
StrTrunc

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

Remove Leading/Trailing Whitespace From A String
TitleRect

Plot Boxed Annotation
ToLong, ToWide

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

Send Objects to Word
VarCI

Confidence Intervals for the Variance
ToWrdB

Send Objects to Word and Bookmark Them
WrdCaption

Insert Caption to Word
Var

Variance
WrdCellRange

Return the Cell Range Of a Word Table
WrdTableBorders

Draw Borders to a Word Table
WrdTable

Insert a Table in a Word Document
d.countries

ISO 3166-1 Country Codes
d.diamonds

Data diamonds
%c%

Concatenates Two Strings Without Any Separator
rSum21

Random Numbers Adding Up to 1
split.formula

Formula Interface for Split
power.chisq.test

Power Calculations for ChiSquared Tests