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

94,600

Version

0.99.48

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

February 19th, 2023

Functions in DescTools (0.99.48)

AllIdentical

Test Multiple Objects for Exact Equality
AllDuplicated

Index Vector of All Values Involved in Ties
AddMonths

Add a Month to a Date
Abstract

Display Compact Abstract of a Data Frame
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BartelsRankTest

Bartels Rank Test of Randomness
BarText

Place Value Labels on a Barplot
Assocs

Association Measures
BarnardTest

Barnard's Unconditional Test
Arrow

Insert an Arrow Into a Plot
Atkinson

Atkinson Index - A Measure of Inequality.
Asp

Get Aspect Ratio of the Current Plot
Append

Append Elements to Objects
AxisBreak

Place a Break Mark on an Axis
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
BinomCI

Confidence Intervals for Binomial Proportions
BinTree

Binary Tree
Bg

Background of a Plot
Between, Outside

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

Confidence Interval for a Difference of Binomials
BhapkarTest

Bhapkar Marginal Homogeneity Test
BinomCIn

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

Benford's Distribution
Base Conversions

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

Automatic Selection of Box Cox Transformation Parameter
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
BoxCox

Box Cox Transformation
CCC

Concordance Correlation Coefficient
BrierScore

Brier Score for Assessing Prediction Accuracy
BoxedText

Add Text in a Box to a Plot
BootCI

Simple Bootstrap Confidence Intervals
Canvas

Canvas for Geometric Plotting
BubbleLegend

Add a Legend to a Bubble Plot
BreuschGodfreyTest

Breusch-Godfrey Test
CohenD

Cohen's Effect Size
Coalesce

Return the First Element Not Being NA
CochranQTest

Cochran's Q test
Closest

Find the Closest Value
Clockwise

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

Coefficient of Variation
CohenKappa

Cohen's Kappa and Weighted Kappa
ColToHsv

R Color to HSV Conversion
ColToRgb

Color to RGB Conversion
CollapseTable

Collapse Levels of a Table
ColorLegend

Add a ColorLegend to a Plot
CatTable

Function to write a table
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
ConDisPairs

Concordant and Discordant Pairs
CompleteColumns

Find Complete Columns
ColumnWrap

Column Wrap
CorPart

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

Add Connection Lines to a Barplot
ColToHex

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

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

Count Complete Cases
ConvUnit

Unit Conversion and Metrix Prefixes
ColToGrey

Convert Colors to Grey/Grayscale
Conf

Confusion Matrix And Associated Statistics
Datasets for Simulation

Datasets for Probabilistic Simulation
CorPolychor

Polychoric Correlation
CramerVonMisesTest

Cramer-von Mises Test for Normality
CountWorkDays

Count Work Days Between Two Dates
CochranArmitageTest

Cochran-Armitage Test for Trend
CourseData

Get HWZ Datasets
CronbachAlpha

Cronbach's Coefficient Alpha
Cross

Vector Cross Product
ConoverTest

Conover's Test of Multiple Comparisons
Date Functions

Basic Date Functions
Cor

Covariance and Correlation (Matrices)
Association measures

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

C Statistic (Area Under the ROC Curve)
Contrasts

Pairwise Contrasts
CutQ

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

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

n-dimensional Vector Cross Product
DescToolsOptions

DescTools Options
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DivCoef

Rao's Diversity Coefficient
DigitSum

Calculate Digit Sum
DoBy

Evaluates a Function Groupwise
DoCall

Fast Alternative To The Internal do.call
Divisors

Calculate Divisors
DunnettTest

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

Dunn's Test of Multiple Comparisons
DrawBand

Draw Confidence Band
DrawBezier

Draw a Bezier Curve
DrawEllipse

Draw an Ellipse
DrawCircle

Draw a Circle
DurbinWatsonTest

Durbin-Watson Test
Entropy

Shannon Entropy and Mutual Information
DrawRegPolygon

Draw Regular Polygon(s)
Dummy

Generate Dummy Codes for a Factor
ErrBars

Add Error Bars to an Existing Plot
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
FctArgs

Retrieve a Function's Arguments
DegToRad

Convert Degrees to Radians and Vice Versa
Fibonacci

Fibonacci Numbers
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
GCD, LCM

Greatest Common Divisor and Least Common Multiple
FixToTable

Convert a Text to a Table
FisherZ

Fisher-Transformation for Correlation to z-Score
GetNewXL

Create a New Excel Instance
Factorize

Prime Factorization of Integers
GetNewWrd

Create a New Word Instance
Dot

Scalar Product
GetCalls

Return All Used Functions Within a Function
Desc

Describe Data
Frechet

The Frechet Distribution
ExtrVal

Distributions of Maxima and Minima
Freq

Frequency Table for a Single Variable
DrawArc

Draw Elliptic Arc(s)
HexToCol

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

Get a Handle to a Running Word/Excel Instance
GeomSn

Geometric Series
GoodmanKruskalGamma

Goodman Kruskal's Gamma
ExpFreq

Expected Frequencies
HexToRgb

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

Effect Size Calculations for ANOVAs
GoodmanKruskalTau

Goodman Kruskal's Tau
GeomTrans

Geometric Transformations
Gompertz

The Gompertz distribution
HotellingsT2Test

Hotelling's T2 Test
Gmean

Geometric Mean and Standard Deviation
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
IQRw

The (weighted) Interquartile Range
HodgesLehmann

Hodges-Lehmann Estimator of Location
IsPrime

IsPrime Property
IsOdd

Checks If An Integer Is Even Or Odd
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
Keywords

List Keywords For R Manual Pages
ImputeKnn

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

Format Numbers and Dates
IsValidHwnd

Check Windows Pointer
IsDichotomous

Test If a Variable Contains Only Two Unique Values
LOF

Local Outlier Factor
HoeffD

Matrix of Hoeffding's D Statistics
Label, Unit

Label, Unit Attribute of an Object
Frac

Fractional Part and Maximal Digits of a Numeric Value
KendallTauB

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

Krippendorff's Alpha Reliability Coefficient
IsEuclid

Is a Distance Matrix Euclidean?
Some numeric checks

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

G-Test for Count Data
GenExtrVal

The Generalized Extreme Value Distribution
LeveneTest

Levene's Test for Homogeneity of Variance
FindColor

Get Color on a Defined Color Range
LOCF

Last Observation Carried Forward
KendallW

Kendall's Coefficient of Concordance W
Hmean

Harmonic Mean and Its Confidence Interval
FindCorr

Determine Highly Correlated Variables
Gumbel

The Gumbel Distribution
GenRandGroups

Generate Random Groups
Herfindahl

Concentration Measures
GenPareto

The Generalized Pareto Distribution
Lc

Lorenz Curve
Gini

Gini Coefficient
Lambda

Goodman Kruskal Lambda
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
Mean

(Weighted) Arithmetic Mean
HuberM

Safe (generalized) Huber M-Estimator of Location
ICC

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

Convert h:m:s To/From Seconds
MeanAD

Mean Absolute Deviation From a Center Point
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
LogSt

Started Logarithmic Transformation and Its Inverse
JarqueBeraTest

(Robust) Jarque Bera Test
KappaM

Kappa for m Raters
Logit

Generalized Logit and Inverse Logit Function
KendallTauA

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

Is a Specific Argument in the Dots-Arguments?
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
MoveAvg

Moving Average
MADCI

Confidence Intervals for Median Absolute Deviations
MultMerge

Merge Multiple Data Frames
Extremes

Kth Smallest/Largest Values
LehmacherTest

Lehmacher's Test for Marginal Homogenity
IsDate

Check If an Object Is of Type Date
Measures of Accuracy

Measures of Accuracy
LinScale

Linear Scaling
MeanCI

Confidence Interval for the Mean
Outlier

Outlier
Order

Distributions of Order Statistics
LineToUser

Convert Line Coordinates To User Coordinates
MeanCIn

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

Transform Odds Ratio to Relative Risk
MosesTest

Moses Test of Extreme Reactions
Mode

Mode, Most Frequent Value(s)
Midx

Find the Midpoints of a Numeric Vector
OddsRatio

Odds Ratio Estimation and Confidence Intervals
List Variety Of Objects

List Objects, Functions Or Data in a Package
PairApply

Pairwise Calculations
PageTest

Exact Page Test for Ordered Alternatives
MAD

Median Absolute Deviation
DescTools Palettes

Some Custom Palettes
MixColor

Compute the Convex Combination of Two Colors
MHChisqTest

Mantel-Haenszel Chi-Square Test
PDFManual

Get PDF Manual of a Package From CRAN
Mar and Mgp

Set Plot Margins and Distances
PercTable

Percentage Table
PlotConDens

Plot Conditional Densities
PearsonTest

Pearson Chi-Square Test for Normality
PMT

Periodic Payment of an Annuity.
PlotCorr

Plot a Correlation Matrix
NemenyiTest

Nemenyi Test
PlotECDF

Empirical Cumulative Distribution Function
PlotDot

Cleveland's Dot Plots
Nf

As Numeric Factor
MedianCI

Confidence Interval for the Median
PercentRank

Percent Ranks
NPV

Short Selection of Financial Mathematical Functions
MultinomCI

Confidence Intervals for Multinomial Proportions
PlotCashFlow

Cash Flow Plot
Median

(Weighted) Median Value
PlotCandlestick

Plot Candlestick Chart
PlotFun

Plot a Function
PlotLinesA

Plot Lines
PlotBubble

Draw a Bubble Plot
Permn

Number and Samples for Permutations or Combinations of a Set
ParseFormula

Parse a Formula and Create a Model Frame
PlotQQ

QQ-Plot for Any Distribution
PlotLog

Logarithmic Plot
PlotPairs

Extended Scatterplot Matrices
PlotCirc

Plot Circular Plot
ParseSASDatalines

Parse a SAS Dataline Command
PlotMarDens

Scatterplot With Marginal Densities
PasswordDlg

Password Dialog
PlotBag

Bivariate Boxplot
PlotTreemap

Create a Treemap
MeanDiffCI

Confidence Interval For Difference of Means
PlotVenn

Plot a Venn Diagram
PlotArea

Create an Area Plot
PlotMultiDens

Plot Multiple Density Curves
PlotFdist

Frequency Distribution Plot
PlotFaces

Chernoff Faces
PlotMosaic

Mosaic Plots
MeanSE

Standard Error of Mean
Phrase

Phrasing Results of t-Test
PlotACF

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

Confidence Interval for Any Quantile
PlotTernary

Ternary or Triangular Plots
Quot

Lagged Quotients
PlotMiss

Plot Missing Data
PtInPoly

Point in Polygon
Quantile

(Weighted) Sample Quantiles
PlotPyramid

Draw a Back To Back Pyramid Plot
PlotProbDist

Plot Probability Distribution
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotPolar

Plot Values on a Circular Grid
PlotViolin

Plot Violins Instead of Boxplots
Recycle

Recyle a List of Elements
RSessionAlive

How Long Has the RSession Been Running?
PostHocTest

Post-Hoc Tests
Range

(Robust) Range
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PlotWeb

Plot a Web of Connected Points
RgbToCol

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

Poisson Confidence Interval
Rename

Change Names of a Named Object
RelRisk

Relative Risk
Primes

Find All Primes Less Than n
PseudoR2

Pseudo R2 Statistics
RobScale

Robust Scaling With Median and Mad
pRevGumbel

"Reverse" Gumbel Distribution Functions
RomanToInt

Convert Roman Numerals to Integers
PolarGrid

Plot a Grid in Polar Coordinates
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Rev

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

Fast Sample Ranks
SendOutlookMail

Send a Mail Using Outlook as Mail Client
Recode

Recode a Factor
reorder.factor

Reorder the Levels of a Factor
ColToOpaque

Equivalent Opaque Color for Transparent Color
RndPairs

Create Pairs of Correlated Random Numbers
RevWeibull

The Reverse Weibull Distribution
Measures of Shape

Skewness and Kurtosis
RevCode

Reverse Codes
Depreciation

Several Methods of Depreciation of an Asset
RgbToCmy

Conversion Between RGB and CMYK
Sample

Random Samples and Permutations
RunsTest

Runs Test for Randomness
SD

(Weighted) Standard Deviation
SmoothSpline

Formula Interface For smooth.spline
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
SpearmanRho

Spearman Rank Correlation
SignTest

Sign Test
SplitPath

Split Path In Drive, Path, Filename
SetNames

Set the Names in an Object
SetAlpha

Add an Alpha Channel To a Color
Sort

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

Sort Strings with Embedded Numbers Based on Their Numeric Order
SampleTwins

Sample Twins
SaveAs

Saves an R Object Under a Different Name
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrPad

Pad a String With Justification
StrIsNumeric

Does a String Contain Only Numeric Data
RoundTo

Round to Multiple
Rotate

Rotate a Geometric Structure
TextContrastColor

Choose Textcolor Depending on Background Color
StrPos

Find Position of First Occurrence Of a String
Str

Compactly Display the Structure of any R Object
SplitToCol

Split Data Frame String Column Into Multiple Columns
Shade

Produce a Shaded Curve
StrAbbr

String Abbreviation
Some

Return Some Randomly Chosen Elements of an Object
SysInfo

System Information
StripAttr

Remove Attributes from an Object
Strata

Stratified Sampling
TextToTable

Converts String To a Table
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
StrRev

Reverse a String
ShapiroFranciaTest

Shapiro-Francia Test for Normality
StrAlign

String Alignment
StuartTauC

Stuart \(\tau_{c}\)
StrCap

Capitalize the First Letter of a String
SplitToDummy

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

Spread Out a Vector of Numbers To a Minimum Interval
StrChop

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

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

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

Send Objects to Word
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
TMod

Comparison Table For Linear Models
StrCountW

Count Words in a String
SomersDelta

Somers' Delta
StrSpell

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

Uncertainty Coefficient
VonNeumannTest

Von Neumann's Successive Difference Test
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Trim

Trim a Vector
TheilU

Theil's U Index of Inequality
WrdParagraphFormat

Get or Set the Paragraph Format in Word
TitleRect

Plot Boxed Annotation
Stamp

Date/Time/Directory Stamp the Current Plot
UnirootAll

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

Recover Original Data From Contingency Table
StdCoef

Standardized Model Coefficients
StrDist

Compute Distances Between Strings
StrSplit

Split the Elements of a Character Vector
StrTrim

Remove Leading/Trailing Whitespace From A String
StrExtract

Extract Part of a String
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
WrdMergeCells

Merges Cells Of a Defined Word Table Range
VanWaerdenTest

van der Waerden Test
day.name

Build-in Constants Extension
VecRot

Vector Rotation (Shift Elements)
Vigenere

Vigenere Cypher
ToWrdPlot

Send a Plot to Word and Bookmark it
ToWrdB

Send Objects to Word and Bookmark Them
VIF

Variance Inflation Factors
Unwhich

Inverse Which
XLGetRange

Import Data Directly From Excel
StrTrunc

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

Format Cells Of a Word Table
StrVal

Extract All Numeric Values From a String
TTestA

Student's t-Test Based on Sample Statistics
TOne

Create Table One Describing Baseline Characteristics
Var

Variance
VarCI

Confidence Intervals for the Variance
WrdCellRange

Return the Cell Range Of a Word Table
d.pizza

Data pizza
split.formula

Formula Interface for Split
WrdFont

Get or Set the Font in Word
%nin%

Find Matching (or Non-Matching) Elements
XLSaveAs

Save Excel File
WithOptions

Execute Function with Temporary Options
VarTest

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

Use MS-Excel as Viewer for a Data.Frame
WrdStyle

Get or Set the Style in Word
rSum21

Random Numbers Adding Up to 1
d.whisky

Classification of Scotch Single Malts
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
WrdPageBreak

Insert a Page Break
YuenTTest

Yuen t-Test For Trimmed Means
ZTest

Z Test for Known Population Standard Deviation
power.chisq.test

Power Calculations for ChiSquared Tests
WrdTable

Insert a Table in a Word Document
wdConst

Word VBA Constants
identify.formula

Identify Points In a Plot Using a Formula
WrdCaption

Insert Caption to Word
Zodiac

Calculate the Zodiac of a Date
WrdTableBorders

Draw Borders to a Word Table
DescTools Aliases

Some Aliases Set for Convenience
ZeroIfNA

Replace NAs by 0
%c%

Concatenates Two Strings Without Any Separator
as.matrix.xtabs

Convert xtabs To matrix
WrdPlot

Insert Active Plot to Word
XLDateToPOSIXct

Convert Excel Dates to POSIXct
WrdSaveAs

Open and Save Word Documents
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
%like%

Like Operator
d.countries

ISO 3166-1 Country Codes
lines.loess

Add a Loess or a Spline Smoother
d.diamonds

Data diamonds
d.periodic

Periodic Table of Elements
matpow

Matrix Power
lines.lm

Add a Linear Regression Line
ABCCoords

Coordinates for "bottomright", etc.
Agree

Raw Simple And Extended Percentage Agreement
AUC

Area Under the Curve
AddMonthsYM

Add a Month to a Date in YearMonth Format
Abind

Combine Multidimensional Arrays