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.49

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

May 17th, 2023

Functions in DescTools (0.99.49)

AddMonths

Add a Month to a Date
Abind

Combine Multidimensional Arrays
Agree

Raw Simple And Extended Percentage Agreement
AllDuplicated

Index Vector of All Values Involved in Ties
Assocs

Association Measures
Atkinson

Atkinson Index - A Measure of Inequality.
Abstract

Display Compact Abstract of a Data Frame
CCC

Concordance Correlation Coefficient
AxisBreak

Place a Break Mark on an Axis
Canvas

Canvas for Geometric Plotting
ABCCoords

Coordinates for "bottomright", etc.
AddMonthsYM

Add a Month to a Date in YearMonth Format
BinomCI

Confidence Intervals for Binomial Proportions
Clockwise

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

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

Area Under the Curve
AllIdentical

Test Multiple Objects for Exact Equality
Closest

Find the Closest Value
BarnardTest

Barnard's Unconditional Test
CollapseTable

Collapse Levels of a Table
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Asp

Get Aspect Ratio of the Current Plot
ColorLegend

Add a ColorLegend to a Plot
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
BartelsRankTest

Bartels Rank Test of Randomness
Append

Append Elements to Objects
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
DivCoefMax

Maximal value of Rao's diversity coefficient also called quadratic entropy
Between, Outside

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

Breusch-Godfrey Test
Coalesce

Return the First Element Not Being NA
BarText

Place Value Labels on a Barplot
BootCI

Simple Bootstrap Confidence Intervals
Bg

Background of a Plot
BinomDiffCI

Confidence Interval for a Difference of Binomials
CochranArmitageTest

Cochran-Armitage Test for Trend
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
Base Conversions

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

Benford's Distribution
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BrierScore

Brier Score for Assessing Prediction Accuracy
BoxedText

Add Text in a Box to a Plot
ColumnWrap

Column Wrap
BoxCox

Box Cox Transformation
CochranQTest

Cochran's Q test
BubbleLegend

Add a Legend to a Bubble Plot
CohenD

Cohen's Effect Size
CoefVar

Coefficient of Variation
CohenKappa

Cohen's Kappa and Weighted Kappa
CountCompCases

Count Complete Cases
Divisors

Calculate Divisors
CompleteColumns

Find Complete Columns
ConDisPairs

Concordant and Discordant Pairs
ColToGrey

Convert Colors to Grey/Grayscale
CorPart

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

Count Work Days Between Two Dates
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
ColToHex

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

C Statistic (Area Under the ROC Curve)
DunnTest

Dunn's Test of Multiple Comparisons
DunnettTest

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

Function to write a table
CorPolychor

Polychoric Correlation
ColToHsv

R Color to HSV Conversion
CombPairs

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

Conover's Test of Multiple Comparisons
ColToRgb

Color to RGB Conversion
Cross

Vector Cross Product
EtaSq

Effect Size Calculations for ANOVAs
ExpFreq

Expected Frequencies
Conf

Confusion Matrix And Associated Statistics
CutQ

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

Draw Regular Polygon(s)
ConnLines

Add Connection Lines to a Barplot
Dummy

Generate Dummy Codes for a Factor
Datasets for Simulation

Datasets for Probabilistic Simulation
CrossN

n-dimensional Vector Cross Product
Contrasts

Pairwise Contrasts
Date Functions

Basic Date Functions
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
ConvUnit

Unit Conversion and Metrix Prefixes
FisherZ

Fisher-Transformation for Correlation to z-Score
FixToTable

Convert a Text to a Table
GenPareto

The Generalized Pareto Distribution
DoBy

Evaluates a Function Groupwise
DoCall

Fast Alternative To The Internal do.call
ExtrVal

Distributions of Maxima and Minima
Cor

Covariance and Correlation (Matrices)
GenRandGroups

Generate Random Groups
DurbinWatsonTest

Durbin-Watson Test
CourseData

Get HWZ Datasets
Factorize

Prime Factorization of Integers
DescToolsOptions

DescTools Options
HexToCol

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

Shannon Entropy and Mutual Information
Gmean

Geometric Mean and Standard Deviation
Dot

Scalar Product
Association measures

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

Cramer-von Mises Test for Normality
CronbachAlpha

Cronbach's Coefficient Alpha
DrawArc

Draw Elliptic Arc(s)
FindColor

Get Color on a Defined Color Range
FindCorr

Determine Highly Correlated Variables
Gompertz

The Gompertz distribution
DegToRad

Convert Degrees to Radians and Vice Versa
IQRw

The (weighted) Interquartile Range
HexToRgb

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

Hodges-Lehmann Estimator of Location
Desc

Describe Data
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
HoeffD

Matrix of Hoeffding's D Statistics
DigitSum

Calculate Digit Sum
GetCalls

Return All Used Functions Within a Function
JarqueBeraTest

(Robust) Jarque Bera Test
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
GCD, LCM

Greatest Common Divisor and Least Common Multiple
DrawCircle

Draw a Circle
DivCoef

Rao's Diversity Coefficient
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
IsOdd

Checks If An Integer Is Even Or Odd
DrawEllipse

Draw an Ellipse
GTest

G-Test for Count Data
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
Gumbel

The Gumbel Distribution
Herfindahl

Concentration Measures
GenExtrVal

The Generalized Extreme Value Distribution
Gini

Gini Coefficient
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
IsPrime

IsPrime Property
DrawBand

Draw Confidence Band
FctArgs

Retrieve a Function's Arguments
KappaM

Kappa for m Raters
Fibonacci

Fibonacci Numbers
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
HuberM

Safe (generalized) Huber M-Estimator of Location
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
ICC

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

Hotelling's T2 Test
InDots

Is a Specific Argument in the Dots-Arguments?
IsDichotomous

Test If a Variable Contains Only Two Unique Values
LOCF

Last Observation Carried Forward
IsDate

Check If an Object Is of Type Date
IsEuclid

Is a Distance Matrix Euclidean?
KendallTauB

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

Kendall's Coefficient of Concordance W
Median

(Weighted) Median Value
LogSt

Started Logarithmic Transformation and Its Inverse
MedianCI

Confidence Interval for the Median
Lambda

Goodman Kruskal Lambda
DrawBezier

Draw a Bezier Curve
Extremes

Kth Smallest/Largest Values
Logit

Generalized Logit and Inverse Logit Function
KendallTauA

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

Greenhouse-Geisser And Huynh-Feldt Epsilons
Frechet

The Frechet Distribution
MeanCI

Confidence Interval for the Mean
Order

Distributions of Order Statistics
Outlier

Outlier
PearsonTest

Pearson Chi-Square Test for Normality
MADCI

Confidence Intervals for Median Absolute Deviations
Measures of Accuracy

Measures of Accuracy
Freq

Frequency Table for a Single Variable
GetNewWrd

Create a New Word Instance
GetNewXL

Create a New Excel Instance
MoveAvg

Moving Average
PercTable

Percentage Table
GoodmanKruskalGamma

Goodman Kruskal's Gamma
LeveneTest

Levene's Test for Homogeneity of Variance
MeanCIn

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

Lilliefors (Kolmogorov-Smirnov) Test for Normality
PlotCashFlow

Cash Flow Plot
PlotCirc

Plot Circular Plot
GoodmanKruskalTau

Goodman Kruskal's Tau
List Variety Of Objects

List Objects, Functions Or Data in a Package
PlotDot

Cleveland's Dot Plots
Midx

Find the Midpoints of a Numeric Vector
MixColor

Compute the Convex Combination of Two Colors
ErrBars

Add Error Bars to an Existing Plot
MAD

Median Absolute Deviation
MultMerge

Merge Multiple Data Frames
PlotECDF

Empirical Cumulative Distribution Function
Format

Format Numbers and Dates
Frac

Fractional Part and Maximal Digits of a Numeric Value
MultinomCI

Confidence Intervals for Multinomial Proportions
PoissonCI

Poisson Confidence Interval
NPV

Short Selection of Financial Mathematical Functions
PolarGrid

Plot a Grid in Polar Coordinates
Mode

Mode, Most Frequent Value(s)
ParseSASDatalines

Parse a SAS Dataline Command
GeomSn

Geometric Series
PasswordDlg

Password Dialog
Hmean

Harmonic Mean and Its Confidence Interval
PlotArea

Create an Area Plot
HmsToSec

Convert h:m:s To/From Seconds
MosesTest

Moses Test of Extreme Reactions
PDFManual

Get PDF Manual of a Package From CRAN
PMT

Periodic Payment of an Annuity.
PageTest

Exact Page Test for Ordered Alternatives
Recycle

Recyle a List of Elements
RelRisk

Relative Risk
DescTools Palettes

Some Custom Palettes
RobScale

Robust Scaling With Median and Mad
RomanToInt

Convert Roman Numerals to Integers
GeomTrans

Geometric Transformations
ParseFormula

Parse a Formula and Create a Model Frame
PairApply

Pairwise Calculations
PlotBubble

Draw a Bubble Plot
LOF

Local Outlier Factor
IsValidHwnd

Check Windows Pointer
Label, Unit

Label, Unit Attribute of an Object
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
SignTest

Sign Test
PlotCandlestick

Plot Candlestick Chart
Stamp

Date/Time/Directory Stamp the Current Plot
LinScale

Linear Scaling
StdCoef

Standardized Model Coefficients
StrChop

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

QQ-Plot for Any Distribution
StrCountW

Count Words in a String
LineToUser

Convert Line Coordinates To User Coordinates
Some numeric checks

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

Ternary or Triangular Plots
MHChisqTest

Mantel-Haenszel Chi-Square Test
Keywords

List Keywords For R Manual Pages
PtInPoly

Point in Polygon
PlotBag

Bivariate Boxplot
Quantile

(Weighted) Sample Quantiles
ImputeKnn

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

"Reverse" Gumbel Distribution Functions
PlotFaces

Chernoff Faces
PlotFdist

Frequency Distribution Plot
RevWeibull

The Reverse Weibull Distribution
Mar and Mgp

Set Plot Margins and Distances
RunsTest

Runs Test for Randomness
NemenyiTest

Nemenyi Test
SD

(Weighted) Standard Deviation
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
PlotPairs

Extended Scatterplot Matrices
StrSpell

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

As Numeric Factor
PlotMiss

Plot Missing Data
PlotPolar

Plot Values on a Circular Grid
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
Measures of Shape

Skewness and Kurtosis
PercentRank

Percent Ranks
Primes

Find All Primes Less Than n
PlotTreemap

Create a Treemap
SmoothSpline

Formula Interface For smooth.spline
Str

Compactly Display the Structure of any R Object
Permn

Number and Samples for Permutations or Combinations of a Set
PlotVenn

Plot a Venn Diagram
PseudoR2

Pseudo R2 Statistics
StrAbbr

String Abbreviation
PlotConDens

Plot Conditional Densities
Rename

Change Names of a Named Object
Lc

Lorenz Curve
TextContrastColor

Choose Textcolor Depending on Background Color
QuantileCI

Confidence Interval for Any Quantile
TextToTable

Converts String To a Table
Quot

Lagged Quotients
reorder.factor

Reorder the Levels of a Factor
PlotCorr

Plot a Correlation Matrix
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
ColToOpaque

Equivalent Opaque Color for Transparent Color
SendOutlookMail

Send a Mail Using Outlook as Mail Client
RgbToCmy

Conversion Between RGB and CMYK
PlotLog

Logarithmic Plot
SetAlpha

Add an Alpha Channel To a Color
LehmacherTest

Lehmacher's Test for Marginal Homogenity
SetNames

Set the Names in an Object
Rotate

Rotate a Geometric Structure
TOne

Create Table One Describing Baseline Characteristics
Mean

(Weighted) Arithmetic Mean
PlotMarDens

Scatterplot With Marginal Densities
MeanAD

Mean Absolute Deviation From a Center Point
MeanDiffCI

Confidence Interval For Difference of Means
RoundTo

Round to Multiple
SplitToDummy

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

Produce a Shaded Curve
PlotMosaic

Mosaic Plots
MeanSE

Standard Error of Mean
ShapiroFranciaTest

Shapiro-Francia Test for Normality
TTestA

Student's t-Test Based on Sample Statistics
ToWrdB

Send Objects to Word and Bookmark Them
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
ORToRelRisk

Transform Odds Ratio to Relative Risk
UnirootAll

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

Plot Multiple Density Curves
Untable

Recover Original Data From Contingency Table
WrdFormatCells

Format Cells Of a Word Table
SpearmanRho

Spearman Rank Correlation
StrSplit

Split the Elements of a Character Vector
OddsRatio

Odds Ratio Estimation and Confidence Intervals
WrdMergeCells

Merges Cells Of a Defined Word Table Range
PlotViolin

Plot Violins Instead of Boxplots
Phrase

Phrasing Results of t-Test
PlotWeb

Plot a Web of Connected Points
PlotACF

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

Send a Plot to Word and Bookmark it
d.diamonds

Data diamonds
StrTrim

Remove Leading/Trailing Whitespace From A String
VarCI

Confidence Intervals for the Variance
TheilU

Theil's U Index of Inequality
PlotFun

Plot a Function
TitleRect

Plot Boxed Annotation
d.periodic

Periodic Table of Elements
RSessionAlive

How Long Has the RSession Been Running?
VarTest

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

Return the Cell Range Of a Word Table
PlotLinesA

Plot Lines
WrdFont

Get or Set the Font in Word
SplitAt

Split a Vector Into Several Pieces at Given Positions
XLGetRange

Import Data Directly From Excel
Trim

Trim a Vector
StrDist

Compute Distances Between Strings
StrExtract

Extract Part of a String
PlotProbDist

Plot Probability Distribution
StrPos

Find Position of First Occurrence Of a String
StrRev

Reverse a String
PlotPyramid

Draw a Back To Back Pyramid Plot
XLSaveAs

Save Excel File
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
DescTools Aliases

Some Aliases Set for Convenience
Unwhich

Inverse Which
VIF

Variance Inflation Factors
Range

(Robust) Range
RgbToCol

Find the Nearest Named R-Color to a Given RGB-Color
%nin%

Find Matching (or Non-Matching) Elements
RndPairs

Create Pairs of Correlated Random Numbers
SysInfo

System Information
TMod

Comparison Table For Linear Models
Depreciation

Several Methods of Depreciation of an Asset
Sample

Random Samples and Permutations
WithOptions

Execute Function with Temporary Options
PostHocTest

Post-Hoc Tests
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
Some

Return Some Randomly Chosen Elements of an Object
SomersDelta

Somers' Delta
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
WrdStyle

Get or Set the Style in Word
Rank

Fast Sample Ranks
WrdTable

Insert a Table in a Word Document
Recode

Recode a Factor
TwoGroups

Describe a Variable by a Factor with Two Levels
Rev

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

Reverse Codes
Sort

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

Calculate the Zodiac of a Date
as.matrix.xtabs

Convert xtabs To matrix
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
SampleTwins

Sample Twins
StrIsNumeric

Does a String Contain Only Numeric Data
SaveAs

Saves an R Object Under a Different Name
SplitPath

Split Path In Drive, Path, Filename
StrPad

Pad a String With Justification
day.name

Build-in Constants Extension
StrTrunc

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

Split Data Frame String Column Into Multiple Columns
identify.formula

Identify Points In a Plot Using a Formula
StrVal

Extract All Numeric Values From a String
StrAlign

String Alignment
UncertCoef

Uncertainty Coefficient
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
StrCap

Capitalize the First Letter of a String
StuartTauC

Stuart \(\tau_{c}\)
Strata

Stratified Sampling
VonNeumannTest

Von Neumann's Successive Difference Test
StripAttr

Remove Attributes from an Object
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
XLView

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

van der Waerden Test
YuenTTest

Yuen t-Test For Trimmed Means
axTicks.POSIXct

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

ISO 3166-1 Country Codes
%overlaps%

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

Concatenates Two Strings Without Any Separator
ToLong, ToWide

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

Send Objects to Word
VecRot

Vector Rotation (Shift Elements)
Vigenere

Vigenere Cypher
Var

Variance
split.formula

Formula Interface for Split
WrdPageBreak

Insert a Page Break
wdConst

Word VBA Constants
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WrdCaption

Insert Caption to Word
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WrdTableBorders

Draw Borders to a Word Table
WrdPlot

Insert Active Plot to Word
WrdSaveAs

Open and Save Word Documents
d.pizza

Data pizza
d.whisky

Classification of Scotch Single Malts
%like%

Like Operator
XLDateToPOSIXct

Convert Excel Dates to POSIXct
ZTest

Z Test for Known Population Standard Deviation
lines.lm

Add a Linear Regression Line
ZeroIfNA

Replace NAs by 0
lines.loess

Add a Loess or a Spline Smoother
matpow

Matrix Power
power.chisq.test

Power Calculations for ChiSquared Tests
rSum21

Random Numbers Adding Up to 1