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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

September 9th, 2021

Functions in DescTools (0.99.43)

Abind

Combine Multidimensional Arrays
ABCCoords

Coordinates for "bottomright", etc.
Agree

Raw Simple And Extended Percentage Agreement
AddMonthsYM

Add a Month to a Date in YearMonth Format
Abstract

Display Compact Abstract of a Data Frame
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AllDuplicated

Index Vector of All Values Involved in Ties
AddMonths

Add a Month to a Date
AUC

Area Under the Curve
AllIdentical

Test Multiple Objects for Exact Equality
Append

Append Elements to Objects
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BarText

Place Value Labels on a Barplot
AxisBreak

Place a Break Mark on an Axis
BarnardTest

Barnard's Unconditional Test
BartelsRankTest

Bartels Rank Test of Randomness
Atkinson

Atkinson Index - A Measure of Inequality.
Assocs

Association Measures
Bg

Background of a Plot
Asp

Get Aspect Ratio of the Current Plot
BhapkarTest

Bhapkar Marginal Homogeneity Test
BinTree

Binary Tree
Benford

Benford's Distribution
Between, Outside

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

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

Confidence Intervals for the Ratio of Binomial Proportions
BinomDiffCI

Confidence Interval for a Difference of Binomials
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BoxedText

Add Text in a Box to a Plot
BinomCIn

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

Insert an Arrow Into a Plot
Canvas

Canvas for Geometric Plotting
BrierScore

Brier Score for Assessing Prediction Accuracy
BubbleLegend

Add a Legend to a Bubble Plot
BinomCI

Confidence Intervals for Binomial Proportions
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
BootCI

Simple Bootstrap Confidence Intervals
CatTable

Function to write a table
CCC

Concordance Correlation Coefficient
BoxCox

Box Cox Transformation
ColumnWrap

Column Wrap
CombPairs

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

Cohen's Effect Size
ColToGrey

Convert Colors to Grey/Grayscale
ColToHex

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

Cohen's Kappa and Weighted Kappa
CochranQTest

Cochran's Q test
Clockwise

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

Find the Closest Value
CountCompCases

Count Complete Cases
CountWorkDays

Count Work Days Between Two Dates
BreuschGodfreyTest

Breusch-Godfrey Test
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
CoefVar

Coefficient of Variation
CollapseTable

Collapse Levels of a Table
CochranArmitageTest

Cochran-Armitage Test for Trend
ConvUnit

Unit Conversion and Metrix Prefixes
Cor

Covariance and Correlation (Matrices)
ColorLegend

Add a ColorLegend to a Plot
CompleteColumns

Find Complete Columns
Coalesce

Return the First Element Not Being NA
ConDisPairs

Concordant and Discordant Pairs
Conf

Confusion Matrix And Associated Statistics
ConnLines

Add Connection Lines to a Barplot
ColToRgb

Color to RGB Conversion
ColToHsv

R Color to HSV Conversion
CramerVonMisesTest

Cramer-von Mises Test for Normality
CorPart

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

Polychoric Correlation
Cstat

C Statistic (Area Under the ROC Curve)
CutQ

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

Cronbach's Coefficient Alpha
Date Functions

Basic Date Functions
Datasets for Simulation

Datasets for Probabilistic Simulation
Cross

Vector Cross Product
CrossN

n-dimensional Vector Cross Product
Desc

Describe Data
DegToRad

Convert Degrees to Radians and Vice Versa
Contrasts

Pairwise Contrasts
ConoverTest

Conover's Test of Multiple Comparisons
DivCoefMax

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

Calculate Divisors
DescToolsOptions

DescTools Options
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DoBy

Evaluates a Function Groupwise
DoCall

Fast Alternative To The Internal do.call
Dot

Scalar Product
DrawArc

Draw Elliptic Arc(s)
CourseData

Get HWZ Datasets
DivCoef

Rao's Diversity Coefficient
DrawBand

Draw Confidence Band
DunnTest

Dunn's Test of Multiple Comparisons
Association measures

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

Calculate Digit Sum
EtaSq

Effect Size Calculations for ANOVAs
DunnettTest

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

Draw a Circle
DrawEllipse

Draw an Ellipse
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
FixToTable

Convert a Text to a Table
ErrBars

Add Error Bars to an Existing Plot
FisherZ

Fisher-Transformation for Correlation to z-Score
DurbinWatsonTest

Durbin-Watson Test
Entropy

Shannon Entropy and Mutual Information
GenExtrVal

The Generalized Extreme Value Distribution
GTest

G-Test for Count Data
GetCalls

Return All Used Functions Within a Function
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
Fibonacci

Fibonacci Numbers
FctArgs

Retrieve a Function's Arguments
FindColor

Get Color on a Defined Color Range
Gini

Gini Coefficient
DrawBezier

Draw a Bezier Curve
GenPareto

The Generalized Pareto Distribution
FindCorr

Determine Highly Correlated Variables
GenRandGroups

Generate Random Groups
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
GoodmanKruskalGamma

Goodman Kruskal's Gamma
Frac

Fractional Part and Maximal Digits of a Numeric Value
DrawRegPolygon

Draw Regular Polygon(s)
Gmean

Geometric Mean and Standard Deviation
Format

Format Numbers and Dates
HodgesLehmann

Hodges-Lehmann Estimator of Location
GoodmanKruskalTau

Goodman Kruskal's Tau
IsPrime

IsPrime Property
HoeffD

Matrix of Hoeffding's D Statistics
IsOdd

Checks If An Integer Is Even Or Odd
Dummy

Generate Dummy Codes for a Factor
ExtrVal

Distributions of Maxima and Minima
GetNewXL

Create a New Excel Instance
ExpFreq

Expected Frequencies
GetNewWrd

Create a New Word Instance
Herfindahl

Concentration Measures
Gumbel

The Gumbel Distribution
Factorize

Prime Factorization of Integers
InDots

Is a Specific Argument in the Dots-Arguments?
HmsToSec

Convert h:m:s To/From Seconds
Gompertz

The Gompertz distribution
Hmean

Harmonic Mean and Its Confidence Interval
IsValidHwnd

Check Windows Pointer
Some numeric checks

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

Hosmer-Lemeshow Goodness of Fit Tests
HotellingsT2Test

Hotelling's T2 Test
KappaM

Kappa for m Raters
Keywords

List Keywords For R Manual Pages
KendallTauA

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

Identify Points in Plot Lying Within a Rectangle or Polygon
Lc

Lorenz Curve
GeomSn

Geometric Series
JarqueBeraTest

(Robust) Jarque Bera Test
Freq

Frequency Table for a Single Variable
IQRw

The (weighted) Interquartile Range
LogSt

Started Logarithmic Transformation and Its Inverse
MeanCI

Confidence Interval for the Mean
Frechet

The Frechet Distribution
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Lambda

Goodman Kruskal Lambda
ImputeKnn

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

Check If an Object Is of Type Date
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
LOCF

Last Observation Carried Forward
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
List Variety Of Objects

List Objects, Functions Or Data in a Package
Extremes

Kth Smallest/Largest Values
MAD

Median Absolute Deviation
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
LeveneTest

Levene's Test for Homogeneity of Variance
MHChisqTest

Mantel-Haenszel Chi-Square Test
KendallTauB

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

Exact Page Test for Ordered Alternatives
PMT

Periodic Payment of an Annuity.
HexToRgb

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

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

Geometric Transformations
HuberM

Safe (generalized) Huber M-Estimator of Location
Logit

Generalized Logit and Inverse Logit Function
MultinomCI

Confidence Intervals for Multinomial Proportions
Midx

Find the Midpoints of a Numeric Vector
MADCI

Confidence Intervals for Median Absolute Deviations
MixColor

Compute the Convex Combination of Two Colors
KendallW

Kendall's Coefficient of Concordance W
NPV

Short Selection of Financial Mathematical Functions
MeanCIn

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

(Weighted) Median Value
MedianCI

Confidence Interval for the Median
MeanDiffCI

Confidence Interval For Difference of Means
PearsonTest

Pearson Chi-Square Test for Normality
PasswordDlg

Password Dialog
MeanSE

Standard Error of Mean
Mar and Mgp

Set Plot Margins and Distances
PlotDot

Cleveland's Dot Plots
PlotCorr

Plot a Correlation Matrix
PlotCirc

Plot Circular Plot
PercentRank

Percent Ranks
PlotACF

Combined Plot of a Time Series and Its ACF and PACF
Measures of Accuracy

Measures of Accuracy
PlotArea

Create an Area Plot
PercTable

Percentage Table
MoveAvg

Moving Average
IsDichotomous

Test If a Variable Contains Only Two Unique Values
ICC

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

Plot Conditional Densities
PlotFaces

Chernoff Faces
PlotECDF

Empirical Cumulative Distribution Function
PlotMiss

Plot Missing Data
PlotMarDens

Scatterplot With Marginal Densities
ParseSASDatalines

Parse a SAS Dataline Command
ParseFormula

Parse a Formula and Create a Model Frame
NemenyiTest

Nemenyi Test
MultMerge

Merge Multiple Data Frames
PlotCashFlow

Cash Flow Plot
ORToRelRisk

Transform Odds Ratio to Relative Risk
PlotLinesA

Plot Lines
PlotCandlestick

Plot Candlestick Chart
LOF

Local Outlier Factor
IsEuclid

Is a Distance Matrix Euclidean?
Permn

Number and Samples for Permutations or Combinations of a Set
Order

Distributions of Order Statistics
OddsRatio

Odds Ratio Estimation and Confidence Intervals
PlotLog

Logarithmic Plot
Label, Unit

Label, Unit Attribute of an Object
MeanAD

Mean Absolute Deviation From a Center Point
LineToUser

Convert Line Coordinates To User Coordinates
LinScale

Linear Scaling
Mean

(Weighted) Arithmetic Mean
PlotMultiDens

Plot Multiple Density Curves
PlotPolar

Plot Values on a Circular Grid
PlotPairs

Extended Scatterplot Matrices
PlotViolin

Plot Violins Instead of Boxplots
PlotWeb

Plot a Web of Connected Points
PlotMosaic

Mosaic Plots
PlotTernary

Ternary or Triangular Plots
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotQQ

QQ-Plot for Any Distribution
Phrase

Phrasing Results of t-Test
PostHocTest

Post-Hoc Tests
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PtInPoly

Point in Polygon
PoissonCI

Poisson Confidence Interval
Quantile

Weighted Quantiles
PolarGrid

Plot a Grid in Polar Coordinates
Mode

Mode, Most Frequent Value(s)
PlotPyramid

Draw a Back To Back Pyramid Plot
MosesTest

Moses Test of Extreme Reactions
Primes

Find All Primes Less Than n
RSessionAlive

How Long Has the RSession Been Running?
Range

(Robust) Range
Rank

Fast Sample Ranks
Recode

Recode a Factor
PDFManual

Get PDF Manual of a Package From CRAN
DescTools Palettes

Some Custom Palettes
Outlier

Outlier
PairApply

Pairwise Calculations
QuantileCI

Confidence Interval for Any Quantile
PlotBag

Bivariate Boxplot
RelRisk

Relative Risk
Recycle

Recyle a List of Elements
PseudoR2

Pseudo R2 Statistics
RgbToCol

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

Create Pairs of Correlated Random Numbers
Quot

Lagged Quotients
RevCode

Reverse Codes
RoundTo

Round to Multiple
Rotate

Rotate a Geometric Structure
Rev

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

Conversion Between RGB and CMYK
ColToOpaque

Equivalent Opaque Color for Transparent Color
SaveAs

Saves an R Object Under a Different Name
SampleTwins

Sample Twins
pRevGumbel

"Reverse" Gumbel Distribution Functions
SD

(Weighted) Standard Deviation
RevWeibull

The Reverse Weibull Distribution
RunsTest

Runs Test for Randomness
Sort

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

Sort Strings with Embedded Numbers Based on Their Numeric Order
Depreciation

Several Methods of Depreciation of an Asset
Sample

Random Samples and Permutations
StrAlign

String Alignment
StrDist

Compute Distances Between Strings
StrCountW

Count Words in a String
StrAbbr

String Abbreviation
PlotVenn

Plot a Venn Diagram
PlotFun

Plot a Function
PlotBubble

Draw a Bubble Plot
PlotFdist

Frequency Distribution Plot
PlotTreemap

Create a Treemap
Rename

Change Names of a Named Object
StripAttr

Remove Attributes from an Object
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
SendOutlookMail

Send a Mail Using Outlook as Mail Client
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
Stamp

Date/Time/Directory Stamp the Current Plot
SplitPath

Split Path In Drive, Path, Filename
SmoothSpline

Formula Interface For smooth.spline
StrChop

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

Stuart \(\tau_{c}\)
ToWrd

Send Objects to Word
reorder.factor

Reorder the Levels of a Factor
StrCap

Capitalize the First Letter of a String
Measures of Shape

Skewness and Kurtosis
SplitToCol

Split Data Frame String Column Into Multiple Columns
RobScale

Robust Scaling With Median and Mad
SysInfo

System Information
ToWrdB

Send Objects to Word and Bookmark Them
TMod

Comparison Table For Linear Models
UncertCoef

Uncertainty Coefficient
SetNames

Set the Names in an Object
ToWrdPlot

Send a Plot to Word and Bookmark it
UnirootAll

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

Add an Alpha Channel To a Color
RomanToInt

Convert Roman Numerals to Integers
Shade

Produce a Shaded Curve
Trim

Trim a Vector
Var

Variance
TOne

Create Table One Describing Baseline Characteristics
VecRot

Vector Rotation (Shift Elements)
VarTest

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

Calculate Tukey's Biweight Robust Mean
WrdPageBreak

Insert a Page Break
StdCoef

Standardized Model Coefficients
TwoGroups

Describe a Variable by a Factor with Two Levels
VarCI

Confidence Intervals for the Variance
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Some

Return Some Randomly Chosen Elements of an Object
WrdMergeCells

Merges Cells Of a Defined Word Table Range
SignTest

Sign Test
SomersDelta

Somers' Delta
WrdCaption

Insert Caption to Word
WrdCellRange

Return the Cell Range Of a Word Table
d.periodic

Periodic Table of Elements
StrExtract

Extract Part of a String
as.matrix.xtabs

Convert xtabs To matrix
WrdTable

Insert a Table in a Word Document
WrdTableBorders

Draw Borders to a Word Table
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
DescTools Aliases

Some Aliases Set for Convenience
XLSaveAs

Save Excel File
StrIsNumeric

Does a String Contain Only Numeric Data
XLView

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

Matrix Power
StrSpell

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

Plot Boxed Annotation
Str

Compactly Display the Structure of any R Object
StrSplit

Split the Elements of a Character Vector
lines.lm

Add a Linear Regression Line
d.pizza

Data pizza
StrPad

Pad a String With Justification
StrTrunc

Truncate Strings and Add Ellipses If a String is Truncated.
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrRev

Reverse a String
SpearmanRho

Spearman Rank Correlation
lines.loess

Add a Loess or a Spline Smoother
StrTrim

Remove Leading/Trailing Whitespace From A String
ToLong, ToWide

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

Recover Original Data From Contingency Table
XLDateToPOSIXct

Convert Excel Dates to POSIXct
WrdFont

Get or Set the Font in Word
WithOptions

Execute Function with Temporary Options
Unwhich

Inverse Which
WrdFormatCells

Format Cells Of a Word Table
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
XLGetRange

Import Data Directly From Excel
d.countries

ISO 3166-1 Country Codes
TTestA

Student's t-Test Based on Sample Statistics
StrPos

Find Position of First Occurrence Of a String
d.diamonds

Data diamonds
TheilU

Theil's U Index of Inequality
StrVal

Extract All Numeric Values From a String
TextToTable

Converts String To a Table
Strata

Stratified Sampling
%nin%

Find Matching (or Non-Matching) Elements
VIF

Variance Inflation Factors
Vigenere

Vigenere Cypher
VonNeumannTest

Von Neumann's Successive Difference Test
WrdPlot

Insert Active Plot to Word
VanWaerdenTest

van der Waerden Test
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
TextContrastColor

Choose Textcolor Depending on Background Color
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
ZeroIfNA

Replace NAs by 0
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
WrdSaveAs

Open and Save Word Documents
%c%

Concatenates Two Strings Without Any Separator
d.whisky

Classification of Scotch Single Malts
YuenTTest

Yuen t-Test For Trimmed Means
ZTest

Z Test for Known Population Standard Deviation
power.chisq.test

Power Calculations for ChiSquared Tests
WrdStyle

Get or Set the Style in Word
day.name

Build-in Constants Extension
identify.formula

Identify Points In a Plot Using a Formula
Zodiac

Calculate the Zodiac of a Date
%like%

Like Operator
split.formula

Formula Interface for Split
wdConst

Word VBA Constants