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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

November 23rd, 2021

Functions in DescTools (0.99.44)

ABCCoords

Coordinates for "bottomright", etc.
AddMonthsYM

Add a Month to a Date in YearMonth Format
Abind

Combine Multidimensional Arrays
Abstract

Display Compact Abstract of a Data Frame
Agree

Raw Simple And Extended Percentage Agreement
AddMonths

Add a Month to a Date
AUC

Area Under the Curve
AllDuplicated

Index Vector of All Values Involved in Ties
AllIdentical

Test Multiple Objects for Exact Equality
AscToChar

Convert ASCII Codes to Characters and Vice Versa
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
Append

Append Elements to Objects
AxisBreak

Place a Break Mark on an Axis
BarnardTest

Barnard's Unconditional Test
BinomCIn

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

Confidence Intervals for Binomial Proportions
Arrow

Insert an Arrow Into a Plot
Between, Outside

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

Background of a Plot
Asp

Get Aspect Ratio of the Current Plot
Base Conversions

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

Benford's Distribution
BartelsRankTest

Bartels Rank Test of Randomness
BubbleLegend

Add a Legend to a Bubble Plot
BrierScore

Brier Score for Assessing Prediction Accuracy
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
CohenD

Cohen's Effect Size
CohenKappa

Cohen's Kappa and Weighted Kappa
BoxedText

Add Text in a Box to a Plot
Closest

Find the Closest Value
Atkinson

Atkinson Index - A Measure of Inequality.
Clockwise

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

Collapse Levels of a Table
BinTree

Binary Tree
BinomDiffCI

Confidence Interval for a Difference of Binomials
BhapkarTest

Bhapkar Marginal Homogeneity Test
Assocs

Association Measures
BarText

Place Value Labels on a Barplot
BootCI

Simple Bootstrap Confidence Intervals
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
ColorLegend

Add a ColorLegend to a Plot
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
CatTable

Function to write a table
Conf

Confusion Matrix And Associated Statistics
ConnLines

Add Connection Lines to a Barplot
CombPairs

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

Count Complete Cases
CorPart

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

Breusch-Godfrey Test
CountWorkDays

Count Work Days Between Two Dates
ColumnWrap

Column Wrap
CourseData

Get HWZ Datasets
CorPolychor

Polychoric Correlation
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
Cross

Vector Cross Product
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
CochranArmitageTest

Cochran-Armitage Test for Trend
Coalesce

Return the First Element Not Being NA
Canvas

Canvas for Geometric Plotting
ColToGrey

Convert Colors to Grey/Grayscale
CCC

Concordance Correlation Coefficient
Date Functions

Basic Date Functions
ColToHex

Convert a Color or a RGB-color Into Hex String
Datasets for Simulation

Datasets for Probabilistic Simulation
BoxCox

Box Cox Transformation
CochranQTest

Cochran's Q test
CoefVar

Coefficient of Variation
ColToRgb

Color to RGB Conversion
DegToRad

Convert Degrees to Radians and Vice Versa
Desc

Describe Data
Contrasts

Pairwise Contrasts
Cstat

C Statistic (Area Under the ROC Curve)
ConoverTest

Conover's Test of Multiple Comparisons
DivCoefMax

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

R Color to HSV Conversion
DoCall

Fast Alternative To The Internal do.call
DoBy

Evaluates a Function Groupwise
DrawBand

Draw Confidence Band
Divisors

Calculate Divisors
DrawRegPolygon

Draw Regular Polygon(s)
DigitSum

Calculate Digit Sum
DrawCircle

Draw a Circle
DescToolsOptions

DescTools Options
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
CutQ

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

Rao's Diversity Coefficient
ExpFreq

Expected Frequencies
Dummy

Generate Dummy Codes for a Factor
EtaSq

Effect Size Calculations for ANOVAs
Dot

Scalar Product
ExtrVal

Distributions of Maxima and Minima
DrawEllipse

Draw an Ellipse
DrawArc

Draw Elliptic Arc(s)
DrawBezier

Draw a Bezier Curve
DurbinWatsonTest

Durbin-Watson Test
Entropy

Shannon Entropy and Mutual Information
Fibonacci

Fibonacci Numbers
DunnettTest

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

Return All Used Functions Within a Function
FctArgs

Retrieve a Function's Arguments
DunnTest

Dunn's Test of Multiple Comparisons
GCD, LCM

Greatest Common Divisor and Least Common Multiple
FindCorr

Determine Highly Correlated Variables
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
FindColor

Get Color on a Defined Color Range
ConDisPairs

Concordant and Discordant Pairs
CompleteColumns

Find Complete Columns
Frechet

The Frechet Distribution
Factorize

Prime Factorization of Integers
GenExtrVal

The Generalized Extreme Value Distribution
GTest

G-Test for Count Data
GoodmanKruskalGamma

Goodman Kruskal's Gamma
GetNewWrd

Create a New Word Instance
GoodmanKruskalTau

Goodman Kruskal's Tau
CramerVonMisesTest

Cramer-von Mises Test for Normality
ConvUnit

Unit Conversion and Metrix Prefixes
Freq

Frequency Table for a Single Variable
Cor

Covariance and Correlation (Matrices)
Frac

Fractional Part and Maximal Digits of a Numeric Value
CronbachAlpha

Cronbach's Coefficient Alpha
ErrBars

Add Error Bars to an Existing Plot
Format

Format Numbers and Dates
GetNewXL

Create a New Excel Instance
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
Gini

Gini Coefficient
GenRandGroups

Generate Random Groups
GenPareto

The Generalized Pareto Distribution
Gumbel

The Gumbel Distribution
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
FisherZ

Fisher-Transformation for Correlation to z-Score
HexToCol

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

Convert a Text to a Table
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
IsDate

Check If an Object Is of Type Date
InDots

Is a Specific Argument in the Dots-Arguments?
HoeffD

Matrix of Hoeffding's D Statistics
HodgesLehmann

Hodges-Lehmann Estimator of Location
GeomSn

Geometric Series
GeomTrans

Geometric Transformations
HuberM

Safe (generalized) Huber M-Estimator of Location
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
JarqueBeraTest

(Robust) Jarque Bera Test
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
HexToRgb

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

Hotelling's T2 Test
ICC

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

Concentration Measures
IsValidHwnd

Check Windows Pointer
IQRw

The (weighted) Interquartile Range
LOF

Local Outlier Factor
Label, Unit

Label, Unit Attribute of an Object
LeveneTest

Levene's Test for Homogeneity of Variance
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
LOCF

Last Observation Carried Forward
List Variety Of Objects

List Objects, Functions Or Data in a Package
Keywords

List Keywords For R Manual Pages
Some numeric checks

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

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

Linear Scaling
LineToUser

Convert Line Coordinates To User Coordinates
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
Gmean

Geometric Mean and Standard Deviation
MeanAD

Mean Absolute Deviation From a Center Point
MeanDiffCI

Confidence Interval For Difference of Means
Mean

(Weighted) Arithmetic Mean
Hmean

Harmonic Mean and Its Confidence Interval
Gompertz

The Gompertz distribution
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Lc

Lorenz Curve
MeanSE

Standard Error of Mean
MultinomCI

Confidence Intervals for Multinomial Proportions
NPV

Short Selection of Financial Mathematical Functions
OddsRatio

Odds Ratio Estimation and Confidence Intervals
MAD

Median Absolute Deviation
Mode

Mode, Most Frequent Value(s)
PairApply

Pairwise Calculations
MosesTest

Moses Test of Extreme Reactions
DescTools Palettes

Some Custom Palettes
PlotConDens

Plot Conditional Densities
PlotCirc

Plot Circular Plot
IsPrime

IsPrime Property
HmsToSec

Convert h:m:s To/From Seconds
MADCI

Confidence Intervals for Median Absolute Deviations
IsOdd

Checks If An Integer Is Even Or Odd
Measures of Accuracy

Measures of Accuracy
KappaM

Kappa for m Raters
Lambda

Goodman Kruskal Lambda
KendallTauA

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

Confidence Interval for the Median
Outlier

Outlier
PDFManual

Get PDF Manual of a Package From CRAN
Median

(Weighted) Median Value
PlotMarDens

Scatterplot With Marginal Densities
PercentRank

Percent Ranks
PlotCandlestick

Plot Candlestick Chart
PercTable

Percentage Table
Extremes

Kth Smallest/Largest Values
PlotLog

Logarithmic Plot
PlotDot

Cleveland's Dot Plots
PlotLinesA

Plot Lines
PlotCorr

Plot a Correlation Matrix
PasswordDlg

Password Dialog
Order

Distributions of Order Statistics
MHChisqTest

Mantel-Haenszel Chi-Square Test
Mar and Mgp

Set Plot Margins and Distances
PlotTernary

Ternary or Triangular Plots
PlotTreemap

Create a Treemap
MoveAvg

Moving Average
PlotCashFlow

Cash Flow Plot
MultMerge

Merge Multiple Data Frames
PseudoR2

Pseudo R2 Statistics
PtInPoly

Point in Polygon
NemenyiTest

Nemenyi Test
LogSt

Started Logarithmic Transformation and Its Inverse
IsDichotomous

Test If a Variable Contains Only Two Unique Values
IsEuclid

Is a Distance Matrix Euclidean?
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
KendallW

Kendall's Coefficient of Concordance W
KendallTauB

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

Confidence Interval for the Mean
Logit

Generalized Logit and Inverse Logit Function
PlotMosaic

Mosaic Plots
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
ORToRelRisk

Transform Odds Ratio to Relative Risk
Range

(Robust) Range
PolarGrid

Plot a Grid in Polar Coordinates
PlotMiss

Plot Missing Data
PostHocTest

Post-Hoc Tests
Quot

Lagged Quotients
QuantileCI

Confidence Interval for Any Quantile
Quantile

Weighted Quantiles
PlotPyramid

Draw a Back To Back Pyramid Plot
reorder.factor

Reorder the Levels of a Factor
Permn

Number and Samples for Permutations or Combinations of a Set
PlotQQ

QQ-Plot for Any Distribution
Phrase

Phrasing Results of t-Test
PlotBag

Bivariate Boxplot
PlotACF

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

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

Chernoff Faces
PlotECDF

Empirical Cumulative Distribution Function
PearsonTest

Pearson Chi-Square Test for Normality
PlotArea

Create an Area Plot
RgbToCmy

Conversion Between RGB and CMYK
Midx

Find the Midpoints of a Numeric Vector
Rank

Fast Sample Ranks
PlotBubble

Draw a Bubble Plot
PlotMultiDens

Plot Multiple Density Curves
RelRisk

Relative Risk
RSessionAlive

How Long Has the RSession Been Running?
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PlotPairs

Extended Scatterplot Matrices
Primes

Find All Primes Less Than n
Rotate

Rotate a Geometric Structure
RomanToInt

Convert Roman Numerals to Integers
Shade

Produce a Shaded Curve
SetNames

Set the Names in an Object
Rev

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

Saves an R Object Under a Different Name
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Str

Compactly Display the Structure of any R Object
StrAbbr

String Abbreviation
PlotFdist

Frequency Distribution Plot
StrExtract

Extract Part of a String
ToLong, ToWide

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

Send Objects to Word
TwoGroups

Describe a Variable by a Factor with Two Levels
StrDist

Compute Distances Between Strings
PMT

Periodic Payment of an Annuity.
MixColor

Compute the Convex Combination of Two Colors
PlotFun

Plot a Function
PlotVenn

Plot a Venn Diagram
VarTest

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

Confidence Intervals for the Variance
UncertCoef

Uncertainty Coefficient
PoissonCI

Poisson Confidence Interval
Rename

Change Names of a Named Object
RndPairs

Create Pairs of Correlated Random Numbers
RgbToCol

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

The Reverse Weibull Distribution
PlotViolin

Plot Violins Instead of Boxplots
PlotWeb

Plot a Web of Connected Points
PageTest

Exact Page Test for Ordered Alternatives
ParseSASDatalines

Parse a SAS Dataline Command
ParseFormula

Parse a Formula and Create a Model Frame
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrChop

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

Split Path In Drive, Path, Filename
StrCountW

Count Words in a String
TitleRect

Plot Boxed Annotation
TheilU

Theil's U Index of Inequality
UnirootAll

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

Recover Original Data From Contingency Table
StrTrunc

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

Extract All Numeric Values From a String
PlotPolar

Plot Values on a Circular Grid
SendOutlookMail

Send a Mail Using Outlook as Mail Client
RobScale

Robust Scaling With Median and Mad
SD

(Weighted) Standard Deviation
ColToOpaque

Equivalent Opaque Color for Transparent Color
Depreciation

Several Methods of Depreciation of an Asset
Stamp

Date/Time/Directory Stamp the Current Plot
ShapiroFranciaTest

Shapiro-Francia Test for Normality
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
VecRot

Vector Rotation (Shift Elements)
RoundTo

Round to Multiple
RunsTest

Runs Test for Randomness
SignTest

Sign Test
StdCoef

Standardized Model Coefficients
Measures of Shape

Skewness and Kurtosis
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
SplitToCol

Split Data Frame String Column Into Multiple Columns
StrAlign

String Alignment
StrCap

Capitalize the First Letter of a String
WrdMergeCells

Merges Cells Of a Defined Word Table Range
WrdFormatCells

Format Cells Of a Word Table
YuenTTest

Yuen t-Test For Trimmed Means
XLView

Use MS-Excel as Viewer for a Data.Frame
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
Strata

Stratified Sampling
StrSpell

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

Reverse a String
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
PlotProbDist

Plot Probability Distribution
StrPos

Find Position of First Occurrence Of a String
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
%c%

Concatenates Two Strings Without Any Separator
d.countries

ISO 3166-1 Country Codes
SysInfo

System Information
StripAttr

Remove Attributes from an Object
TMod

Comparison Table For Linear Models
WithOptions

Execute Function with Temporary Options
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
SetAlpha

Add an Alpha Channel To a Color
WrdFont

Get or Set the Font in Word
WrdCellRange

Return the Cell Range Of a Word Table
matpow

Matrix Power
lines.loess

Add a Loess or a Spline Smoother
TextContrastColor

Choose Textcolor Depending on Background Color
TextToTable

Converts String To a Table
Unwhich

Inverse Which
Vigenere

Vigenere Cypher
WrdTableBorders

Draw Borders to a Word Table
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WrdCaption

Insert Caption to Word
Sort

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

Somers' Delta
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
Recode

Recode a Factor
d.diamonds

Data diamonds
XLDateToPOSIXct

Convert Excel Dates to POSIXct
VIF

Variance Inflation Factors
WrdSaveAs

Open and Save Word Documents
WrdPlot

Insert Active Plot to Word
VonNeumannTest

Von Neumann's Successive Difference Test
SpearmanRho

Spearman Rank Correlation
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
RevCode

Reverse Codes
StrIsNumeric

Does a String Contain Only Numeric Data
Recycle

Recyle a List of Elements
WrdStyle

Get or Set the Style in Word
StrSplit

Split the Elements of a Character Vector
StrPad

Pad a String With Justification
StrTrim

Remove Leading/Trailing Whitespace From A String
ToWrdB

Send Objects to Word and Bookmark Them
TTestA

Student's t-Test Based on Sample Statistics
TOne

Create Table One Describing Baseline Characteristics
WrdTable

Insert a Table in a Word Document
ZTest

Z Test for Known Population Standard Deviation
ToWrdPlot

Send a Plot to Word and Bookmark it
DescTools Aliases

Some Aliases Set for Convenience
d.periodic

Periodic Table of Elements
%nin%

Find Matching (or Non-Matching) Elements
pRevGumbel

"Reverse" Gumbel Distribution Functions
SampleTwins

Sample Twins
Sample

Random Samples and Permutations
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
Some

Return Some Randomly Chosen Elements of an Object
SmoothSpline

Formula Interface For smooth.spline
StuartTauC

Stuart \(\tau_{c}\)
ZeroIfNA

Replace NAs by 0
Zodiac

Calculate the Zodiac of a Date
power.chisq.test

Power Calculations for ChiSquared Tests
as.matrix.xtabs

Convert xtabs To matrix
VanWaerdenTest

van der Waerden Test
d.pizza

Data pizza
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Trim

Trim a Vector
Var

Variance
rSum21

Random Numbers Summing to 1
d.whisky

Classification of Scotch Single Malts
day.name

Build-in Constants Extension
WrdPageBreak

Insert a Page Break
identify.formula

Identify Points In a Plot Using a Formula
%like%

Like Operator
WrdParagraphFormat

Get or Set the Paragraph Format in Word
XLSaveAs

Save Excel File
XLGetRange

Import Data Directly From Excel
lines.lm

Add a Linear Regression Line
split.formula

Formula Interface for Split
wdConst

Word VBA Constants