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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

April 10th, 2021

Functions in DescTools (0.99.41)

AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
Agree

Raw Simple And Extended Percentage Agreement
AUC

Area Under the Curve
AddMonths

Add a Month to a Date
Abstract

Display Compact Abstract of a Data Frame
AddMonthsYM

Add a Month to a Date in YearMonth Format
AllDuplicated

Index Vector of All Values Involved in Ties
Arrow

Insert an Arrow Into a Plot
Append

Append Elements to Objects
Abind

Combine Multidimensional Arrays
AllIdentical

Test Multiple Objects for Exact Equality
Asp

Get Aspect Ratio of the Current Plot
BinomCI

Confidence Intervals for Binomial Proportions
BinomCIn

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

Breusch-Godfrey Test
BarText

Place Value Labels on a Barplot
Benford

Benford's Distribution
BartelsRankTest

Bartels Rank Test of Randomness
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
AscToChar

Convert ASCII Codes to Characters and Vice Versa
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
Between, Outside

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

Cohen's Effect Size
CatTable

Function to write a table
Atkinson

Atkinson Index - A Measure of Inequality.
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
BinomDiffCI

Confidence Interval for a Difference of Binomials
AxisBreak

Place a Break Mark on an Axis
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BoxedText

Add Text in a Box to a Plot
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
BarnardTest

Barnard's Unconditional Test
BhapkarTest

Bhapkar Marginal Homogeneity Test
BinTree

Binary Tree
CoefVar

Coefficient of Variation
Cstat

C Statistic (Area Under the ROC Curve)
Desc

Describe Data
CutQ

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

Add a ColorLegend to a Plot
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
CollapseTable

Collapse Levels of a Table
Assocs

Association Measures
CCC

Concordance Correlation Coefficient
ConvUnit

Unit Conversion and Metrix Prefixes
Canvas

Canvas for Geometric Plotting
Base Conversions

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

Covariance and Correlation (Matrices)
BrierScore

Brier Score for Assessing Prediction Accuracy
Dummy

Generate Dummy Codes for a Factor
DunnTest

Dunn's Test of Multiple Comparisons
BootCI

Simple Bootstrap Confidence Intervals
Cross

Vector Cross Product
CompleteColumns

Find Complete Columns
DoCall

Fast Alternative To The Internal do.call
DurbinWatsonTest

Durbin-Watson Test
DunnettTest

Dunnett's Test for Comparing Several Treatments With a Control
Association measures

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

Concordant and Discordant Pairs
CourseData

Get HWZ Datasets
CohenKappa

Cohen's Kappa and Weighted Kappa
Dot

Scalar Product
BubbleLegend

Add a Legend to a Bubble Plot
CochranArmitageTest

Cochran-Armitage Test for Trend
FixToTable

Convert a Text to a Table
ColToGrey

Convert Colors to Grey/Grayscale
Coalesce

Return the First Element Not Being NA
Format

Format Numbers and Dates
GenExtrVal

The Generalized Extreme Value Distribution
GenPareto

The Generalized Pareto Distribution
ErrBars

Add Error Bars to an Existing Plot
BoxCox

Box Cox Transformation
ColToHex

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

Frequency Table for a Single Variable
GetCurrWrd

Get a Handle to a Running Word Instance
EtaSq

Effect Size Calculations for ANOVAs
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Fibonacci

Fibonacci Numbers
ColToHsv

R Color to HSV Conversion
DrawBand

Draw Confidence Band
CrossN

n-dimensional Vector Cross Product
DrawArc

Draw Elliptic Arc(s)
ColumnWrap

Column Wrap
Conf

Confusion Matrix And Associated Statistics
GetNewWrd

Create a New Word Instance
CombPairs

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

Goodman Kruskal's Tau
FindColor

Get Color on a Defined Color Range
FindCorr

Determine Highly Correlated Variables
GeomTrans

Geometric Transformations
Gompertz

The Gompertz distribution
CountCompCases

Count Complete Cases
FisherZ

Fisher-Transformation for Correlation to z-Score
ColToRgb

Color to RGB Conversion
CramerVonMisesTest

Cramer-von Mises Test for Normality
CronbachAlpha

Cronbach's Coefficient Alpha
CountWorkDays

Count Work Days Between Two Dates
GetCalls

Return All Used Functions Within a Function
GoodmanKruskalGamma

Goodman Kruskal's Gamma
Gumbel

The Gumbel Distribution
Some numeric checks

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

(Robust) Jarque Bera Test
DivCoef

Rao's Diversity Coefficient
DivCoefMax

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

Retrieve a Function's Arguments
DrawEllipse

Draw an Ellipse
Herfindahl

Concentration Measures
DrawRegPolygon

Draw Regular Polygon(s)
Factorize

Prime Factorization of Integers
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
IsDichotomous

Test If a Variable Contains Only Two Unique Values
InDots

Is a Specific Argument in the Dots-Arguments?
KendallTauA

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

Check If an Object Is of Type Date
MeanAD

Mean Absolute Deviation From a Center Point
CorPart

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

Kendall's Coefficient of Concordance W
MeanCI

Confidence Interval for the Mean
KendallTauB

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

Polychoric Correlation
ConoverTest

Conover's Test of Multiple Comparisons
ICC

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

Add Connection Lines to a Barplot
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
IsOdd

Checks If An Integer Is Even Or Odd
Extremes

Kth Smallest/Largest Values
IsEuclid

Is a Distance Matrix Euclidean?
IQRw

The (weighted) Interquartile Range
PDFManual

Get PDF Manual of a Package From CRAN
MosesTest

Moses Test of Extreme Reactions
MoveAvg

Moving Average
Datasets for Simulation

Datasets for Probabilistic Simulation
Hmean

Harmonic Mean and Its Confidence Interval
Date Functions

Basic Date Functions
DescToolsOptions

DescTools Options
Keywords

List Keywords For R Manual Pages
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
PMT

Periodic Payment of an Annuity.
Contrasts

Pairwise Contrasts
DegToRad

Convert Degrees to Radians and Vice Versa
HodgesLehmann

Hodges-Lehmann Estimator of Location
HmsToSec

Convert h:m:s To/From Seconds
LinScale

Linear Scaling
DigitSum

Calculate Digit Sum
MHChisqTest

Mantel-Haenszel Chi-Square Test
KappaM

Kappa for m Raters
Lc

Lorenz Curve
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
Label, Unit

Label, Unit Attribute of an Object
Measures of Accuracy

Measures of Accuracy
Median

(Weighted) Median Value
MultMerge

Merge Multiple Data Frames
DrawBezier

Draw a Bezier Curve
MeanSE

Standard Error of Mean
PlotCandlestick

Plot Candlestick Chart
MultinomCI

Confidence Intervals for Multinomial Proportions
PlotCashFlow

Cash Flow Plot
DrawCircle

Draw a Circle
List Variety Of Objects

List Objects, Functions Or Data in a Package
NPV

Short Selection of Financial Mathematical Functions
Logit

Generalized Logit and Inverse Logit Function
Lambda

Goodman Kruskal Lambda
Mar and Mgp

Set Plot Margins and Distances
PercentRank

Dense Ranks and Percent Ranks
DoBy

Evaluates a Function Groupwise
NemenyiTest

Nemenyi Test
Divisors

Calculate Divisors
Mean

(Weighted) Arithmetic Mean
Entropy

Shannon Entropy and Mutual Information
RoundTo

Round to Multiple
Frac

Fractional Part and Maximal Digits of a Numeric Value
PlotFun

Plot a Function
PlotFdist

Frequency Distribution Plot
ExpFreq

Expected Frequencies
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
ExtrVal

Distributions of Maxima and Minima
ParseSASDatalines

Parse a SAS Dataline Command
Rotate

Rotate a Geometric Structure
SendOutlookMail

Send a Mail Using Outlook as Mail Client
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Frechet

The Frechet Distribution
MixColor

Compute the Convex Combination of Two Colors
Mode

Mode, Most Frequent Value(s)
Measures of Shape

Skewness and Kurtosis
PasswordDlg

Password Dialog
PlotBag

Bivariate Boxplot
PearsonTest

Pearson Chi-Square Test for Normality
Permn

Number and Samples for Permutations or Combinations of a Set
ORToRelRisk

Transform Odds Ratio to Relative Risk
OddsRatio

Odds Ratio Estimation and Confidence Intervals
Phrase

Phrasing Results of t-Test
GenRandGroups

Generate Random Groups
PercTable

Percentage Table
PlotBubble

Draw a Bubble Plot
SmoothSpline

Formula Interface For smooth.spline
StrCap

Capitalize the First Letter of a String
PlotConDens

Plot Conditional Densities
PlotECDF

Empirical Cumulative Distribution Function
PlotMultiDens

Plot Multiple Density Curves
PlotCirc

Plot Circular Plot
GeomSn

Geometric Series
StrChop

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

Last Observation Carried Forward
HuberM

Safe (generalized) Huber M-Estimator of Location
HotellingsT2Test

Hotelling's T2 Test
StrExtract

Extract Part of a String
StrIsNumeric

Does a String Contain Only Numeric Data
TMod

Comparison Table For Linear Models
PtInPoly

Point in Polygon
PlotTernary

Ternary or Triangular Plots
Quantile

Weighted Quantiles
PlotPairs

Extended Scatterplot Matrices
GCD, LCM

Greatest Common Divisor and Least Common Multiple
PlotQQ

QQ-Plot for Any Distribution
PlotFaces

Chernoff Faces
PoissonCI

Poisson Confidence Interval
TOne

Create Table One Describing Baseline Characteristics
PlotMarDens

Scatterplot With Marginal Densities
GetNewXL

Create a New Excel Instance
GTest

G-Test for Count Data
LeveneTest

Levene's Test for Homogeneity of Variance
LOF

Local Outlier Factor
TextContrastColor

Choose Textcolor Depending on Background Color
LehmacherTest

Lehmacher's Test for Marginal Homogenity
TTestA

Student's t-Test Based on Sample Statistics
Untable

Recover Original Data From Contingency Table
Unwhich

Inverse Which
PlotMiss

Plot Missing Data
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
PlotViolin

Plot Violins Instead of Boxplots
RevCode

Reverse Codes
RgbToCmy

Conversion Between RGB and CMYK
Depreciation

Several Methods of Depreciation of an Asset
Rev

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

Confidence Interval for Any Quantile
ColToOpaque

Equivalent Opaque Color for Transparent Color
Rank

Fast Sample Ranks
MAD

Median Absolute Deviation
Recode

Recode a Factor
Quot

Lagged Quotients
PlotWeb

Plot a Web of Connected Points
RunsTest

Runs Test for Randomness
WithOptions

Execute Function with Temporary Options
Gini

Gini Coefficient
WrdSaveAs

Open and Save Word Documents
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
MADCI

Confidence Intervals for Median Absolute Deviations
Gmean

Geometric Mean and Standard Deviation
Some

Return Some Randomly Chosen Elements of an Object
HoeffD

Matrix of Hoeffding's D Statistics
Sample

Random Samples and Permutations
PolarGrid

Plot a Grid in Polar Coordinates
IsPrime

IsPrime Property
IsValidHwnd

Check Windows Pointer
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
ImputeKnn

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

(Weighted) Standard Deviation
SetAlpha

Add an Alpha Channel To a Color
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
SetNames

Set the Names in an Object
MeanCIn

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

Siegel-Tukey Test For Equality In Variability
LineToUser

Convert Line Coordinates To User Coordinates
Order

Distributions of Order Statistics
LogSt

Started Logarithmic Transformation and Its Inverse
SignTest

Sign Test
RSessionAlive

How Long Has the RSession Been Running?
SomersDelta

Somers' Delta
XLView

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

"Reverse" Gumbel Distribution Functions
Range

(Robust) Range
WrdStyle

Get or Set the Style in Word
RevWeibull

The Reverse Weibull Distribution
XLSaveAs

Save Excel File
RomanToInt

Convert Roman Numerals to Integers
RobScale

Robust Scaling With Median and Mad
SplitPath

Split Path In Drive, Path, Filename
SplitToCol

Split Data Frame String Column Into Multiple Columns
Outlier

Outlier
StrAbbr

String Abbreviation
StrPad

Pad a String With Justification
Strata

Stratified Sampling
StrAlign

String Alignment
StrVal

Extract All Numeric Values From a String
StrPos

Find Position of First Occurrence Of a String
PlotACF

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

Converts String To a Table
lines.lm

Add a Linear Regression Line
TheilU

Theil's U Index of Inequality
PlotArea

Create an Area Plot
StripAttr

Remove Attributes from an Object
lines.loess

Add a Loess or a Spline Smoother
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
VIF

Variance Inflation Factors
PlotCorr

Plot a Correlation Matrix
VanWaerdenTest

van der Waerden Test
%nin%

Find Matching (or Non-Matching) Elements
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
Midx

Find the Midpoints of a Numeric Vector
PageTest

Exact Page Test for Ordered Alternatives
MeanDiffCI

Confidence Interval For Difference of Means
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
MedianCI

Confidence Interval for the Median
PlotDot

Cleveland's Dot Plots
WrdTable

Insert a Table in a Word Document
WrdTableBorders

Draw Borders to a Word Table
SpearmanRho

Spearman Rank Correlation
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
d.countries

ISO 3166-1 Country Codes
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
XLGetRange

Import Data Directly From Excel
XLDateToPOSIXct

Convert Excel Dates to POSIXct
d.diamonds

Data diamonds
split.formula

Formula Interface for Split
PlotMosaic

Mosaic Plots
StrSpell

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

Split a Vector Into Several Pieces at Given Positions
StrSplit

Split the Elements of a Character Vector
ZeroIfNA

Replace NAs by 0
PlotLog

Logarithmic Plot
PairApply

Pairwise Calculations
DescTools Palettes

Some Custom Palettes
ParseFormula

Parse a Formula and Create a Model Frame
PlotLinesA

Plot Lines
PlotPyramid

Draw a Back To Back Pyramid Plot
wdConst

Word VBA Constants
PlotPolar

Plot Values on a Circular Grid
PseudoR2

Pseudo R2 Statistics
Primes

Find All Primes Less Than n
Zodiac

Calculate the Zodiac of a Date
DescTools Aliases

Some Aliases Set for Convenience
identify.formula

Identify Points In a Plot Using a Formula
%like%

Like Operator
matpow

Matrix Power
RelRisk

Relative Risk
PlotTreemap

Create a Treemap
RgbToCol

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

Send a Plot to Word and Bookmark it
Recycle

Recyle a List of Elements
RndPairs

Create Pairs of Correlated Random Numbers
PlotVenn

Plot a Venn Diagram
Shade

Produce a Shaded Curve
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Trim

Trim a Vector
Sort

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

Post-Hoc Tests
UnirootAll

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

Von Neumann's Successive Difference Test
UncertCoef

Uncertainty Coefficient
Vigenere

Vigenere Cypher
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
WrdFont

Get or Set the Font in Word
StdCoef

Standardized Model Coefficients
Str

Compactly Display the Structure of any R Object
StrRev

Reverse a String
SysInfo

System Information
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
Rename

Change Names of a Named Object
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
ToWrd

Send Objects to Word
StuartTauC

Stuart \(\tau_{c}\)
WrdFormatCells

Format Cells Of a Word Table
ToWrdB

Send Objects to Word and Bookmark Them
VarCI

Confidence Intervals for the Variance
Var

Variance
as.matrix.xtabs

Convert xtabs To matrix
reorder.factor

Reorder the Levels of a Factor
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
SampleTwins

Sample Twins
SaveAs

Saves an R Object Under a Different Name
Stamp

Date/Time/Directory Stamp the Current Plot
WrdCaption

Insert Caption to Word
StrCountW

Count Words in a String
StrDist

Compute Distances Between Strings
d.whisky

Classification of Scotch Single Malts
WrdCellRange

Return the Cell Range Of a Word Table
WrdPlot

Insert Active Plot to Word
WrdParagraphFormat

Get or Set the Paragraph Format in Word
ToLong, ToWide

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

Plot Boxed Annotation
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
StrTrunc

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

Remove Leading/Trailing Whitespace From A String
day.name

Build-in Constants Extension
VarTest

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

Vector Rotation (Shift Elements)
WrdMergeCells

Merges Cells Of a Defined Word Table Range
TwoGroups

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

Data pizza
power.chisq.test

Power Calculations for ChiSquared Tests
d.periodic

Periodic Table of Elements
YuenTTest

Yuen t-Test For Trimmed Means
WrdPageBreak

Insert a Page Break
ZTest

Z Test for Known Population Standard Deviation
%c%

Concatenates Two Strings Without Any Separator