Learn R Programming

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

79,502

Version

0.99.52

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

December 1st, 2023

Functions in DescTools (0.99.52)

Arrow

Insert an Arrow Into a Plot
BhapkarTest

Bhapkar Marginal Homogeneity Test
Assocs

Association Measures
BinomCIn

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

Atkinson Index - A Measure of Inequality.
BinTree

Binary Tree
BartelsRankTest

Bartels Rank Test of Randomness
BarnardTest

Barnard's Unconditional Test
BinomCI

Confidence Intervals for Binomial Proportions
Base Conversions

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

Confidence Interval for a Difference of Binomials
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
Canvas

Canvas for Geometric Plotting
CCC

Concordance Correlation Coefficient
Benford

Benford's Distribution
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BreuschGodfreyTest

Breusch-Godfrey Test
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
BrierScore

Brier Score for Assessing Prediction Accuracy
Asp

Get Aspect Ratio of the Current Plot
BootCI

Simple Bootstrap Confidence Intervals
BoxCox

Box Cox Transformation
Between, Outside

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

Background of a Plot
CoefVar

Coefficient of Variation
ColToHsv

R Color to HSV Conversion
CochranQTest

Cochran's Q test
ColToRgb

Color to RGB Conversion
Clockwise

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

Add a Legend to a Bubble Plot
Closest

Find the Closest Value
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
CatTable

Function to write a table
Coalesce

Return the First Element Not Being NA
CochranArmitageTest

Cochran-Armitage Test for Trend
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BoxedText

Add Text in a Box to a Plot
CohenD

Cohen's Effect Size
ColorLegend

Add a ColorLegend to a Plot
CollapseTable

Collapse Levels of a Table
CompleteColumns

Find Complete Columns
CohenKappa

Cohen's Kappa and Weighted Kappa
ConvUnit

Unit Conversion and Metrix Prefixes
ColumnWrap

Column Wrap
CorPart

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

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

Polychoric Correlation
ConDisPairs

Concordant and Discordant Pairs
ColToGrey

Convert Colors to Grey/Grayscale
Conf

Confusion Matrix And Associated Statistics
Cor

Covariance and Correlation (Matrices)
CutQ

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

Conover's Test of Multiple Comparisons
Contrasts

Pairwise Contrasts
Cstat

C Statistic (Area Under the ROC Curve)
ConnLines

Add Connection Lines to a Barplot
ColToHex

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

Count Complete Cases
Cross

Vector Cross Product
CountWorkDays

Count Work Days Between Two Dates
CrossN

n-dimensional Vector Cross Product
Datasets for Simulation

Datasets for Probabilistic Simulation
CourseData

Get HWZ Datasets
Date Functions

Basic Date Functions
DescToolsOptions

DescTools Options
DunnTest

Dunn's Test of Multiple Comparisons
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
Dot

Scalar Product
DunnettTest

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

Draw Elliptic Arc(s)
DoCall

Fast Alternative To The Internal do.call
Factorize

Prime Factorization of Integers
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
DoBy

Evaluates a Function Groupwise
CronbachAlpha

Cronbach's Coefficient Alpha
ExpFreq

Expected Frequencies
ExtrVal

Distributions of Maxima and Minima
Frac

Fractional Part and Maximal Digits of a Numeric Value
Frechet

The Frechet Distribution
FctArgs

Retrieve a Function's Arguments
FindCorr

Determine Highly Correlated Variables
FisherZ

Fisher-Transformation for Correlation to z-Score
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
EX

Expected Value and Variance
DivCoef

Rao's Diversity Coefficient
DurbinWatsonTest

Durbin-Watson Test
DigitSum

Calculate Digit Sum
GCD, LCM

Greatest Common Divisor and Least Common Multiple
GetNewWrd

Create a New Word Instance
FixToTable

Convert a Text to a Table
DrawRegPolygon

Draw Regular Polygon(s)
Dummy

Generate Dummy Codes for a Factor
DivCoefMax

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

Calculate Divisors
ErrBars

Add Error Bars to an Existing Plot
GTest

G-Test for Count Data
GoodmanKruskalTau

Goodman Kruskal's Tau
Format

Format Numbers and Dates
DegToRad

Convert Degrees to Radians and Vice Versa
DrawCircle

Draw a Circle
EtaSq

Effect Size Calculations for ANOVAs
Desc

Describe Data
Gumbel

The Gumbel Distribution
Gmean

Geometric Mean and Standard Deviation
GiniSimpson

Gini-Simpson Coefficient, Gini-Deltas coefficient and Hunter-Gaston Index
DrawBand

Draw Confidence Band
HoeffD

Matrix of Hoeffding's D Statistics
Fibonacci

Fibonacci Numbers
DrawEllipse

Draw an Ellipse
IsDate

Check If an Object Is of Type Date
GetCalls

Return All Used Functions Within a Function
GenRandGroups

Generate Random Groups
DrawBezier

Draw a Bezier Curve
GeomTrans

Geometric Transformations
GeomSn

Geometric Series
HuberM

Safe (generalized) Huber M-Estimator of Location
HotellingsT2Test

Hotelling's T2 Test
Entropy

Shannon Entropy and Mutual Information
IsDichotomous

Test If a Variable Contains Only Two Unique Values
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
Keywords

List Keywords For R Manual Pages
KendallW

Kendall's Coefficient of Concordance W
FindColor

Get Color on a Defined Color Range
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
LineToUser

Convert Line Coordinates To User Coordinates
LogSt

Started Logarithmic Transformation and Its Inverse
GetNewXL

Create a New Excel Instance
Freq

Frequency Table for a Single Variable
IsEuclid

Is a Distance Matrix Euclidean?
List Variety Of Objects

List Objects, Functions Or Data in a Package
Logit

Generalized Logit and Inverse Logit Function
Gini

Gini Coefficient
IsOdd

Checks If An Integer Is Even Or Odd
Extremes

Kth Smallest/Largest Values
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Gompertz

The Gompertz distribution
HmsToSec

Convert h:m:s To/From Seconds
HodgesLehmann

Hodges-Lehmann Estimator of Location
GoodmanKruskalGamma

Goodman Kruskal's Gamma
Lc

Lorenz Curve
ICC

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

The Generalized Extreme Value Distribution
MultinomCI

Confidence Intervals for Multinomial Proportions
GenPareto

The Generalized Pareto Distribution
Some numeric checks

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

The (weighted) Interquartile Range
JarqueBeraTest

(Robust) Jarque Bera Test
Herfindahl

Concentration Measures
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
NPV

Short Selection of Financial Mathematical Functions
InDots

Is a Specific Argument in the Dots-Arguments?
KendallTauA

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

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

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

Kappa for m Raters
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
ImputeKnn

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

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

Pearson Chi-Square Test for Normality
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Midx

Find the Midpoints of a Numeric Vector
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
MixColor

Compute the Convex Combination of Two Colors
Hmean

Harmonic Mean and Its Confidence Interval
LeveneTest

Levene's Test for Homogeneity of Variance
PercTable

Percentage Table
MoveAvg

Moving Average
IsPrime

IsPrime Property
PageTest

Exact Page Test for Ordered Alternatives
MultMerge

Merge Multiple Data Frames
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
IsValidHwnd

Check Windows Pointer
LinScale

Linear Scaling
PlotArea

Create an Area Plot
Measures of Accuracy

Measures of Accuracy
LOCF

Last Observation Carried Forward
MHChisqTest

Mantel-Haenszel Chi-Square Test
MedianCI

Confidence Interval for the Median
MeanAD

Mean Absolute Deviation From a Center Point
Mgsub

Multiple Gsub
PairApply

Pairwise Calculations
PlotBag

Bivariate Boxplot
Mar and Mgp

Set Plot Margins and Distances
Mean

(Weighted) Arithmetic Mean
LOF

Local Outlier Factor
MeanCI

Confidence Interval for the Mean
MeanCIn

Sample Size for a Given Width of a Confidence Interval for a Mean
Label, Unit

Label, Unit Attribute of an Object
PlotCashFlow

Cash Flow Plot
Mode

Mode, Most Frequent Value(s)
MeanDiffCI

Confidence Interval For Difference of Means
PlotBubble

Draw a Bubble Plot
MosesTest

Moses Test of Extreme Reactions
Lambda

Goodman Kruskal Lambda
Order

Distributions of Order Statistics
PlotCirc

Plot Circular Plot
PlotMosaic

Mosaic Plots
MAD

Median Absolute Deviation
Outlier

Outlier
Recode

Recode a Factor
MADCI

Confidence Intervals for Median Absolute Deviations
PlotACF

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

Plot Conditional Densities
ORToRelRisk

Transform Odds Ratio to Relative Risk
PlotPyramid

Draw a Back To Back Pyramid Plot
OddsRatio

Odds Ratio Estimation and Confidence Intervals
PlotCorr

Plot a Correlation Matrix
WrdFormatCells

Format Cells Of a Word Table
PlotCandlestick

Plot Candlestick Chart
ColToOpaque

Equivalent Opaque Color for Transparent Color
PDFManual

Get PDF Manual of a Package From CRAN
PlotMultiDens

Plot Multiple Density Curves
PMT

Periodic Payment of an Annuity.
Rotate

Rotate a Geometric Structure
Phrase

Phrasing Results of t-Test
TitleRect

Plot Boxed Annotation
MeanSE

Standard Error of Mean
ZTest

Z Test for Known Population Standard Deviation
PlotViolin

Plot Violins Instead of Boxplots
PlotWeb

Plot a Web of Connected Points
PlotECDF

Empirical Cumulative Distribution Function
Median

(Weighted) Median Value
DescTools Palettes

Some Custom Palettes
TOne

Create Table One Describing Baseline Characteristics
PlotMarDens

Scatterplot With Marginal Densities
NemenyiTest

Nemenyi Test
ParseSASDatalines

Parse a SAS Dataline Command
Measures of Shape

Skewness and Kurtosis
Nf

As Numeric Factor
PlotDot

Cleveland's Dot Plots
StrAlign

String Alignment
Recycle

Recyle a List of Elements
RelRisk

Relative Risk
ParseFormula

Parse a Formula and Create a Model Frame
PoissonCI

Poisson Confidence Interval
PasswordDlg

Password Dialog
RoundTo

Round to Multiple
PercentRank

Percent Ranks
VonNeumannTest

Von Neumann's Successive Difference Test
PlotFun

Plot a Function
RgbToCmy

Conversion Between RGB and CMYK
PlotTernary

Ternary or Triangular Plots
PlotQQ

QQ-Plot for Any Distribution
PlotLog

Logarithmic Plot
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
%like%

Like Operator
SetAlpha

Add an Alpha Channel To a Color
Primes

Find All Primes Less Than n
PlotMiss

Plot Missing Data
Triangular

The Triangular Distribution
Stamp

Date/Time/Directory Stamp the Current Plot
SplitAt

Split a Vector Into Several Pieces at Given Positions
Permn

Number and Samples for Permutations or Combinations of a Set
SampleTwins

Sample Twins
SmoothSpline

Formula Interface For smooth.spline
PostHocTest

Post-Hoc Tests
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
WrdFont

Get or Set the Font in Word
PlotVenn

Plot a Venn Diagram
PlotLinesA

Plot Lines
StdCoef

Standardized Model Coefficients
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
StrTrunc

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

Chernoff Faces
SpearmanRho

Spearman Rank Correlation
TheilU

Theil's U Index of Inequality
VarTest

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

Student's t-Test Based on Sample Statistics
WrdPlot

Insert Active Plot to Word
PlotTreemap

Create a Treemap
PlotFdist

Frequency Distribution Plot
SaveAs

Saves an R Object Under a Different Name
VecRot

Vector Rotation (Shift Elements)
Rank

Fast Sample Ranks
WithOptions

Execute Function with Temporary Options
TextToTable

Converts String To a Table
Rename

Change Names of a Named Object
StrTrim

Remove Leading/Trailing Whitespace From A String
RgbToCol

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

Produce a Shaded Curve
Untable

Recover Original Data From Contingency Table
Trim

Trim a Vector
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
day.name

Build-in Constants Extension
PlotPairs

Extended Scatterplot Matrices
Str

Compactly Display the Structure of any R Object
PlotProbDist

Plot Probability Distribution
RndPairs

Create Pairs of Correlated Random Numbers
ToLong, ToWide

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

Random Numbers Adding Up to 1
Depreciation

Several Methods of Depreciation of an Asset
SplitToDummy

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

Replace NAs by 0
pRevGumbel

"Reverse" Gumbel Distribution Functions
WrdParagraphFormat

Get or Set the Paragraph Format in Word
StrSplit

Split the Elements of a Character Vector
split.formula

Formula Interface for Split
PlotPolar

Plot Values on a Circular Grid
Sort

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

(Weighted) Standard Deviation
PseudoR2

Pseudo R2 Statistics
RevWeibull

The Reverse Weibull Distribution
RomanToInt

Convert Roman Numerals to Integers
StrPad

Pad a String With Justification
StrIsNumeric

Does a String Contain Only Numeric Data
RSessionAlive

How Long Has the RSession Been Running?
Range

(Robust) Range
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Some

Return Some Randomly Chosen Elements of an Object
XLGetRange

Import Data Directly From Excel
Sample

Random Samples and Permutations
%nin%

Find Matching (or Non-Matching) Elements
reorder.factor

Reorder the Levels of a Factor
XLDateToPOSIXct

Convert Excel Dates to POSIXct
RunsTest

Runs Test for Randomness
StrChop

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

Choose Textcolor Depending on Background Color
PolarGrid

Plot a Grid in Polar Coordinates
SomersDelta

Somers' Delta
Quot

Lagged Quotients
SendOutlookMail

Send a Mail Using Outlook as Mail Client
ToWrdB

Send Objects to Word and Bookmark Them
PtInPoly

Point in Polygon
RevCode

Reverse Codes
Quantile

(Weighted) Sample Quantiles
XLSaveAs

Save Excel File
QuantileCI

Confidence Interval for Any Quantile
StripAttr

Remove Attributes from an Object
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
WrdSaveAs

Open and Save Word Documents
RobScale

Robust Scaling With Median and Mad
StrCountW

Count Words in a String
StrAbbr

String Abbreviation
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
SplitToCol

Split Data Frame String Column Into Multiple Columns
WrdMergeCells

Merges Cells Of a Defined Word Table Range
ToWrdPlot

Send a Plot to Word and Bookmark it
as.matrix.xtabs

Convert xtabs To matrix
XLView

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

Set the Names in an Object
SplitPath

Split Path In Drive, Path, Filename
d.countries

ISO 3166-1 Country Codes
identify.formula

Identify Points In a Plot Using a Formula
Unwhich

Inverse Which
StrVal

Extract All Numeric Values From a String
Vigenere

Vigenere Cypher
wdConst

Word VBA Constants
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
StuartTauC

Stuart \(\tau_{c}\)
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
Rev

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

Compute Distances Between Strings
StrExtract

Extract Part of a String
TMod

Comparison Table For Linear Models
WrdStyle

Get or Set the Style in Word
WrdCaption

Insert Caption to Word
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
WrdCellRange

Return the Cell Range Of a Word Table
StrPos

Find Position of First Occurrence Of a String
StrRev

Reverse a String
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
StrCap

Capitalize the First Letter of a String
SignTest

Sign Test
VIF

Variance Inflation Factors
ToWrd

Send Objects to Word
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
Strata

Stratified Sampling
DescTools Aliases

Some Aliases Set for Convenience
YuenTTest

Yuen t-Test For Trimmed Means
matpow

Matrix Power
Zodiac

Calculate the Zodiac of a Date
StrSpell

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

Describe a Variable by a Factor with Two Levels
d.diamonds

Data diamonds
VanWaerdenTest

van der Waerden Test
%c%

Concatenates Two Strings Without Any Separator
SysInfo

System Information
Var

Variance
d.whisky

Classification of Scotch Single Malts
UncertCoef

Uncertainty Coefficient
WrdTable

Insert a Table in a Word Document
VarCI

Confidence Intervals for the Variance
UnirootAll

Finds many (all) roots of one equation within an interval
power.chisq.test

Power Calculations for ChiSquared Tests
WrdPageBreak

Insert a Page Break
d.pizza

Data pizza
lines.lm

Add a Linear Regression Line
d.periodic

Periodic Table of Elements
lines.loess

Add a Loess or a Spline Smoother
WrdTableBorders

Draw Borders to a Word Table
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
Agree

Raw Simple And Extended Percentage Agreement
ABCCoords

Coordinates for "bottomright", etc.
Abstract

Display Compact Abstract of a Data Frame
BarText

Place Value Labels on a Barplot
AddMonths

Add a Month to a Date
Append

Append Elements to Objects
AUC

Area Under the Curve
AllDuplicated

Index Vector of All Values Involved in Ties
AllIdentical

Test Multiple Objects for Exact Equality
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AxisBreak

Place a Break Mark on an Axis
AddMonthsYM

Add a Month to a Date in YearMonth Format
Abind

Combine Multidimensional Arrays