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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

November 20th, 2023

Functions in DescTools (0.99.51)

BinomCI

Confidence Intervals for Binomial Proportions
BinomDiffCI

Confidence Interval for a Difference of Binomials
Bg

Background of a Plot
BinomCIn

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

Binary Tree
Benford

Benford's Distribution
BhapkarTest

Bhapkar Marginal Homogeneity Test
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
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BreuschGodfreyTest

Breusch-Godfrey Test
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
CCC

Concordance Correlation Coefficient
BoxedText

Add Text in a Box to a Plot
BootCI

Simple Bootstrap Confidence Intervals
BoxCox

Box Cox Transformation
Canvas

Canvas for Geometric Plotting
BubbleLegend

Add a Legend to a Bubble Plot
BrierScore

Brier Score for Assessing Prediction Accuracy
CohenD

Cohen's Effect Size
Closest

Find the Closest Value
CochranQTest

Cochran's Q test
CatTable

Function to write a table
CoefVar

Coefficient of Variation
Coalesce

Return the First Element Not Being NA
Clockwise

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

Cochran-Armitage Test for Trend
CohenKappa

Cohen's Kappa and Weighted Kappa
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
ColToRgb

Color to RGB Conversion
ConDisPairs

Concordant and Discordant Pairs
ColToHsv

R Color to HSV Conversion
CombPairs

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

Add a ColorLegend to a Plot
CompleteColumns

Find Complete Columns
ColToHex

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

Convert Colors to Grey/Grayscale
ColumnWrap

Column Wrap
CollapseTable

Collapse Levels of a Table
ConoverTest

Conover's Test of Multiple Comparisons
CountCompCases

Count Complete Cases
Conf

Confusion Matrix And Associated Statistics
CorPolychor

Polychoric Correlation
ConnLines

Add Connection Lines to a Barplot
CountWorkDays

Count Work Days Between Two Dates
ConvUnit

Unit Conversion and Metrix Prefixes
CorPart

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

Pairwise Contrasts
Cor

Covariance and Correlation (Matrices)
CrossN

n-dimensional Vector Cross Product
Cstat

C Statistic (Area Under the ROC Curve)
CourseData

Get HWZ Datasets
Cross

Vector Cross Product
CramerVonMisesTest

Cramer-von Mises Test for Normality
CronbachAlpha

Cronbach's Coefficient Alpha
Datasets for Simulation

Datasets for Probabilistic Simulation
Date Functions

Basic Date Functions
Association measures

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

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

Fast Alternative To The Internal do.call
DescToolsOptions

DescTools Options
Desc

Describe Data
DoBy

Evaluates a Function Groupwise
DivCoef

Rao's Diversity Coefficient
DegToRad

Convert Degrees to Radians and Vice Versa
Divisors

Calculate Divisors
DivCoefMax

Maximal value of Rao's diversity coefficient also called quadratic entropy
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
DigitSum

Calculate Digit Sum
DunnTest

Dunn's Test of Multiple Comparisons
DrawEllipse

Draw an Ellipse
DunnettTest

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

Generate Dummy Codes for a Factor
DrawBand

Draw Confidence Band
DrawArc

Draw Elliptic Arc(s)
Dot

Scalar Product
DrawBezier

Draw a Bezier Curve
DrawRegPolygon

Draw Regular Polygon(s)
DrawCircle

Draw a Circle
EX

Expected Value and Variance
ExtrVal

Distributions of Maxima and Minima
ErrBars

Add Error Bars to an Existing Plot
Entropy

Shannon Entropy and Mutual Information
Factorize

Prime Factorization of Integers
DurbinWatsonTest

Durbin-Watson Test
ExpFreq

Expected Frequencies
FctArgs

Retrieve a Function's Arguments
EtaSq

Effect Size Calculations for ANOVAs
Fibonacci

Fibonacci Numbers
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
Freq

Frequency Table for a Single Variable
Frac

Fractional Part and Maximal Digits of a Numeric Value
FindCorr

Determine Highly Correlated Variables
FixToTable

Convert a Text to a Table
Format

Format Numbers and Dates
Frechet

The Frechet Distribution
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
FisherZ

Fisher-Transformation for Correlation to z-Score
FindColor

Get Color on a Defined Color Range
GeomTrans

Geometric Transformations
GenRandGroups

Generate Random Groups
GetCurrWrd

Get a Handle to a Running Word/Excel Instance
GCD, LCM

Greatest Common Divisor and Least Common Multiple
GeomSn

Geometric Series
GetCalls

Return All Used Functions Within a Function
GenExtrVal

The Generalized Extreme Value Distribution
GetNewWrd

Create a New Word Instance
GenPareto

The Generalized Pareto Distribution
GTest

G-Test for Count Data
GetNewXL

Create a New Excel Instance
HexToCol

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

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

The Gompertz distribution
Gumbel

The Gumbel Distribution
GoodmanKruskalGamma

Goodman Kruskal's Gamma
Gmean

Geometric Mean and Standard Deviation
Herfindahl

Concentration Measures
Gini

Gini Coefficient
GoodmanKruskalTau

Goodman Kruskal's Tau
HmsToSec

Convert h:m:s To/From Seconds
HotellingsT2Test

Hotelling's T2 Test
Hmean

Harmonic Mean and Its Confidence Interval
HexToRgb

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

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

Hosmer-Lemeshow Goodness of Fit Tests
HodgesLehmann

Hodges-Lehmann Estimator of Location
HoeffD

Matrix of Hoeffding's D Statistics
IQRw

The (weighted) Interquartile Range
HuberM

Safe (generalized) Huber M-Estimator of Location
IsValidHwnd

Check Windows Pointer
Some numeric checks

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

Is a Distance Matrix Euclidean?
IsPrime

IsPrime Property
IsDate

Check If an Object Is of Type Date
IsOdd

Checks If An Integer Is Even Or Odd
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
IsDichotomous

Test If a Variable Contains Only Two Unique Values
JarqueBeraTest

(Robust) Jarque Bera Test
InDots

Is a Specific Argument in the Dots-Arguments?
ImputeKnn

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

Exact Version of Jonckheere-Terpstra Test
LOCF

Last Observation Carried Forward
KappaM

Kappa for m Raters
KendallTauB

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

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

Kendall's Coefficient of Concordance W
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
LOF

Local Outlier Factor
Keywords

List Keywords For R Manual Pages
Extremes

Kth Smallest/Largest Values
LeveneTest

Levene's Test for Homogeneity of Variance
LineToUser

Convert Line Coordinates To User Coordinates
Lambda

Goodman Kruskal Lambda
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Label, Unit

Label, Unit Attribute of an Object
LogSt

Started Logarithmic Transformation and Its Inverse
Lc

Lorenz Curve
LinScale

Linear Scaling
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
MHChisqTest

Mantel-Haenszel Chi-Square Test
Mean

(Weighted) Arithmetic Mean
MADCI

Confidence Intervals for Median Absolute Deviations
Mar and Mgp

Set Plot Margins and Distances
Measures of Accuracy

Measures of Accuracy
MeanAD

Mean Absolute Deviation From a Center Point
Logit

Generalized Logit and Inverse Logit Function
List Variety Of Objects

List Objects, Functions Or Data in a Package
MeanCI

Confidence Interval for the Mean
MAD

Median Absolute Deviation
MosesTest

Moses Test of Extreme Reactions
MeanCIn

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

Multiple Gsub
Mode

Mode, Most Frequent Value(s)
Midx

Find the Midpoints of a Numeric Vector
MeanSE

Standard Error of Mean
MeanDiffCI

Confidence Interval For Difference of Means
MixColor

Compute the Convex Combination of Two Colors
MedianCI

Confidence Interval for the Median
Median

(Weighted) Median Value
MoveAvg

Moving Average
Nf

As Numeric Factor
NPV

Short Selection of Financial Mathematical Functions
MultinomCI

Confidence Intervals for Multinomial Proportions
Order

Distributions of Order Statistics
Outlier

Outlier
ORToRelRisk

Transform Odds Ratio to Relative Risk
NemenyiTest

Nemenyi Test
OddsRatio

Odds Ratio Estimation and Confidence Intervals
MultMerge

Merge Multiple Data Frames
ParseSASDatalines

Parse a SAS Dataline Command
PDFManual

Get PDF Manual of a Package From CRAN
PasswordDlg

Password Dialog
PairApply

Pairwise Calculations
PMT

Periodic Payment of an Annuity.
ParseFormula

Parse a Formula and Create a Model Frame
PearsonTest

Pearson Chi-Square Test for Normality
DescTools Palettes

Some Custom Palettes
PageTest

Exact Page Test for Ordered Alternatives
PercTable

Percentage Table
Phrase

Phrasing Results of t-Test
PlotCashFlow

Cash Flow Plot
Permn

Number and Samples for Permutations or Combinations of a Set
PercentRank

Percent Ranks
PlotCandlestick

Plot Candlestick Chart
PlotACF

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

Plot Circular Plot
PlotArea

Create an Area Plot
PlotBubble

Draw a Bubble Plot
PlotBag

Bivariate Boxplot
PlotConDens

Plot Conditional Densities
PlotFdist

Frequency Distribution Plot
PlotDot

Cleveland's Dot Plots
PlotLog

Logarithmic Plot
PlotFaces

Chernoff Faces
PlotFun

Plot a Function
PlotMarDens

Scatterplot With Marginal Densities
PlotLinesA

Plot Lines
PlotECDF

Empirical Cumulative Distribution Function
PlotCorr

Plot a Correlation Matrix
PlotMosaic

Mosaic Plots
PlotPairs

Extended Scatterplot Matrices
PlotMultiDens

Plot Multiple Density Curves
PlotProbDist

Plot Probability Distribution
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
PlotMiss

Plot Missing Data
PlotTernary

Ternary or Triangular Plots
PlotPolar

Plot Values on a Circular Grid
PlotQQ

QQ-Plot for Any Distribution
PlotPyramid

Draw a Back To Back Pyramid Plot
Primes

Find All Primes Less Than n
PoissonCI

Poisson Confidence Interval
PlotVenn

Plot a Venn Diagram
PostHocTest

Post-Hoc Tests
PlotViolin

Plot Violins Instead of Boxplots
PlotWeb

Plot a Web of Connected Points
PlotTreemap

Create a Treemap
PolarGrid

Plot a Grid in Polar Coordinates
PseudoR2

Pseudo R2 Statistics
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
Range

(Robust) Range
PtInPoly

Point in Polygon
RSessionAlive

How Long Has the RSession Been Running?
Quantile

(Weighted) Sample Quantiles
RelRisk

Relative Risk
QuantileCI

Confidence Interval for Any Quantile
Recode

Recode a Factor
Quot

Lagged Quotients
Recycle

Recyle a List of Elements
Rank

Fast Sample Ranks
RgbToCmy

Conversion Between RGB and CMYK
reorder.factor

Reorder the Levels of a Factor
RevCode

Reverse Codes
Rev

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

Create Pairs of Correlated Random Numbers
ColToOpaque

Equivalent Opaque Color for Transparent Color
RevWeibull

The Reverse Weibull Distribution
pRevGumbel

"Reverse" Gumbel Distribution Functions
RgbToCol

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

Change Names of a Named Object
Depreciation

Several Methods of Depreciation of an Asset
SD

(Weighted) Standard Deviation
RomanToInt

Convert Roman Numerals to Integers
Rotate

Rotate a Geometric Structure
RunsTest

Runs Test for Randomness
RobScale

Robust Scaling With Median and Mad
RoundTo

Round to Multiple
SampleTwins

Sample Twins
SaveAs

Saves an R Object Under a Different Name
Sample

Random Samples and Permutations
Measures of Shape

Skewness and Kurtosis
SetAlpha

Add an Alpha Channel To a Color
ShapiroFranciaTest

Shapiro-Francia Test for Normality
SendOutlookMail

Send a Mail Using Outlook as Mail Client
SetNames

Set the Names in an Object
SmoothSpline

Formula Interface For smooth.spline
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Shade

Produce a Shaded Curve
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
SignTest

Sign Test
Some

Return Some Randomly Chosen Elements of an Object
SplitToDummy

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

Split Data Frame String Column Into Multiple Columns
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
Sort

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

Spearman Rank Correlation
SplitAt

Split a Vector Into Several Pieces at Given Positions
SomersDelta

Somers' Delta
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
SplitPath

Split Path In Drive, Path, Filename
StrChop

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

Extract Part of a String
StrCap

Capitalize the First Letter of a String
Stamp

Date/Time/Directory Stamp the Current Plot
StrAlign

String Alignment
Str

Compactly Display the Structure of any R Object
StdCoef

Standardized Model Coefficients
StrCountW

Count Words in a String
StrDist

Compute Distances Between Strings
StrAbbr

String Abbreviation
StrSpell

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

Reverse a String
StrTrim

Remove Leading/Trailing Whitespace From A String
StrPad

Pad a String With Justification
StrIsNumeric

Does a String Contain Only Numeric Data
StrSplit

Split the Elements of a Character Vector
StrTrunc

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

Extract All Numeric Values From a String
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
StrPos

Find Position of First Occurrence Of a String
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
StripAttr

Remove Attributes from an Object
SysInfo

System Information
TTestA

Student's t-Test Based on Sample Statistics
TextContrastColor

Choose Textcolor Depending on Background Color
TOne

Create Table One Describing Baseline Characteristics
StuartTauC

Stuart \(\tau_{c}\)
Strata

Stratified Sampling
TMod

Comparison Table For Linear Models
TextToTable

Converts String To a Table
ToWrd

Send Objects to Word
ToWrdPlot

Send a Plot to Word and Bookmark it
ToWrdB

Send Objects to Word and Bookmark Them
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
ToLong, ToWide

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

Plot Boxed Annotation
TheilU

Theil's U Index of Inequality
TwoGroups

Describe a Variable by a Factor with Two Levels
Trim

Trim a Vector
UncertCoef

Uncertainty Coefficient
Untable

Recover Original Data From Contingency Table
VanWaerdenTest

van der Waerden Test
VecRot

Vector Rotation (Shift Elements)
UnirootAll

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

Confidence Intervals for the Variance
Var

Variance
Unwhich

Inverse Which
Vigenere

Vigenere Cypher
VarTest

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

Variance Inflation Factors
WrdFont

Get or Set the Font in Word
WrdCaption

Insert Caption to Word
WrdFormatCells

Format Cells Of a Word Table
WrdMergeCells

Merges Cells Of a Defined Word Table Range
WrdCellRange

Return the Cell Range Of a Word Table
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
VonNeumannTest

Von Neumann's Successive Difference Test
WithOptions

Execute Function with Temporary Options
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
XLGetRange

Import Data Directly From Excel
WrdPageBreak

Insert a Page Break
XLDateToPOSIXct

Convert Excel Dates to POSIXct
XLSaveAs

Save Excel File
WrdTableBorders

Draw Borders to a Word Table
WrdPlot

Insert Active Plot to Word
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WrdStyle

Get or Set the Style in Word
WrdTable

Insert a Table in a Word Document
WrdSaveAs

Open and Save Word Documents
as.matrix.xtabs

Convert xtabs To matrix
Zodiac

Calculate the Zodiac of a Date
d.diamonds

Data diamonds
ZTest

Z Test for Known Population Standard Deviation
d.periodic

Periodic Table of Elements
XLView

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

Compute Axis Tickmark Locations (For POSIXct Axis)
YuenTTest

Yuen t-Test For Trimmed Means
d.countries

ISO 3166-1 Country Codes
ZeroIfNA

Replace NAs by 0
%like%

Like Operator
DescTools Aliases

Some Aliases Set for Convenience
d.pizza

Data pizza
day.name

Build-in Constants Extension
identify.formula

Identify Points In a Plot Using a Formula
lines.lm

Add a Linear Regression Line
d.whisky

Classification of Scotch Single Malts
split.formula

Formula Interface for Split
wdConst

Word VBA Constants
rSum21

Random Numbers Adding Up to 1
matpow

Matrix Power
%nin%

Find Matching (or Non-Matching) Elements
lines.loess

Add a Loess or a Spline Smoother
%c%

Concatenates Two Strings Without Any Separator
power.chisq.test

Power Calculations for ChiSquared Tests
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
Abstract

Display Compact Abstract of a Data Frame
ABCCoords

Coordinates for "bottomright", etc.
AddMonthsYM

Add a Month to a Date in YearMonth Format
Agree

Raw Simple And Extended Percentage Agreement
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
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
Abind

Combine Multidimensional Arrays
Assocs

Association Measures
Atkinson

Atkinson Index - A Measure of Inequality.
Append

Append Elements to Objects
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Arrow

Insert an Arrow Into a Plot
AxisBreak

Place a Break Mark on an Axis
BartelsRankTest

Bartels Rank Test of Randomness
BarText

Place Value Labels on a Barplot
BarnardTest

Barnard's Unconditional Test
Asp

Get Aspect Ratio of the Current Plot