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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

February 3rd, 2021

Functions in DescTools (0.99.40)

Append

Append Elements to Objects
AddMonthsYM

Add a Month to a Date in YearMonth Format
AllDuplicated

Index Vector of All Values Involved in Ties
Abstract

Display Compact Abstract of a Data Frame
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AUC

Area Under the Curve
Abind

Combine Multidimensional Arrays
Agree

Raw Simple And Extended Percentage Agreement
AddMonths

Add a Month to a Date
AllIdentical

Test Multiple Objects for Exact Equality
BinomRatioCI

Confidence Intervals for the Ratio of Binomial Proportions
Arrow

Insert an Arrow Into a Plot
BinomDiffCI

Confidence Interval for a Difference of Binomials
Base Conversions

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

Bartels Rank Test of Randomness
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Atkinson

Atkinson Index - A Measure of Inequality.
BarText

Add the Value Labels to a Barplot
Assocs

Association Measures
Asp

Get Aspect Ratio of the Current Plot
CCC

Concordance Correlation Coefficient
BinomCI

Confidence Intervals for Binomial Proportions
BootCI

Simple Bootstrap Confidence Intervals
BrierScore

Brier Score for Assessing Prediction Accuracy
BoxCox

Box Cox Transformation
BarnardTest

Barnard's Unconditional Test
CohenD

Cohen's Effect Size
BhapkarTest

Bhapkar Marginal Homogeneity Test
AxisBreak

Place a Break Mark on an Axis
CatTable

Function to write a table
Benford

Benford's Distribution
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
BubbleLegend

Add a Legend to a Bubble Plot
BinTree

Binary Tree
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
BreuschGodfreyTest

Breusch-Godfrey Test
Between, Outside

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

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

Column Wrap
CoefVar

Coefficient of Variation
CochranQTest

Cochran's Q test
Canvas

Canvas for Geometric Plotting
Coalesce

Return the First Element Not Being NA
CourseData

Get HWZ Datasets
CombPairs

Get All Pairs Out of One or Two Sets of Elements
Association measures

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

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

Convert Colors to Grey/Grayscale
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
ColorLegend

Add a ColorLegend to a Plot
BoxedText

Add Text in a Box to a Plot
FindColor

Get Color on a Defined Color Range
CohenKappa

Cohen's Kappa and Weighted Kappa
ConoverTest

Conover's Test of Multiple Comparisons
Closest

Find the Closest Value
CollapseTable

Collapse Levels of a Table
DoCall

Fast Alternative To The Internal do.call
ColToHsv

R Color to HSV Conversion
Contrasts

Pairwise Contrasts
Datasets for Simulation

Datasets for Probabilistic Simulation
CorPart

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

Find Complete Columns
Cross

Vector Cross Product
ColToHex

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

Confusion Matrix And Associated Statistics
ConDisPairs

Concordant and Discordant Pairs
CochranArmitageTest

Cochran-Armitage Test for Trend
Date Functions

Basic Date Functions
GetCalls

Return All Used Functions Within a Function
DunnettTest

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

Scalar Product
HmsToSec

Convert h:m:s To/From Seconds
KendallTauB

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

Count Complete Cases
ColToRgb

Color to RGB Conversion
DurbinWatsonTest

Durbin-Watson Test
ConnLines

Add Connection Lines to a Barplot
ConvUnit

Unit Conversion and Metrix Prefixes
Cor

Covariance and Correlation (Matrices)
CountWorkDays

Count Work Days Between Two Dates
DrawCircle

Draw a Circle
DivCoef

Rao's Diversity Coefficient
CutQ

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

DescTools Options
Cstat

C Statistic (Area Under the ROC Curve)
DenseRank

Dense Ranks and Percent Ranks
CorPolychor

Polychoric Correlation
DegToRad

Convert Degrees to Radians and Vice Versa
DivCoefMax

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

The Generalized Pareto Distribution
DrawBezier

Draw a Bezier Curve
CramerVonMisesTest

Cramer-von Mises Test for Normality
Fibonacci

Fibonacci Numbers
CrossN

n-dimensional Vector Cross Product
CronbachAlpha

Cronbach's Coefficient Alpha
Freq

Frequency Table for a Single Variable
Dummy

Generate Dummy Codes for a Factor
DunnTest

Dunn's Test of Multiple Comparisons
Gompertz

The Gompertz distribution
ExpFreq

Expected Frequencies
Format

Format Numbers and Dates
ExtrVal

Distributions of Maxima and Minima
FixToTable

Convert a Text to a Table
Factorize

Prime Factorization of Integers
GeomTrans

Geometric Transformations
Desc

Describe Data
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Entropy

Shannon Entropy and Mutual Information
DrawBand

Draw Confidence Band
DrawArc

Draw Elliptic Arc(s)
DigitSum

Calculate Digit Sum
FctArgs

Retrieve a Function's Arguments
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
DoBy

Evaluates a Function Groupwise
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
GetNewXL

Create a New Excel Instance
Frechet

The Frechet Distribution
Frac

Fractional Part and Maximal Digits of a Numeric Value
GetCurrWrd

Get a Handle to a Running Word Instance
Divisors

Calculate Divisors
GetNewWrd

Create a New Word Instance
JarqueBeraTest

(Robust) Jarque Bera Test
Gumbel

The Gumbel Distribution
GoodmanKruskalTau

Goodman Kruskal's Tau
HodgesLehmann

Hodges-Lehmann Estimator of Location
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
DrawEllipse

Draw an Ellipse
ErrBars

Add Error Bars to an Existing Plot
DrawRegPolygon

Draw Regular Polygon(s)
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
MoveAvg

Moving Average
EtaSq

Effect Size Calculations for ANOVAs
MultMerge

Merge Multiple Data Frames
GoodmanKruskalGamma

Goodman Kruskal's Gamma
HoeffD

Matrix of Hoeffding's D Statistics
KendallTauA

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

Gini Coefficient
FisherZ

Fisher-Transformation for Correlation to z-Score
MeanAD

Mean Absolute Deviation From a Center Point
GenExtrVal

The Generalized Extreme Value Distribution
Some numeric checks

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

Determine Highly Correlated Variables
PlotArea

Create an Area Plot
Gmean

Geometric Mean and Standard Deviation
Extremes

Kth Smallest/Largest Values
InDots

Is a Specific Argument in the Dots-Arguments?
Lc

Lorenz Curve
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
Herfindahl

Concentration Measures
ICC

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

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

Goodman Kruskal Lambda
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
LehmacherTest

Lehmacher's Test for Marginal Homogenity
KappaM

Kappa for m Raters
Label, Unit

Label, Unit Attribute of an Object
GCD, LCM

Greatest Common Divisor and Least Common Multiple
ImputeKnn

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

The (weighted) Interquartile Range
GenRandGroups

Generate Random Groups
GeomSn

Geometric Series
HexToRgb

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

Checks If An Integer Is Even Or Odd
Hmean

Harmonic Mean and Its Confidence Interval
IsEuclid

Is a Distance Matrix Euclidean?
KendallW

Kendall's Coefficient of Concordance W
HotellingsT2Test

Hotelling's T2 Test
GTest

G-Test for Count Data
Keywords

List Keywords For R Manual Pages
LeveneTest

Levene's Test for Homogeneity of Variance
Mar and Mgp

Set Plot Margins and Distances
IsValidHwnd

Check Windows Pointer
IsPrime

IsPrime Property
HuberM

Safe (generalized) Huber M-Estimator of Location
Mean

(Weighted) Arithmetic Mean
PairApply

Pairwise Calculations
IsDichotomous

Test If a Variable Contains Only Two Unique Values
LOCF

Last Observation Carried Forward
LOF

Local Outlier Factor
LogSt

Started Logarithmic Transformation and Its Inverse
LineToUser

Convert Line Coordinates To User Coordinates
Measures of Accuracy

Measures of Accuracy
Outlier

Outlier
MAD

Median Absolute Deviation
MixColor

Compute the Convex Combination of Two Colors
Midx

Find the Midpoints of a Numeric Vector
OddsRatio

Odds Ratio Estimation and Confidence Intervals
Logit

Generalized Logit and Inverse Logit Function
Order

Distributions of Order Statistics
PDFManual

Get PDF Manual of a Package From CRAN
MHChisqTest

Mantel-Haenszel Chi-Square Test
List Variety Of Objects

List Objects, Functions Or Data in a Package
PlotCandlestick

Plot Candlestick Chart
Phrase

Phrasing Results of t-Test
MADCI

Confidence Intervals for Median Absolute Deviations
PlotACF

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

Confidence Interval For Difference of Means
IsDate

Check If an Object Is of Type Date
MultinomCI

Confidence Intervals for Multinomial Proportions
LinScale

Linear Scaling
PlotConDens

Plot Conditional Densities
NPV

Short Selection of Financial Mathematical Functions
PageTest

Exact Page Test for Ordered Alternatives
PMT

Periodic Payment of an Annuity.
MeanCI

Confidence Interval for the Mean
PlotCorr

Plot a Correlation Matrix
Mode

Mode, Most Frequent Value(s)
MosesTest

Moses Test of Extreme Reactions
PasswordDlg

Password Dialog
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
PlotLog

Logarithmic Plot
PlotMarDens

Scatterplot With Marginal Densities
PlotPyramid

Draw a Back To Back Pyramid Plot
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
MeanSE

Standard Error of Mean
MedianCI

Confidence Interval for the Median
PlotQQ

QQ-Plot for Any Distribution
ParseFormula

Parse a Formula and Create a Model Frame
NemenyiTest

Nemenyi Test
Median

(Weighted) Median Value
ORToRelRisk

Transform Odds Ratio to Relative Risk
ParseSASDatalines

Parse a SAS Dataline Command
PlotCashFlow

Cash Flow Plot
PlotBubble

Draw a Bubble Plot
PlotFaces

Chernoff Faces
PlotBag

Bivariate Boxplot
Range

(Robust) Range
DescTools Palettes

Some Custom Palettes
Recode

Recode a Factor
PlotMiss

Plot Missing Data
pRevGumbel

"Reverse" Gumbel Distribution Functions
PearsonTest

Pearson Chi-Square Test for Normality
PlotCirc

Plot Circular Plot
PercTable

Percentage Table
PlotDot

Cleveland's Dot Plots
PlotECDF

Empirical Cumulative Distribution Function
Permn

Number and Samples for Permutations or Combinations of a Set
PlotFdist

Frequency Distribution Plot
RevWeibull

The Reverse Weibull Distribution
RgbToCol

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

Plot Lines
PlotFun

Plot a Function
Quantile

Weighted Quantiles
PlotWeb

Plot a Web of Connected Points
SaveAs

Saves an R Object Under a Different Name
SampleTwins

Sample Twins
RndPairs

Create Pairs of Correlated Random Numbers
PlotMosaic

Mosaic Plots
SplitToCol

Split Data Frame String Column Into Multiple Columns
SplitPath

Split Path In Drive, Path, Filename
PlotMultiDens

Plot Multiple Density Curves
PoissonCI

Poisson Confidence Interval
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
RelRisk

Relative Risk
StrRev

Reverse a String
Stamp

Date/Time/Directory Stamp the Current Plot
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
PseudoR2

Pseudo R2 Statistics
PlotVenn

Plot a Venn Diagram
QuantileCI

Confidence Interval for Any Quantile
RobScale

Robust Scaling With Median and Mad
StripAttr

Remove Attributes from an Object
PlotTernary

Ternary or Triangular Plots
PlotPolar

Plot Values on a Circular Grid
PlotPairs

Extended Scatterplot Matrices
Recycle

Recyle a List of Elements
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
Some

Return Some Randomly Chosen Elements of an Object
PolarGrid

Plot a Grid in Polar Coordinates
ToWrd

Send Objects to Word
PostHocTest

Post-Hoc Tests
RgbToCmy

Conversion Between RGB and CMYK
PlotViolin

Plot Violins Instead of Boxplots
PlotTreemap

Create a Treemap
ToWrdB

Send Objects to Word and Bookmark Them
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
Primes

Find All Primes Less Than n
SetNames

Set the Names in an Object
Rotate

Rotate a Geometric Structure
ColToOpaque

Equivalent Opaque Color for Transparent Color
RSessionAlive

How Long Has the RSession Been Running?
PtInPoly

Point in Polygon
Quot

Lagged Quotients
Rev

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

Reverse Codes
Rename

Change Names of a Named Object
RomanToInt

Convert Roman Numerals to Integers
reorder.factor

Reorder the Levels of a Factor
StrCountW

Count Words in a String
SendOutlookMail

Send a Mail Using Outlook as Mail Client
SD

(Weighted) Standard Deviation
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
RunsTest

Runs Test for Randomness
SetAlpha

Add an Alpha Channel To a Color
UncertCoef

Uncertainty Coefficient
SpearmanRho

Spearman Rank Correlation
VarCI

Confidence Intervals for the Variance
Var

Variance
Depreciation

Several Methods of Depreciation of an Asset
Sort

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

Return the Cell Range Of a Word Table
Sample

Random Samples and Permutations
RoundTo

Round to Multiple
Shade

Produce a Shaded Curve
WrdCaption

Insert Caption to Word
StrAlign

String Alignment
TextToTable

Converts String To a Table
SplitAt

Split a Vector Into Several Pieces at Given Positions
StrAbbr

String Abbreviation
TheilU

Theil's U Index of Inequality
WrdTableBorders

Draw Borders to a Word Table
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
StrChop

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

Shapiro-Francia Test for Normality
StrExtract

Extract Part of a String
SomersDelta

Somers' Delta
StrCap

Capitalize the First Letter of a String
StrIsNumeric

Does a String Contain Only Numeric Data
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
TOne

Create Table One Describing Baseline Characteristics
StrDist

Compute Distances Between Strings
as.matrix.xtabs

Convert xtabs To matrix
TTestA

Student's t-Test Based on Sample Statistics
SysInfo

System Information
StrSpell

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

Choose Textcolor Depending on Background Color
StuartTauC

Stuart \(\tau_{c}\)
ZeroIfNA

Replace NAs by 0
StrTrim

Remove Leading/Trailing Whitespace From A String
WrdTable

Insert a Table in a Word Document
TwoGroups

Describe a Variable by a Factor with Two Levels
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
StrSplit

Split the Elements of a Character Vector
Measures of Shape

Skewness and Kurtosis
SignTest

Sign Test
power.chisq.test

Power Calculations for ChiSquared Tests
Untable

Recover Original Data From Contingency Table
SmoothSpline

Formula Interface For smooth.spline
Zodiac

Calculate the Zodiac of a Date
Trim

Trim a Vector
StrTrunc

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

Compactly Display the Structure of any R Object
StdCoef

Standardized Model Coefficients
TMod

Comparison Table For Linear Models
StrPad

Pad a String With Justification
StrPos

Find Position of First Occurrence Of a String
UnirootAll

Finds many (all) roots of one equation within an interval
d.whisky

Classification of Scotch Single Malts
VonNeumannTest

Von Neumann's Successive Difference Test
WrdFont

Get or Set the Font in Word
Unwhich

Inverse Which
ToWrdPlot

Send a Plot to Word and Bookmark it
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
matpow

Matrix Power
day.name

Build-in Constants Extension
Strata

Stratified Sampling
StrVal

Extract All Numeric Values From a String
%c%

Concatenates Two Strings Without Any Separator
VarTest

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

Get or Set the Style in Word
ToLong, ToWide

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

Plot Boxed Annotation
Vigenere

Vigenere Cypher
VIF

Variance Inflation Factors
VecRot

Vector Rotation (Shift Elements)
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
WrdPlot

Insert Active Plot to Word
WrdFormatCells

Format Cells Of a Word Table
XLDateToPOSIXct

Convert Excel Dates to POSIXct
VanWaerdenTest

van der Waerden Test
XLGetRange

Import Data Directly From Excel
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WrdMergeCells

Merges Cells Of a Defined Word Table Range
lines.lm

Add a Linear Regression Line
YuenTTest

Yuen t-Test For Trimmed Means
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
d.countries

ISO 3166-1 Country Codes
WrdSaveAs

Open and Save Word Documents
WithOptions

Execute Function with Temporary Options
lines.loess

Add a Loess or a Spline Smoother
%nin%

Find Matching (or Non-Matching) Elements
WrdPageBreak

Insert a Page Break
ZTest

Z Test for Known Population Standard Deviation
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
XLSaveAs

Save Excel File
DescTools Aliases

Some Aliases Set for Convenience
XLView

Use MS-Excel as Viewer for a Data.Frame
identify.formula

Identify Points In a Plot Using a Formula
%like%

Like Operator
d.diamonds

Data diamonds
split.formula

Formula Interface for Split
d.periodic

Periodic Table of Elements
d.pizza

Data pizza
wdConst

Word VBA Constants