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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

December 7th, 2020

Functions in DescTools (0.99.39)

AUC

Area Under the Curve
AddMonths

Add a Month to a Date
AddMonthsYM

Add a Month to a Date in YearMonth Format
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AllDuplicated

Index Vector of All Values Involved in Ties
Abstract

Display Compact Abstract of a Data Frame
Agree

Raw Simple And Extended Percentage Agreement
Append

Append Elements to Objects
Abind

Combine Multidimensional Arrays
AllIdentical

Test Multiple Objects for Exact Equality
Arrow

Insert an Arrow Into a Plot
Assocs

Association Measures
Asp

Get Aspect Ratio of the Current Plot
Atkinson

Atkinson Index - A Measure of Inequality.
AxisBreak

Place a Break Mark on an Axis
Benford

Benford's Distribution
Base Conversions

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

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

Bhapkar Marginal Homogeneity Test
BartelsRankTest

Bartels Rank Test of Randomness
BinomCI

Confidence Intervals for Binomial Proportions
BinTree

Binary Tree
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
BreuschGodfreyTest

Breusch-Godfrey Test
CohenD

Cohen's Effect Size
CatTable

Function to write a table
BrierScore

Brier Score for Assessing Prediction Accuracy
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
ColToHex

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

Convert ASCII Codes to Characters and Vice Versa
ColToGrey

Convert Colors to Grey/Grayscale
CollapseTable

Collapse Levels of a Table
BootCI

Simple Bootstrap Confidence Intervals
CCC

Concordance Correlation Coefficient
ColorLegend

Add a ColorLegend to a Plot
CohenKappa

Cohen's Kappa and Weighted Kappa
BarText

Add the Value Labels to a Barplot
BoxCox

Box Cox Transformation
BarnardTest

Barnard's Unconditional Test
CountCompCases

Count Complete Cases
Canvas

Canvas for Geometric Plotting
CompleteColumns

Find Complete Columns
Between, Outside

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

Count Work Days Between Two Dates
Clockwise

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

Confusion Matrix And Associated Statistics
Closest

Find the Closest Value
BubbleLegend

Add a Legend to a Bubble Plot
ConoverTest

Conover's Test of Multiple Comparisons
CourseData

Get HWZ Datasets
ConnLines

Add Connection Lines to a Barplot
Contrasts

Pairwise Contrasts
ConDisPairs

Concordant and Discordant Pairs
DoCall

Fast Alternative To The Internal do.call
DescToolsOptions

DescTools Options
CrossN

n-dimensional Vector Cross Product
Cross

Vector Cross Product
Association measures

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

Dense Ranks and Percent Ranks
DegToRad

Convert Degrees to Radians and Vice Versa
BinomDiffCI

Confidence Interval for a Difference of Binomials
Dot

Scalar Product
Date Functions

Basic Date Functions
Datasets for Simulation

Datasets for Probabilistic Simulation
DoBy

Evaluates a Function Groupwise
DigitSum

Calculate Digit Sum
Dummy

Generate Dummy Codes for a Factor
Entropy

Shannon Entropy and Mutual Information
DunnTest

Dunn's Test of Multiple Comparisons
Divisors

Calculate Divisors
FixToTable

Convert a Text to a Table
DrawBezier

Draw a Bezier Curve
Format

Format Numbers and Dates
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
DrawEllipse

Draw an Ellipse
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
FindCorr

Determine Highly Correlated Variables
CochranQTest

Cochran's Q test
BinomRatioCI

Confidence Intervals for the Ratio of Binomial and Multinomial Proportions
CoefVar

Coefficient of Variation
GetCalls

Return All Used Functions Within a Function
EtaSq

Effect Size Calculations for ANOVAs
DrawCircle

Draw a Circle
ErrBars

Add Error Bars to an Existing Plot
ColumnWrap

Column Wrap
HexToCol

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

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

Get a Handle to a Running Word Instance
GetNewXL

Create a New Excel Instance
Gumbel

The Gumbel Distribution
Coalesce

Return the First Element Not Being NA
GetNewWrd

Create a New Word Instance
CochranArmitageTest

Cochran-Armitage Test for Trend
Freq

Frequency Table for a Single Variable
FisherZ

Fisher-Transformation for Correlation to z-Score
BoxedText

Add Text in a Box to a Plot
HexToRgb

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

Polychoric Correlation
CorPart

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

Draw Regular Polygon(s)
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
ColToRgb

Color to RGB Conversion
ColToHsv

R Color to HSV Conversion
ConvUnit

Unit Conversion and Metrix Prefixes
Cor

Covariance and Correlation (Matrices)
Cstat

C Statistic (Area Under the ROC Curve)
Gmean

Geometric Mean and Standard Deviation
GCD, LCM

Greatest Common Divisor and Least Common Multiple
FctArgs

Retrieve a Function's Arguments
Factorize

Prime Factorization of Integers
Gompertz

The Gompertz distribution
Herfindahl

Concentration Measures
InDots

Is a Specific Argument in the Dots-Arguments?
IsDate

Check If an Object Is of Type Date
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
HodgesLehmann

Hodges-Lehmann Estimator of Location
Desc

Describe Data
CutQ

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

Geometric Series
IsEuclid

Is a Distance Matrix Euclidean?
IsDichotomous

Test If a Variable Contains Only Two Unique Values
GeomTrans

Geometric Transformations
GTest

G-Test for Count Data
HoeffD

Matrix of Hoeffding's D Statistics
GoodmanKruskalGamma

Goodman Kruskal's Gamma
LOCF

Last Observation Carried Forward
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
Lc

Lorenz Curve
KendallW

Kendall's Coefficient of Concordance W
KendallTauB

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

Hosmer-Lemeshow Goodness of Fit Tests
LineToUser

Convert Line Coordinates To User Coordinates
KappaM

Kappa for m Raters
LinScale

Linear Scaling
HotellingsT2Test

Hotelling's T2 Test
IsValidHwnd

Check Windows Pointer
KendallTauA

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

Cramer-von Mises Test for Normality
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Keywords

List Keywords For R Manual Pages
GoodmanKruskalTau

Goodman Kruskal's Tau
MeanCI

Confidence Interval for the Mean
Extremes

Kth Smallest/Largest Values
MHChisqTest

Mantel-Haenszel Chi-Square Test
Lambda

Goodman Kruskal Lambda
Some numeric checks

Check a Vector For Being Numeric, Zero Or a Whole Number
List Variety Of Objects

List Objects, Functions Or Data in a Package
Fibonacci

Fibonacci Numbers
DurbinWatsonTest

Durbin-Watson Test
DunnettTest

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

Get Color on a Defined Color Range
Mar and Mgp

Set Plot Margins and Distances
Gini

Gini Coefficient
Mean

(Weighted) Arithmetic Mean
MAD

Median Absolute Deviation
LeveneTest

Levene's Test for Homogeneity of Variance
NPV

Short Selection of Financial Mathematical Functions
MeanAD

Mean Absolute Deviation From a Center Point
ImputeKnn

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

Nemenyi Test
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
MosesTest

Moses Test of Extreme Reactions
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
CronbachAlpha

Cronbach's Coefficient Alpha
IQRw

The (weighted) Interquartile Range
DivCoef

Rao's Diversity Coefficient
DrawArc

Draw Elliptic Arc(s)
DivCoefMax

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

Expected Frequencies
ExtrVal

Distributions of Maxima and Minima
Frac

Fractional Part and Maximal Digits of a Numeric Value
DrawBand

Draw Confidence Band
Frechet

The Frechet Distribution
PDFManual

Get PDF Manual of a Package From CRAN
MoveAvg

Moving Average
ORToRelRisk

Transform Odds Ratio to Relative Risk
GenExtrVal

The Generalized Extreme Value Distribution
Hmean

Harmonic Mean and Its Confidence Interval
HmsToSec

Convert h:m:s To/From Seconds
GenPareto

The Generalized Pareto Distribution
HuberM

Safe (generalized) Huber M-Estimator of Location
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
Permn

Number and Samples for Permutations or Combinations of a Set
Phrase

Phrasing Results of t-Test
OddsRatio

Odds Ratio Estimation and Confidence Intervals
JarqueBeraTest

(Robust) Jarque Bera Test
ICC

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

Frequency Distribution Plot
MADCI

Confidence Intervals for Median Absolute Deviations
PlotLinesA

Plot Lines
PlotFun

Plot a Function
PlotLog

Logarithmic Plot
MedianCI

Confidence Interval for the Median
Midx

Find the Midpoints of a Numeric Vector
MeanDiffCI

Confidence Interval For Difference of Means
PlotTreemap

Create a Treemap
RevCode

Reverse Codes
pRevGumbel

"Reverse" Gumbel Distribution Functions
PlotVenn

Plot a Venn Diagram
PairApply

Pairwise Calculations
PageTest

Exact Page Test for Ordered Alternatives
PlotBag

Bivariate Boxplot
PlotConDens

Plot Conditional Densities
PMT

Periodic Payment of an Annuity.
PlotCirc

Plot Circular Plot
PlotPolar

Plot Values on a Circular Grid
MixColor

Compute the Convex Combination of Two Colors
ParseSASDatalines

Parse a SAS Dataline Command
PlotCorr

Plot a Correlation Matrix
IsOdd

Checks If An Integer Is Even Or Odd
Measures of Accuracy

Measures of Accuracy
PlotMarDens

Scatterplot With Marginal Densities
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
PasswordDlg

Password Dialog
PlotDot

Cleveland's Dot Plots
IsPrime

IsPrime Property
PlotBubble

Draw a Bubble Plot
PlotMiss

Plot Missing Data
SendOutlookMail

Send a Mail Using Outlook as Mail Client
LOF

Local Outlier Factor
SpearmanRho

Spearman Rank Correlation
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
QuantileCI

Confidence Interval for Any Quantile
StrIsNumeric

Does a String Contain Only Numeric Data
SetAlpha

Add an Alpha Channel To a Color
StrPad

Pad a String With Justification
PolarGrid

Plot a Grid in Polar Coordinates
Strata

Stratified Sampling
PoissonCI

Poisson Confidence Interval
Quot

Lagged Quotients
PlotPyramid

Draw a Back To Back Pyramid Plot
RelRisk

Relative Risk
Mode

Mode, Most Frequent Value(s)
DescTools Palettes

Some Custom Palettes
Label, Unit

Label, Unit Attribute of an Object
Logit

Generalized Logit and Inverse Logit Function
PlotCandlestick

Plot Candlestick Chart
PlotCashFlow

Cash Flow Plot
Primes

Find All Primes Less Than n
MeanSE

Standard Error of Mean
LogSt

Started Logarithmic Transformation and Its Inverse
ParseFormula

Parse a Formula and Create a Model Frame
PlotACF

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

Confidence Intervals for Multinomial Proportions
Median

(Weighted) Median Value
MultMerge

Merge Multiple Data Frames
Order

Distributions of Order Statistics
Rename

Change Names of a Named Object
Outlier

Outlier
StripAttr

Remove Attributes from an Object
PearsonTest

Pearson Chi-Square Test for Normality
VecRot

Vector Rotation (Shift Elements)
Vigenere

Vigenere Cypher
PseudoR2

Pseudo R2 Statistics
RevWeibull

The Reverse Weibull Distribution
PercTable

Percentage Table
RndPairs

Create Pairs of Correlated Random Numbers
ColToOpaque

Equivalent Opaque Color for Transparent Color
RobScale

Robust Scaling With Median and Mad
Measures of Shape

Skewness and Kurtosis
PlotMosaic

Mosaic Plots
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
VonNeumannTest

Von Neumann's Successive Difference Test
PostHocTest

Post-Hoc Tests
SignTest

Sign Test
Depreciation

Several Methods of Depreciation of an Asset
PlotECDF

Empirical Cumulative Distribution Function
SD

(Weighted) Standard Deviation
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
PlotArea

Create an Area Plot
Range

(Robust) Range
RSessionAlive

How Long Has the RSession Been Running?
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
SampleTwins

Sample Twins
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
Sample

Random Samples and Permutations
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
PlotFaces

Chernoff Faces
reorder.factor

Reorder the Levels of a Factor
ShapiroFranciaTest

Shapiro-Francia Test for Normality
SplitAt

Split a Vector Into Several Pieces at Given Positions
SplitPath

Split Path In Drive, Path, Filename
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
StrChop

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

Compute Distances Between Strings
StrExtract

Extract Part of a String
StrTrunc

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

Plot Multiple Density Curves
PlotPairs

Extended Scatterplot Matrices
StrVal

Extract All Numeric Values From a String
StrCountW

Count Words in a String
PlotQQ

QQ-Plot for Any Distribution
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
SplitToCol

Split Data Frame String Column Into Multiple Columns
XLDateToPOSIXct

Convert Excel Dates to POSIXct
d.diamonds

Data diamonds
PlotTernary

Ternary or Triangular Plots
PlotViolin

Plot Violins Instead of Boxplots
PlotWeb

Plot a Web of Connected Points
WrdTableBorders

Draw Borders to a Word Table
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
StuartTauC

Stuart \(\tau_{c}\)
StdCoef

Standardized Model Coefficients
PtInPoly

Point in Polygon
Trim

Trim a Vector
Stamp

Date/Time/Directory Stamp the Current Plot
d.periodic

Periodic Table of Elements
Quantile

Weighted Quantiles
WrdFormatCells

Format Cells Of a Word Table
Recode

Recode a Factor
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
WrdMergeCells

Merges Cells Of a Defined Word Table Range
StrSpell

Spell a String Using the NATO Phonetic or the Morse Alphabet
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
TextContrastColor

Choose Textcolor Depending on Background Color
ZeroIfNA

Replace NAs by 0
ZTest

Z Test for Known Population Standard Deviation
ToLong, ToWide

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

Converts String To a Table
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WrdPageBreak

Insert a Page Break
RomanToInt

Convert Roman Numerals to Integers
d.pizza

Data pizza
TwoGroups

Describe a Variable by a Factor with Two Levels
Rotate

Rotate a Geometric Structure
d.whisky

Classification of Scotch Single Malts
Some

Return Some Randomly Chosen Elements of an Object
%like%

Like Operator
StrAlign

String Alignment
SmoothSpline

Formula Interface For smooth.spline
StrCap

Capitalize the First Letter of a String
UncertCoef

Uncertainty Coefficient
lines.lm

Add a Linear Regression Line
UnirootAll

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

Recyle a List of Elements
ToWrd

Send Objects to Word
RgbToCmy

Conversion Between RGB and CMYK
RunsTest

Runs Test for Randomness
Untable

Recover Original Data From Contingency Table
RgbToCol

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

Round to Multiple
SetNames

Set the Names in an Object
StrPos

Find Position of First Occurrence Of a String
VarCI

Confidence Intervals for the Variance
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
VarTest

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

Get or Set the Font in Word
WrdCellRange

Return the Cell Range Of a Word Table
Str

Compactly Display the Structure of any R Object
Shade

Produce a Shaded Curve
Sort

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

String Abbreviation
SomersDelta

Somers' Delta
StrSplit

Split the Elements of a Character Vector
WrdPlot

Insert Active Plot to Word
XLGetRange

Import Data Directly From Excel
WrdCaption

Insert Caption to Word
XLSaveAs

Save Excel File
XLView

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

System Information
TMod

Comparison Table For Linear Models
TitleRect

Plot Boxed Annotation
TheilU

Theil's U Index of Inequality
StrTrim

Remove Leading/Trailing Whitespace From A String
Unwhich

Inverse Which
StrRev

Reverse a String
YuenTTest

Yuen t-Test For Trimmed Means
day.name

Build-in Constants Extension
WithOptions

Execute Function with Temporary Options
VIF

Variance Inflation Factors
%nin%

Find Matching (or Non-Matching) Elements
DescTools Aliases

Some Aliases Set for Convenience
d.countries

ISO 3166-1 Country Codes
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
%c%

Concatenates Two Strings Without Any Separator
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
axTicks.POSIXct

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

Identify Points In a Plot Using a Formula
wdConst

Word VBA Constants
WrdSaveAs

Open and Save Word Documents
Zodiac

Calculate the Zodiac of a Date
TOne

Create Table One Describing Baseline Characteristics
as.matrix.xtabs

Convert xtabs To matrix
TTestA

Student's t-Test Based on Sample Statistics
ToWrdB

Send Objects to Word and Bookmark Them
ToWrdPlot

Send a Plot to Word and Bookmark it
VanWaerdenTest

van der Waerden Test
lines.loess

Add a Loess or a Spline Smoother
WrdTable

Insert a Table in a Word Document
Var

Variance
WrdStyle

Get or Set the Style in Word
matpow

Matrix Power
power.chisq.test

Power Calculations for ChiSquared Tests
split.formula

Formula Interface for Split