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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

October 22nd, 2022

Functions in DescTools (0.99.47)

AddMonths

Add a Month to a Date
ABCCoords

Coordinates for "bottomright", etc.
AddMonthsYM

Add a Month to a Date in YearMonth Format
Agree

Raw Simple And Extended Percentage Agreement
AllDuplicated

Index Vector of All Values Involved in Ties
Abstract

Display Compact Abstract of a Data Frame
Abind

Combine Multidimensional Arrays
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AUC

Area Under the Curve
AllIdentical

Test Multiple Objects for Exact Equality
Atkinson

Atkinson Index - A Measure of Inequality.
Append

Append Elements to Objects
Assocs

Association Measures
BarText

Place Value Labels on a Barplot
Asp

Get Aspect Ratio of the Current Plot
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Arrow

Insert an Arrow Into a Plot
AxisBreak

Place a Break Mark on an Axis
BartelsRankTest

Bartels Rank Test of Randomness
BarnardTest

Barnard's Unconditional Test
Bg

Background of a Plot
BhapkarTest

Bhapkar Marginal Homogeneity Test
BinTree

Binary Tree
BinomCI

Confidence Intervals for Binomial Proportions
Between, Outside

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

Confidence Interval for a Difference of Binomials
BinomCIn

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

Confidence Intervals for the Ratio of Binomial Proportions
Benford

Benford's Distribution
Base Conversions

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

Breslow-Day Test for Homogeneity of the Odds Ratios
BreuschGodfreyTest

Breusch-Godfrey Test
BoxCox

Box Cox Transformation
BrierScore

Brier Score for Assessing Prediction Accuracy
BoxedText

Add Text in a Box to a Plot
BubbleLegend

Add a Legend to a Bubble Plot
Canvas

Canvas for Geometric Plotting
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
CCC

Concordance Correlation Coefficient
BootCI

Simple Bootstrap Confidence Intervals
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
CohenD

Cohen's Effect Size
Clockwise

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

Find the Closest Value
Coalesce

Return the First Element Not Being NA
CochranQTest

Cochran's Q test
CohenKappa

Cohen's Kappa and Weighted Kappa
CatTable

Function to write a table
CochranArmitageTest

Cochran-Armitage Test for Trend
CoefVar

Coefficient of Variation
ColToGrey

Convert Colors to Grey/Grayscale
CombPairs

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

Column Wrap
ColToHex

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

Collapse Levels of a Table
ConDisPairs

Concordant and Discordant Pairs
CompleteColumns

Find Complete Columns
ColorLegend

Add a ColorLegend to a Plot
CountWorkDays

Count Work Days Between Two Dates
CorPart

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

Pairwise Contrasts
ColToRgb

Color to RGB Conversion
CorPolychor

Polychoric Correlation
ColToHsv

R Color to HSV Conversion
CountCompCases

Count Complete Cases
ConnLines

Add Connection Lines to a Barplot
ConoverTest

Conover's Test of Multiple Comparisons
ConvUnit

Unit Conversion and Metrix Prefixes
Conf

Confusion Matrix And Associated Statistics
Cor

Covariance and Correlation (Matrices)
Cstat

C Statistic (Area Under the ROC Curve)
CramerVonMisesTest

Cramer-von Mises Test for Normality
CrossN

n-dimensional Vector Cross Product
Association measures

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

Vector Cross Product
CronbachAlpha

Cronbach's Coefficient Alpha
Date Functions

Basic Date Functions
Datasets for Simulation

Datasets for Probabilistic Simulation
CutQ

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

Get HWZ Datasets
DigitSum

Calculate Digit Sum
DescToolsOptions

DescTools Options
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DivCoefMax

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

Calculate Divisors
DegToRad

Convert Degrees to Radians and Vice Versa
DivCoef

Rao's Diversity Coefficient
DoCall

Fast Alternative To The Internal do.call
DrawArc

Draw Elliptic Arc(s)
DoBy

Evaluates a Function Groupwise
DrawCircle

Draw a Circle
DrawEllipse

Draw an Ellipse
Desc

Describe Data
Dot

Scalar Product
DunnTest

Dunn's Test of Multiple Comparisons
DrawRegPolygon

Draw Regular Polygon(s)
DurbinWatsonTest

Durbin-Watson Test
DunnettTest

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

Shannon Entropy and Mutual Information
Dummy

Generate Dummy Codes for a Factor
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
DrawBand

Draw Confidence Band
ErrBars

Add Error Bars to an Existing Plot
DrawBezier

Draw a Bezier Curve
ExpFreq

Expected Frequencies
Frechet

The Frechet Distribution
EtaSq

Effect Size Calculations for ANOVAs
ExtrVal

Distributions of Maxima and Minima
FctArgs

Retrieve a Function's Arguments
GetCalls

Return All Used Functions Within a Function
Factorize

Prime Factorization of Integers
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
FisherZ

Fisher-Transformation for Correlation to z-Score
FindCorr

Determine Highly Correlated Variables
FindColor

Get Color on a Defined Color Range
GenRandGroups

Generate Random Groups
Fibonacci

Fibonacci Numbers
GenPareto

The Generalized Pareto Distribution
FixToTable

Convert a Text to a Table
HexToCol

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

The Generalized Extreme Value Distribution
GTest

G-Test for Count Data
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
Gini

Gini Coefficient
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
Freq

Frequency Table for a Single Variable
GetNewXL

Create a New Excel Instance
GetNewWrd

Create a New Word Instance
GoodmanKruskalGamma

Goodman Kruskal's Gamma
GoodmanKruskalTau

Goodman Kruskal's Tau
Gmean

Geometric Mean and Standard Deviation
HexToRgb

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

The Gompertz distribution
HotellingsT2Test

Hotelling's T2 Test
ICC

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

Check Windows Pointer
HuberM

Safe (generalized) Huber M-Estimator of Location
Some numeric checks

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

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

Is a Specific Argument in the Dots-Arguments?
IsDate

Check If an Object Is of Type Date
GeomSn

Geometric Series
Frac

Fractional Part and Maximal Digits of a Numeric Value
Format

Format Numbers and Dates
Keywords

List Keywords For R Manual Pages
ImputeKnn

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

Hodges-Lehmann Estimator of Location
IsDichotomous

Test If a Variable Contains Only Two Unique Values
Gumbel

The Gumbel Distribution
HoeffD

Matrix of Hoeffding's D Statistics
IsEuclid

Is a Distance Matrix Euclidean?
Herfindahl

Concentration Measures
JarqueBeraTest

(Robust) Jarque Bera Test
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
KendallW

Kendall's Coefficient of Concordance W
KappaM

Kappa for m Raters
KendallTauA

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

Goodman Kruskal Lambda
GeomTrans

Geometric Transformations
IQRw

The (weighted) Interquartile Range
Extremes

Kth Smallest/Largest Values
Hmean

Harmonic Mean and Its Confidence Interval
MeanCI

Confidence Interval for the Mean
Lc

Lorenz Curve
MeanCIn

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

Mantel-Haenszel Chi-Square Test
MoveAvg

Moving Average
LehmacherTest

Lehmacher's Test for Marginal Homogenity
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
HmsToSec

Convert h:m:s To/From Seconds
IsOdd

Checks If An Integer Is Even Or Odd
LinScale

Linear Scaling
LOCF

Last Observation Carried Forward
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
MultMerge

Merge Multiple Data Frames
Mar and Mgp

Set Plot Margins and Distances
Mode

Mode, Most Frequent Value(s)
List Variety Of Objects

List Objects, Functions Or Data in a Package
MAD

Median Absolute Deviation
LineToUser

Convert Line Coordinates To User Coordinates
Outlier

Outlier
PDFManual

Get PDF Manual of a Package From CRAN
MosesTest

Moses Test of Extreme Reactions
MADCI

Confidence Intervals for Median Absolute Deviations
NemenyiTest

Nemenyi Test
IsPrime

IsPrime Property
Measures of Accuracy

Measures of Accuracy
MeanSE

Standard Error of Mean
MeanDiffCI

Confidence Interval For Difference of Means
Label, Unit

Label, Unit Attribute of an Object
LOF

Local Outlier Factor
ORToRelRisk

Transform Odds Ratio to Relative Risk
PercTable

Percentage Table
PlotCandlestick

Plot Candlestick Chart
PlotCashFlow

Cash Flow Plot
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
LeveneTest

Levene's Test for Homogeneity of Variance
OddsRatio

Odds Ratio Estimation and Confidence Intervals
PercentRank

Percent Ranks
LogSt

Started Logarithmic Transformation and Its Inverse
Logit

Generalized Logit and Inverse Logit Function
Order

Distributions of Order Statistics
Mean

(Weighted) Arithmetic Mean
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotTernary

Ternary or Triangular Plots
PlotTreemap

Create a Treemap
MeanAD

Mean Absolute Deviation From a Center Point
Midx

Find the Midpoints of a Numeric Vector
MixColor

Compute the Convex Combination of Two Colors
Permn

Number and Samples for Permutations or Combinations of a Set
Phrase

Phrasing Results of t-Test
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PlotMosaic

Mosaic Plots
PasswordDlg

Password Dialog
PlotBag

Bivariate Boxplot
Primes

Find All Primes Less Than n
PearsonTest

Pearson Chi-Square Test for Normality
PlotLinesA

Plot Lines
PlotBubble

Draw a Bubble Plot
PlotACF

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

Create an Area Plot
PlotLog

Logarithmic Plot
PlotVenn

Plot a Venn Diagram
Median

(Weighted) Median Value
Recode

Recode a Factor
PMT

Periodic Payment of an Annuity.
Recycle

Recyle a List of Elements
MedianCI

Confidence Interval for the Median
RomanToInt

Convert Roman Numerals to Integers
Rotate

Rotate a Geometric Structure
PlotViolin

Plot Violins Instead of Boxplots
PageTest

Exact Page Test for Ordered Alternatives
MultinomCI

Confidence Intervals for Multinomial Proportions
PlotMarDens

Scatterplot With Marginal Densities
NPV

Short Selection of Financial Mathematical Functions
PlotMiss

Plot Missing Data
Range

(Robust) Range
PairApply

Pairwise Calculations
DescTools Palettes

Some Custom Palettes
Rank

Fast Sample Ranks
RunsTest

Runs Test for Randomness
RoundTo

Round to Multiple
ParseSASDatalines

Parse a SAS Dataline Command
ParseFormula

Parse a Formula and Create a Model Frame
StrPos

Find Position of First Occurrence Of a String
PlotCorr

Plot a Correlation Matrix
PseudoR2

Pseudo R2 Statistics
Unwhich

Inverse Which
RgbToCmy

Conversion Between RGB and CMYK
RgbToCol

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

Point in Polygon
SaveAs

Saves an R Object Under a Different Name
PlotDot

Cleveland's Dot Plots
PlotECDF

Empirical Cumulative Distribution Function
PlotPyramid

Draw a Back To Back Pyramid Plot
PlotQQ

QQ-Plot for Any Distribution
SignTest

Sign Test
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
SplitAt

Split a Vector Into Several Pieces at Given Positions
PlotFaces

Chernoff Faces
PlotCirc

Plot Circular Plot
PlotConDens

Plot Conditional Densities
reorder.factor

Reorder the Levels of a Factor
PlotMultiDens

Plot Multiple Density Curves
Rev

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

Plot a Grid in Polar Coordinates
PlotFdist

Frequency Distribution Plot
PlotFun

Plot a Function
PostHocTest

Post-Hoc Tests
SmoothSpline

Formula Interface For smooth.spline
PlotPairs

Extended Scatterplot Matrices
PlotPolar

Plot Values on a Circular Grid
Some

Return Some Randomly Chosen Elements of an Object
Untable

Recover Original Data From Contingency Table
PlotProbDist

Plot Probability Distribution
Sample

Random Samples and Permutations
Str

Compactly Display the Structure of any R Object
SampleTwins

Sample Twins
Quot

Lagged Quotients
RSessionAlive

How Long Has the RSession Been Running?
QuantileCI

Confidence Interval for Any Quantile
Quantile

(Weighted) Sample Quantiles
SplitPath

Split Path In Drive, Path, Filename
lines.loess

Add a Loess or a Spline Smoother
RelRisk

Relative Risk
Measures of Shape

Skewness and Kurtosis
WrdPageBreak

Insert a Page Break
StrRev

Reverse a String
Var

Variance
SysInfo

System Information
SomersDelta

Somers' Delta
Rename

Change Names of a Named Object
Sort

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

Plot a Web of Connected Points
VarCI

Confidence Intervals for the Variance
RndPairs

Create Pairs of Correlated Random Numbers
StdCoef

Standardized Model Coefficients
RobScale

Robust Scaling With Median and Mad
RevWeibull

The Reverse Weibull Distribution
ToWrdPlot

Send a Plot to Word and Bookmark it
VecRot

Vector Rotation (Shift Elements)
StrPad

Pad a String With Justification
StrTrim

Remove Leading/Trailing Whitespace From A String
ColToOpaque

Equivalent Opaque Color for Transparent Color
TextToTable

Converts String To a Table
UncertCoef

Uncertainty Coefficient
PoissonCI

Poisson Confidence Interval
RevCode

Reverse Codes
ZeroIfNA

Replace NAs by 0
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
SD

(Weighted) Standard Deviation
StrAlign

String Alignment
StrIsNumeric

Does a String Contain Only Numeric Data
Depreciation

Several Methods of Depreciation of an Asset
pRevGumbel

"Reverse" Gumbel Distribution Functions
SendOutlookMail

Send a Mail Using Outlook as Mail Client
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
wdConst

Word VBA Constants
SetAlpha

Add an Alpha Channel To a Color
SetNames

Set the Names in an Object
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
StrTrunc

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

Shapiro-Francia Test for Normality
StrExtract

Extract Part of a String
SpearmanRho

Spearman Rank Correlation
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
XLDateToPOSIXct

Convert Excel Dates to POSIXct
Shade

Produce a Shaded Curve
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
WrdMergeCells

Merges Cells Of a Defined Word Table Range
StrCap

Capitalize the First Letter of a String
StuartTauC

Stuart \(\tau_{c}\)
StrChop

Split a String into a Number of Sections of Defined Length
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
d.whisky

Classification of Scotch Single Malts
TMod

Comparison Table For Linear Models
XLGetRange

Import Data Directly From Excel
day.name

Build-in Constants Extension
lines.lm

Add a Linear Regression Line
VIF

Variance Inflation Factors
Stamp

Date/Time/Directory Stamp the Current Plot
Vigenere

Vigenere Cypher
as.matrix.xtabs

Convert xtabs To matrix
ToWrd

Send Objects to Word
SplitToCol

Split Data Frame String Column Into Multiple Columns
SplitToDummy

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

Theil's U Index of Inequality
XLSaveAs

Save Excel File
Trim

Trim a Vector
StrSplit

Split the Elements of a Character Vector
StrSpell

Spell a String Using the NATO Phonetic or the Morse Alphabet
%nin%

Find Matching (or Non-Matching) Elements
WrdCaption

Insert Caption to Word
StripAttr

Remove Attributes from an Object
StrAbbr

String Abbreviation
UnirootAll

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

Calculate Tukey's Biweight Robust Mean
d.periodic

Periodic Table of Elements
TTestA

Student's t-Test Based on Sample Statistics
TextContrastColor

Choose Textcolor Depending on Background Color
Strata

Stratified Sampling
StrVal

Extract All Numeric Values From a String
ToWrdB

Send Objects to Word and Bookmark Them
StrCountW

Count Words in a String
d.diamonds

Data diamonds
StrDist

Compute Distances Between Strings
TitleRect

Plot Boxed Annotation
DescTools Aliases

Some Aliases Set for Convenience
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
WrdParagraphFormat

Get or Set the Paragraph Format in Word
VanWaerdenTest

van der Waerden Test
XLView

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

Winsorize (Replace Extreme Values by Less Extreme Ones)
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
matpow

Matrix Power
WrdStyle

Get or Set the Style in Word
VarTest

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

Von Neumann's Successive Difference Test
WrdCellRange

Return the Cell Range Of a Word Table
WithOptions

Execute Function with Temporary Options
WrdPlot

Insert Active Plot to Word
ZTest

Z Test for Known Population Standard Deviation
YuenTTest

Yuen t-Test For Trimmed Means
TOne

Create Table One Describing Baseline Characteristics
WrdFont

Get or Set the Font in Word
ToLong, ToWide

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

Format Cells Of a Word Table
WrdTable

Insert a Table in a Word Document
WrdSaveAs

Open and Save Word Documents
TwoGroups

Describe a Variable by a Factor with Two Levels
power.chisq.test

Power Calculations for ChiSquared Tests
d.countries

ISO 3166-1 Country Codes
%c%

Concatenates Two Strings Without Any Separator
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
identify.formula

Identify Points In a Plot Using a Formula
WrdTableBorders

Draw Borders to a Word Table
Zodiac

Calculate the Zodiac of a Date
rSum21

Random Numbers Adding Up to 1
d.pizza

Data pizza
split.formula

Formula Interface for Split
%like%

Like Operator