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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

January 18th, 2024

Functions in DescTools (0.99.53)

Atkinson

Atkinson Index - A Measure of Inequality.
Assocs

Association Measures
AllDuplicated

Index Vector of All Values Involved in Ties
AxisBreak

Place a Break Mark on an Axis
Abind

Combine Multidimensional Arrays
BarnardTest

Barnard's Unconditional Test
Append

Append Elements to Objects
BartelsRankTest

Bartels Rank Test of Randomness
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Arrow

Insert an Arrow Into a Plot
Benford

Benford's Distribution
BarText

Place Value Labels on a Barplot
Base Conversions

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

Binary Tree
BhapkarTest

Bhapkar Marginal Homogeneity Test
Between, Outside

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

Confidence Intervals for the Ratio of Binomial Proportions
Asp

Get Aspect Ratio of the Current Plot
BinomDiffCI

Confidence Interval for a Difference of Binomials
BootCI

Simple Bootstrap Confidence Intervals
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BoxCox

Box Cox Transformation
BoxedText

Add Text in a Box to a Plot
Bg

Background of a Plot
BinomCI

Confidence Intervals for Binomial Proportions
BinomCIn

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

Brier Score for Assessing Prediction Accuracy
BubbleLegend

Add a Legend to a Bubble Plot
CochranArmitageTest

Cochran-Armitage Test for Trend
Coalesce

Return the First Element Not Being NA
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
CohenD

Cohen's Effect Size
BreuschGodfreyTest

Breusch-Godfrey Test
CohenKappa

Cohen's Kappa and Weighted Kappa
CochranQTest

Cochran's Q test
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
ColToRgb

Color to RGB Conversion
ColToHsv

R Color to HSV Conversion
ColToGrey

Convert Colors to Grey/Grayscale
CoefVar

Coefficient of Variation
ColumnWrap

Column Wrap
CatTable

Function to write a table
CombPairs

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

Concordant and Discordant Pairs
ColToHex

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

Find Complete Columns
CCC

Concordance Correlation Coefficient
CountCompCases

Count Complete Cases
ConvUnit

Unit Conversion and Metrix Prefixes
Conf

Confusion Matrix And Associated Statistics
Cor

Covariance and Correlation (Matrices)
Canvas

Canvas for Geometric Plotting
CountWorkDays

Count Work Days Between Two Dates
Cross

Vector Cross Product
CrossN

n-dimensional Vector Cross Product
Clockwise

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

Get HWZ Datasets
ConoverTest

Conover's Test of Multiple Comparisons
Cstat

C Statistic (Area Under the ROC Curve)
ConnLines

Add Connection Lines to a Barplot
Contrasts

Pairwise Contrasts
Date Functions

Basic Date Functions
Datasets for Simulation

Datasets for Probabilistic Simulation
Association measures

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

Find the Closest Value
CutQ

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

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

Cramer-von Mises Test for Normality
CorPolychor

Polychoric Correlation
CronbachAlpha

Cronbach's Coefficient Alpha
ColorLegend

Add a ColorLegend to a Plot
CollapseTable

Collapse Levels of a Table
DoBy

Evaluates a Function Groupwise
DescToolsOptions

DescTools Options
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DivCoef

Rao's Diversity Coefficient
DoCall

Fast Alternative To The Internal do.call
DegToRad

Convert Degrees to Radians and Vice Versa
DivCoefMax

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

Calculate Digit Sum
Divisors

Calculate Divisors
Desc

Describe Data
Dot

Scalar Product
DrawRegPolygon

Draw Regular Polygon(s)
Dummy

Generate Dummy Codes for a Factor
DunnTest

Dunn's Test of Multiple Comparisons
DrawCircle

Draw a Circle
DunnettTest

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

Draw Confidence Band
DrawEllipse

Draw an Ellipse
DrawArc

Draw Elliptic Arc(s)
DurbinWatsonTest

Durbin-Watson Test
FctArgs

Retrieve a Function's Arguments
DrawBezier

Draw a Bezier Curve
Factorize

Prime Factorization of Integers
ErrBars

Add Error Bars to an Existing Plot
EtaSq

Effect Size Calculations for ANOVAs
EX

Expected Value and Variance
ExpFreq

Expected Frequencies
FixToTable

Convert a Text to a Table
ExtrVal

Distributions of Maxima and Minima
Freq

Frequency Table for a Single Variable
Fibonacci

Fibonacci Numbers
FindColor

Get Color on a Defined Color Range
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Entropy

Shannon Entropy and Mutual Information
Frac

Fractional Part and Maximal Digits of a Numeric Value
GenExtrVal

The Generalized Extreme Value Distribution
GenPareto

The Generalized Pareto Distribution
GetCalls

Return All Used Functions Within a Function
GeomTrans

Geometric Transformations
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
Format

Format Numbers and Dates
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Gini

Gini Coefficient
GetNewXL

Create a New Excel Instance
FindCorr

Determine Highly Correlated Variables
HotellingsT2Test

Hotelling's T2 Test
Gompertz

The Gompertz distribution
HexToRgb

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

Goodman Kruskal's Gamma
Gumbel

The Gumbel Distribution
Frechet

The Frechet Distribution
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
GoodmanKruskalTau

Goodman Kruskal's Tau
IsPrime

IsPrime Property
HoeffD

Matrix of Hoeffding's D Statistics
Hmean

Harmonic Mean and Its Confidence Interval
Herfindahl

Concentration Measures
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
GetNewWrd

Create a New Word Instance
FisherZ

Fisher-Transformation for Correlation to z-Score
GTest

G-Test for Count Data
HuberM

Safe (generalized) Huber M-Estimator of Location
IsEuclid

Is a Distance Matrix Euclidean?
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
KappaM

Kappa for m Raters
IsValidHwnd

Check Windows Pointer
GenRandGroups

Generate Random Groups
HexToCol

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

Last Observation Carried Forward
InDots

Is a Specific Argument in the Dots-Arguments?
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
LOF

Local Outlier Factor
LinScale

Linear Scaling
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
IsOdd

Checks If An Integer Is Even Or Odd
GiniSimpson

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

Geometric Series
Keywords

List Keywords For R Manual Pages
KendallW

Kendall's Coefficient of Concordance W
Gmean

Geometric Mean and Standard Deviation
ICC

Intraclass Correlations (ICC1, ICC2, ICC3 From Shrout and Fleiss)
Some numeric checks

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

Convert Line Coordinates To User Coordinates
LogSt

Started Logarithmic Transformation and Its Inverse
JarqueBeraTest

(Robust) Jarque Bera Test
KendallTauA

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

The (weighted) Interquartile Range
LehmacherTest

Lehmacher's Test for Marginal Homogenity
KendallTauB

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

Hodges-Lehmann Estimator of Location
HmsToSec

Convert h:m:s To/From Seconds
LeveneTest

Levene's Test for Homogeneity of Variance
IsDate

Check If an Object Is of Type Date
IsDichotomous

Test If a Variable Contains Only Two Unique Values
ImputeKnn

Fill in NA values with the values of the nearest neighbours
Label, Unit

Label, Unit Attribute of an Object
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
MeanAD

Mean Absolute Deviation From a Center Point
Lambda

Goodman Kruskal Lambda
Lc

Lorenz Curve
MADCI

Confidence Intervals for Median Absolute Deviations
MAD

Median Absolute Deviation
MeanCI

Confidence Intervals for the Mean
Mar and Mgp

Set Plot Margins and Distances
Mean

(Weighted) Arithmetic Mean
Midx

Find the Midpoints of a Numeric Vector
MixColor

Compute the Convex Combination of Two Colors
MedianCI

Confidence Interval for the Median
Logit

Generalized Logit and Inverse Logit Function
MeanCIn

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

Kth Smallest/Largest Values
MeanSE

Standard Error of Mean
List Variety Of Objects

List Objects, Functions Or Data in a Package
MeanDiffCI

Confidence Interval For Difference of Means
Median

(Weighted) Median Value
MoveAvg

Moving Average
Mode

Mode, Most Frequent Value(s)
MosesTest

Moses Test of Extreme Reactions
MultMerge

Merge Multiple Data Frames
MultinomCI

Confidence Intervals for Multinomial Proportions
NPV

Short Selection of Financial Mathematical Functions
Mgsub

Multiple Gsub
NemenyiTest

Nemenyi Test
Nf

As Numeric Factor
PDFManual

Get PDF Manual of a Package From CRAN
PMT

Periodic Payment of an Annuity.
Measures of Accuracy

Measures of Accuracy
ORToRelRisk

Transform Odds Ratio to Relative Risk
PearsonTest

Pearson Chi-Square Test for Normality
PercTable

Percentage Table
OddsRatio

Odds Ratio Estimation and Confidence Intervals
MHChisqTest

Mantel-Haenszel Chi-Square Test
Order

Distributions of Order Statistics
PageTest

Exact Page Test for Ordered Alternatives
PlotCandlestick

Plot Candlestick Chart
PercentRank

Percent Ranks
Outlier

Outlier
PlotBubble

Draw a Bubble Plot
Permn

Number and Samples for Permutations or Combinations of a Set
ParseSASDatalines

Parse a SAS Dataline Command
PasswordDlg

Password Dialog
DescTools Palettes

Some Custom Palettes
PairApply

Pairwise Calculations
PlotArea

Create an Area Plot
PlotCashFlow

Cash Flow Plot
PlotBag

Bivariate Boxplot
PlotFaces

Chernoff Faces
ParseFormula

Parse a Formula and Create a Model Frame
PlotFdist

Frequency Distribution Plot
PlotCirc

Plot Circular Plot
PlotConDens

Plot Conditional Densities
Phrase

Phrasing Results of t-Test
PlotFun

Plot a Function
PlotLog

Logarithmic Plot
PlotMarDens

Scatterplot With Marginal Densities
PlotACF

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

Plot Lines
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotMosaic

Mosaic Plots
PlotCorr

Plot a Correlation Matrix
PlotQQ

QQ-Plot for Any Distribution
PlotMiss

Plot Missing Data
PlotECDF

Empirical Cumulative Distribution Function
PlotDot

Cleveland's Dot Plots
PlotProbDist

Plot Probability Distribution
PlotViolin

Plot Violins Instead of Boxplots
PtInPoly

Point in Polygon
Primes

Find All Primes Less Than n
PseudoR2

Pseudo R2 Statistics
PlotPairs

Extended Scatterplot Matrices
PlotMultiDens

Plot Multiple Density Curves
RSessionAlive

How Long Has the RSession Been Running?
QuantileCI

Confidence Interval for Any Quantile
Quantile

(Weighted) Sample Quantiles
PlotPolar

Plot Values on a Circular Grid
PlotTernary

Ternary or Triangular Plots
PostHocTest

Post-Hoc Tests
PlotWeb

Plot a Web of Connected Points
PlotPyramid

Draw a Back To Back Pyramid Plot
PoissonCI

Poisson Confidence Interval
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
ColToOpaque

Equivalent Opaque Color for Transparent Color
pRevGumbel

"Reverse" Gumbel Distribution Functions
PolarGrid

Plot a Grid in Polar Coordinates
Rank

Fast Sample Ranks
Recode

Recode a Factor
PlotTreemap

Create a Treemap
Range

(Robust) Range
RgbToCol

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

Recyle a List of Elements
PlotVenn

Plot a Venn Diagram
Depreciation

Several Methods of Depreciation of an Asset
RevWeibull

The Reverse Weibull Distribution
Quot

Lagged Quotients
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Sample

Random Samples and Permutations
RgbToCmy

Conversion Between RGB and CMYK
RndPairs

Create Pairs of Correlated Random Numbers
SetNames

Set the Names in an Object
SetAlpha

Add an Alpha Channel To a Color
RobScale

Robust Scaling With Median and Mad
RomanToInt

Convert Roman Numerals to Integers
ShapiroFranciaTest

Shapiro-Francia Test for Normality
Shade

Produce a Shaded Curve
RelRisk

Relative Risk
SampleTwins

Sample Twins
Measures of Shape

Skewness and Kurtosis
SpearmanRho

Spearman Rank Correlation
Some

Return Some Randomly Chosen Elements of an Object
SmoothSpline

Formula Interface For smooth.spline
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrPos

Find Position of First Occurrence Of a String
SplitToDummy

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

Saves an R Object Under a Different Name
Rev

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

Reverse a String
Rename

Change Names of a Named Object
reorder.factor

Reorder the Levels of a Factor
TTestA

Student's t-Test Based on Sample Statistics
Str

Compactly Display the Structure of any R Object
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
TOne

Create Table One Describing Baseline Characteristics
RunsTest

Runs Test for Randomness
StrAlign

String Alignment
SomersDelta

Somers' Delta
SD

(Weighted) Standard Deviation
Rotate

Rotate a Geometric Structure
StdCoef

Standardized Model Coefficients
Stamp

Date/Time/Directory Stamp the Current Plot
StrCap

Capitalize the First Letter of a String
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
ToWrdB

Send Objects to Word and Bookmark Them
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
RevCode

Reverse Codes
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
VIF

Variance Inflation Factors
Strata

Stratified Sampling
StrSpell

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

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

Round to Multiple
StrVal

Extract All Numeric Values From a String
VanWaerdenTest

van der Waerden Test
StrAbbr

String Abbreviation
StrIsNumeric

Does a String Contain Only Numeric Data
StrSplit

Split the Elements of a Character Vector
VarTest

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

Send a Mail Using Outlook as Mail Client
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
StrPad

Pad a String With Justification
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
TextContrastColor

Choose Textcolor Depending on Background Color
Sort

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

Variance
WrdTable

Insert a Table in a Word Document
StripAttr

Remove Attributes from an Object
WrdFont

Get or Set the Font in Word
VarCI

Confidence Intervals for the Variance
ToWrdPlot

Send a Plot to Word and Bookmark it
StuartTauC

Stuart \(\tau_{c}\)
WrdTableBorders

Draw Borders to a Word Table
TitleRect

Plot Boxed Annotation
matpow

Matrix Power
SplitPath

Split Path In Drive, Path, Filename
SignTest

Sign Test
power.chisq.test

Power Calculations for ChiSquared Tests
WrdFormatCells

Format Cells Of a Word Table
VecRot

Vector Rotation (Shift Elements)
TheilU

Theil's U Index of Inequality
d.countries

ISO 3166-1 Country Codes
TextToTable

Converts String To a Table
ToLong, ToWide

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

Insert Active Plot to Word
DescTools Aliases

Some Aliases Set for Convenience
TMod

Comparison Table For Linear Models
StrTrim

Remove Leading/Trailing Whitespace From A String
StrDist

Compute Distances Between Strings
WrdParagraphFormat

Get or Set the Paragraph Format in Word
StrChop

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

Merges Cells Of a Defined Word Table Range
SplitToCol

Split Data Frame String Column Into Multiple Columns
WrdSaveAs

Open and Save Word Documents
StrExtract

Extract Part of a String
XLSaveAs

Save Excel File
d.diamonds

Data diamonds
WrdStyle

Get or Set the Style in Word
d.periodic

Periodic Table of Elements
YuenTTest

Yuen t-Test For Trimmed Means
Untable

Recover Original Data From Contingency Table
XLView

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

System Information
WithOptions

Execute Function with Temporary Options
rSum21

Random Numbers Adding Up to 1
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Zodiac

Calculate the Zodiac of a Date
ToWrd

Send Objects to Word
StrCountW

Count Words in a String
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
ZTest

Z Test for Known Population Standard Deviation
XLGetRange

Import Data Directly From Excel
identify.formula

Identify Points In a Plot Using a Formula
UncertCoef

Uncertainty Coefficient
%nin%

Find Matching (or Non-Matching) Elements
TwoGroups

Describe a Variable by a Factor with Two Levels
Vigenere

Vigenere Cypher
d.whisky

Classification of Scotch Single Malts
UnirootAll

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

Convert Excel Dates to POSIXct
VonNeumannTest

Von Neumann's Successive Difference Test
day.name

Build-in Constants Extension
Triangular

The Triangular Distribution
wdConst

Word VBA Constants
split.formula

Formula Interface for Split
%c%

Concatenates Two Strings Without Any Separator
WrdPageBreak

Insert a Page Break
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
ZeroIfNA

Replace NAs by 0
d.pizza

Data pizza
Trim

Trim a Vector
as.matrix.xtabs

Convert xtabs To matrix
Unwhich

Inverse Which
%like%

Like Operator
WrdCaption

Insert Caption to Word
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
WrdCellRange

Return the Cell Range Of a Word Table
lines.loess

Add a Loess or a Spline Smoother
lines.lm

Add a Linear Regression Line
Abstract

Display Compact Abstract of a Data Frame
ABCCoords

Coordinates for "bottomright", etc.
AddMonths

Add a Month to a Date
Agree

Raw Simple And Extended Percentage Agreement
AddMonthsYM

Add a Month to a Date in YearMonth Format
AllIdentical

Test Multiple Objects for Exact Equality
AUC

Area Under the Curve
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit