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

97,236

Version

0.99.42

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

June 17th, 2021

Functions in DescTools (0.99.42)

AddMonths

Add a Month to a Date
ABCCoords

Coordinates for "bottomright", etc.
AUC

Area Under the Curve
Abstract

Display Compact Abstract of a Data Frame
AddMonthsYM

Add a Month to a Date in YearMonth Format
Agree

Raw Simple And Extended Percentage Agreement
Abind

Combine Multidimensional Arrays
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AllIdentical

Test Multiple Objects for Exact Equality
AllDuplicated

Index Vector of All Values Involved in Ties
Assocs

Association Measures
Atkinson

Atkinson Index - A Measure of Inequality.
Asp

Get Aspect Ratio of the Current Plot
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BarnardTest

Barnard's Unconditional Test
BartelsRankTest

Bartels Rank Test of Randomness
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
BinomDiffCI

Confidence Interval for a Difference of Binomials
BarText

Place Value Labels on a Barplot
AxisBreak

Place a Break Mark on an Axis
BhapkarTest

Bhapkar Marginal Homogeneity Test
Arrow

Insert an Arrow Into a Plot
Append

Append Elements to Objects
Base Conversions

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

Automatic Selection of Box Cox Transformation Parameter
Between, Outside

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

Breslow-Day Test for Homogeneity of the Odds Ratios
BreuschGodfreyTest

Breusch-Godfrey Test
Benford

Benford's Distribution
Clockwise

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

Add Text in a Box to a Plot
Closest

Find the Closest Value
CoefVar

Coefficient of Variation
CochranQTest

Cochran's Q test
BinomCIn

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

Concordance Correlation Coefficient
Canvas

Canvas for Geometric Plotting
BinomCI

Confidence Intervals for Binomial Proportions
CompleteColumns

Find Complete Columns
ColumnWrap

Column Wrap
CatTable

Function to write a table
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
BinTree

Binary Tree
CombPairs

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

Background of a Plot
CorPart

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

Polychoric Correlation
BubbleLegend

Add a Legend to a Bubble Plot
BrierScore

Brier Score for Assessing Prediction Accuracy
CohenD

Cohen's Effect Size
ColToHsv

R Color to HSV Conversion
CohenKappa

Cohen's Kappa and Weighted Kappa
Coalesce

Return the First Element Not Being NA
ColToHex

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

Box Cox Transformation
BootCI

Simple Bootstrap Confidence Intervals
ColToRgb

Color to RGB Conversion
CochranArmitageTest

Cochran-Armitage Test for Trend
ConoverTest

Conover's Test of Multiple Comparisons
Contrasts

Pairwise Contrasts
CronbachAlpha

Cronbach's Coefficient Alpha
CramerVonMisesTest

Cramer-von Mises Test for Normality
CollapseTable

Collapse Levels of a Table
Cstat

C Statistic (Area Under the ROC Curve)
ColToGrey

Convert Colors to Grey/Grayscale
ConvUnit

Unit Conversion and Metrix Prefixes
CutQ

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

Concordant and Discordant Pairs
Cor

Covariance and Correlation (Matrices)
Date Functions

Basic Date Functions
Datasets for Simulation

Datasets for Probabilistic Simulation
CountCompCases

Count Complete Cases
CourseData

Get HWZ Datasets
ColorLegend

Add a ColorLegend to a Plot
CountWorkDays

Count Work Days Between Two Dates
Association measures

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

Confusion Matrix And Associated Statistics
DivCoef

Rao's Diversity Coefficient
DigitSum

Calculate Digit Sum
DegToRad

Convert Degrees to Radians and Vice Versa
Desc

Describe Data
Cross

Vector Cross Product
DescToolsOptions

DescTools Options
DrawRegPolygon

Draw Regular Polygon(s)
CrossN

n-dimensional Vector Cross Product
ConnLines

Add Connection Lines to a Barplot
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DrawBezier

Draw a Bezier Curve
DivCoefMax

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

Draw Confidence Band
Divisors

Calculate Divisors
Dummy

Generate Dummy Codes for a Factor
DrawCircle

Draw a Circle
Fibonacci

Fibonacci Numbers
FctArgs

Retrieve a Function's Arguments
ExtrVal

Distributions of Maxima and Minima
DoCall

Fast Alternative To The Internal do.call
Frac

Fractional Part and Maximal Digits of a Numeric Value
DunnTest

Dunn's Test of Multiple Comparisons
DurbinWatsonTest

Durbin-Watson Test
DrawEllipse

Draw an Ellipse
DoBy

Evaluates a Function Groupwise
Format

Format Numbers and Dates
Factorize

Prime Factorization of Integers
DunnettTest

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

Shannon Entropy and Mutual Information
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
Dot

Scalar Product
FisherZ

Fisher-Transformation for Correlation to z-Score
GetNewXL

Create a New Excel Instance
GetNewWrd

Create a New Word Instance
FixToTable

Convert a Text to a Table
GetCalls

Return All Used Functions Within a Function
GetCurrWrd

Get a Handle to a Running Word Instance
GeomSn

Geometric Series
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Gumbel

The Gumbel Distribution
GeomTrans

Geometric Transformations
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
HexToCol

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

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

Goodman Kruskal's Gamma
Frechet

The Frechet Distribution
GoodmanKruskalTau

Goodman Kruskal's Tau
ExpFreq

Expected Frequencies
DrawArc

Draw Elliptic Arc(s)
EtaSq

Effect Size Calculations for ANOVAs
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
HotellingsT2Test

Hotelling's T2 Test
Herfindahl

Concentration Measures
FindColor

Get Color on a Defined Color Range
HuberM

Safe (generalized) Huber M-Estimator of Location
GTest

G-Test for Count Data
IsOdd

Checks If An Integer Is Even Or Odd
Some numeric checks

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

Hodges-Lehmann Estimator of Location
Freq

Frequency Table for a Single Variable
ErrBars

Add Error Bars to an Existing Plot
IsDichotomous

Test If a Variable Contains Only Two Unique Values
IsEuclid

Is a Distance Matrix Euclidean?
IsPrime

IsPrime Property
KendallTauB

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

Convert h:m:s To/From Seconds
LOF

Local Outlier Factor
Hmean

Harmonic Mean and Its Confidence Interval
KendallW

Kendall's Coefficient of Concordance W
ICC

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

Is a Specific Argument in the Dots-Arguments?
KappaM

Kappa for m Raters
IsDate

Check If an Object Is of Type Date
IsValidHwnd

Check Windows Pointer
GenPareto

The Generalized Pareto Distribution
LogSt

Started Logarithmic Transformation and Its Inverse
Lambda

Goodman Kruskal Lambda
Extremes

Kth Smallest/Largest Values
Label, Unit

Label, Unit Attribute of an Object
KendallTauA

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

Geometric Mean and Standard Deviation
GenRandGroups

Generate Random Groups
Gompertz

The Gompertz distribution
LeveneTest

Levene's Test for Homogeneity of Variance
Measures of Accuracy

Measures of Accuracy
Gini

Gini Coefficient
GenExtrVal

The Generalized Extreme Value Distribution
FindCorr

Determine Highly Correlated Variables
List Variety Of Objects

List Objects, Functions Or Data in a Package
Logit

Generalized Logit and Inverse Logit Function
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
JarqueBeraTest

(Robust) Jarque Bera Test
OddsRatio

Odds Ratio Estimation and Confidence Intervals
MAD

Median Absolute Deviation
MeanDiffCI

Confidence Interval For Difference of Means
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
IQRw

The (weighted) Interquartile Range
Mode

Mode, Most Frequent Value(s)
MosesTest

Moses Test of Extreme Reactions
Order

Distributions of Order Statistics
PairApply

Pairwise Calculations
MeanSE

Standard Error of Mean
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
DescTools Palettes

Some Custom Palettes
ImputeKnn

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

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

Outlier
Lc

Lorenz Curve
PlotArea

Create an Area Plot
PlotBubble

Draw a Bubble Plot
LineToUser

Convert Line Coordinates To User Coordinates
LOCF

Last Observation Carried Forward
MHChisqTest

Mantel-Haenszel Chi-Square Test
Mar and Mgp

Set Plot Margins and Distances
LinScale

Linear Scaling
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Midx

Find the Midpoints of a Numeric Vector
ORToRelRisk

Transform Odds Ratio to Relative Risk
HoeffD

Matrix of Hoeffding's D Statistics
PlotECDF

Empirical Cumulative Distribution Function
MultinomCI

Confidence Intervals for Multinomial Proportions
Permn

Number and Samples for Permutations or Combinations of a Set
Phrase

Phrasing Results of t-Test
PlotFdist

Frequency Distribution Plot
PDFManual

Get PDF Manual of a Package From CRAN
PlotTreemap

Create a Treemap
PlotFun

Plot a Function
PlotVenn

Plot a Venn Diagram
PageTest

Exact Page Test for Ordered Alternatives
Mean

(Weighted) Arithmetic Mean
Keywords

List Keywords For R Manual Pages
PercentRank

Percent Ranks
PlotMarDens

Scatterplot With Marginal Densities
PlotMiss

Plot Missing Data
PlotBag

Bivariate Boxplot
Rename

Change Names of a Named Object
MeanAD

Mean Absolute Deviation From a Center Point
MedianCI

Confidence Interval for the Median
PlotWeb

Plot a Web of Connected Points
PlotViolin

Plot Violins Instead of Boxplots
Median

(Weighted) Median Value
MeanCIn

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

Post-Hoc Tests
PoissonCI

Poisson Confidence Interval
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
MixColor

Compute the Convex Combination of Two Colors
MeanCI

Confidence Interval for the Mean
PlotPolar

Plot Values on a Circular Grid
MultMerge

Merge Multiple Data Frames
reorder.factor

Reorder the Levels of a Factor
PearsonTest

Pearson Chi-Square Test for Normality
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
MADCI

Confidence Intervals for Median Absolute Deviations
MoveAvg

Moving Average
PasswordDlg

Password Dialog
RgbToCmy

Conversion Between RGB and CMYK
RunsTest

Runs Test for Randomness
NPV

Short Selection of Financial Mathematical Functions
PlotCashFlow

Cash Flow Plot
ColToOpaque

Equivalent Opaque Color for Transparent Color
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PMT

Periodic Payment of an Annuity.
PlotMultiDens

Plot Multiple Density Curves
PlotLinesA

Plot Lines
PlotFaces

Chernoff Faces
PseudoR2

Pseudo R2 Statistics
RevWeibull

The Reverse Weibull Distribution
PlotPairs

Extended Scatterplot Matrices
PlotConDens

Plot Conditional Densities
NemenyiTest

Nemenyi Test
PlotCandlestick

Plot Candlestick Chart
PercTable

Percentage Table
Primes

Find All Primes Less Than n
Quot

Lagged Quotients
ParseFormula

Parse a Formula and Create a Model Frame
ParseSASDatalines

Parse a SAS Dataline Command
PolarGrid

Plot a Grid in Polar Coordinates
PlotCorr

Plot a Correlation Matrix
RobScale

Robust Scaling With Median and Mad
Shade

Produce a Shaded Curve
PlotMosaic

Mosaic Plots
Sample

Random Samples and Permutations
SplitPath

Split Path In Drive, Path, Filename
Recycle

Recyle a List of Elements
SD

(Weighted) Standard Deviation
StrPos

Find Position of First Occurrence Of a String
RelRisk

Relative Risk
Str

Compactly Display the Structure of any R Object
SampleTwins

Sample Twins
StrAbbr

String Abbreviation
SplitToCol

Split Data Frame String Column Into Multiple Columns
RomanToInt

Convert Roman Numerals to Integers
Depreciation

Several Methods of Depreciation of an Asset
QuantileCI

Confidence Interval for Any Quantile
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Rev

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

Rotate a Geometric Structure
RevCode

Reverse Codes
pRevGumbel

"Reverse" Gumbel Distribution Functions
Some

Return Some Randomly Chosen Elements of an Object
PlotDot

Cleveland's Dot Plots
PlotQQ

QQ-Plot for Any Distribution
PlotTernary

Ternary or Triangular Plots
SpearmanRho

Spearman Rank Correlation
VonNeumannTest

Von Neumann's Successive Difference Test
RgbToCol

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

Split a Vector Into Several Pieces at Given Positions
StrDist

Compute Distances Between Strings
PlotLog

Logarithmic Plot
SetAlpha

Add an Alpha Channel To a Color
Sort

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

Count Words in a String
StrTrim

Remove Leading/Trailing Whitespace From A String
SetNames

Set the Names in an Object
StrAlign

String Alignment
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
RSessionAlive

How Long Has the RSession Been Running?
TMod

Comparison Table For Linear Models
WrdParagraphFormat

Get or Set the Paragraph Format in Word
SomersDelta

Somers' Delta
SendOutlookMail

Send a Mail Using Outlook as Mail Client
Range

(Robust) Range
RndPairs

Create Pairs of Correlated Random Numbers
StrChop

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

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

Extract Part of a String
StrCap

Capitalize the First Letter of a String
Strata

Stratified Sampling
PlotCirc

Plot Circular Plot
WrdCaption

Insert Caption to Word
SmoothSpline

Formula Interface For smooth.spline
ToWrd

Send Objects to Word
StrTrunc

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

Execute Function with Temporary Options
Unwhich

Inverse Which
Untable

Recover Original Data From Contingency Table
Var

Variance
wdConst

Word VBA Constants
ToWrdB

Send Objects to Word and Bookmark Them
StrSpell

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

Return the Cell Range Of a Word Table
TheilU

Theil's U Index of Inequality
StrIsNumeric

Does a String Contain Only Numeric Data
StrSplit

Split the Elements of a Character Vector
VarCI

Confidence Intervals for the Variance
StdCoef

Standardized Model Coefficients
d.periodic

Periodic Table of Elements
WrdSaveAs

Open and Save Word Documents
XLSaveAs

Save Excel File
WrdStyle

Get or Set the Style in Word
day.name

Build-in Constants Extension
TextToTable

Converts String To a Table
SaveAs

Saves an R Object Under a Different Name
Zodiac

Calculate the Zodiac of a Date
ToWrdPlot

Send a Plot to Word and Bookmark it
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Vigenere

Vigenere Cypher
%c%

Concatenates Two Strings Without Any Separator
Measures of Shape

Skewness and Kurtosis
lines.lm

Add a Linear Regression Line
PtInPoly

Point in Polygon
PlotPyramid

Draw a Back To Back Pyramid Plot
split.formula

Formula Interface for Split
Trim

Trim a Vector
StrRev

Reverse a String
Rank

Fast Sample Ranks
d.pizza

Data pizza
TextContrastColor

Choose Textcolor Depending on Background Color
VarTest

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

Yuen t-Test For Trimmed Means
d.whisky

Classification of Scotch Single Malts
VIF

Variance Inflation Factors
ZeroIfNA

Replace NAs by 0
VecRot

Vector Rotation (Shift Elements)
TTestA

Student's t-Test Based on Sample Statistics
WrdFont

Get or Set the Font in Word
StrVal

Extract All Numeric Values From a String
VanWaerdenTest

van der Waerden Test
ZTest

Z Test for Known Population Standard Deviation
as.matrix.xtabs

Convert xtabs To matrix
StripAttr

Remove Attributes from an Object
StrPad

Pad a String With Justification
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
TOne

Create Table One Describing Baseline Characteristics
WrdPlot

Insert Active Plot to Word
UncertCoef

Uncertainty Coefficient
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
UnirootAll

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

Some Functions to Handle MS-Word Bookmarks
power.chisq.test

Power Calculations for ChiSquared Tests
StuartTauC

Stuart \(\tau_{c}\)
TitleRect

Plot Boxed Annotation
Quantile

Weighted Quantiles
DescTools Aliases

Some Aliases Set for Convenience
Recode

Recode a Factor
d.diamonds

Data diamonds
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
matpow

Matrix Power
XLDateToPOSIXct

Convert Excel Dates to POSIXct
WrdFormatCells

Format Cells Of a Word Table
d.countries

ISO 3166-1 Country Codes
RoundTo

Round to Multiple
WrdMergeCells

Merges Cells Of a Defined Word Table Range
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
SignTest

Sign Test
Stamp

Date/Time/Directory Stamp the Current Plot
XLGetRange

Import Data Directly From Excel
lines.loess

Add a Loess or a Spline Smoother
WrdTable

Insert a Table in a Word Document
SysInfo

System Information
ToLong, ToWide

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

Draw Borders to a Word Table
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
WrdPageBreak

Insert a Page Break
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
%nin%

Find Matching (or Non-Matching) Elements
TwoGroups

Describe a Variable by a Factor with Two Levels
identify.formula

Identify Points In a Plot Using a Formula
%like%

Like Operator