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

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

September 7th, 2020

Functions in DescTools (0.99.38)

AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
Append

Append Elements to Objects
Abstract

Display Compact Abstract of a Data Frame
AddMonthsYM

Add a Month to a Date in YearMonth Format
Agree

Raw Simple And Extended Percentage Agreement
AUC

Area Under the Curve
AllDuplicated

Index Vector of All Values Involved in Ties
AddMonths

Add a Month to a Date
BarText

Add the Value Labels to a Barplot
AllIdentical

Test Multiple Objects for Exact Equality
Abind

Combine Multidimensional Arrays
Atkinson

Atkinson Index - A Measure of Inequality.
BootCI

Simple Bootstrap Confidence Intervals
BinomRatioCI

Confidence Intervals for the Ratio of Binomial and Multinomial Proportions
Clockwise

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

Association Measures
CompleteColumns

Find Complete Columns
CombPairs

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

Get Aspect Ratio of the Current Plot
CatTable

Function to write a table
Arrow

Insert an Arrow Into a Plot
BoxCox

Box Cox Transformation
AscToChar

Convert ASCII Codes to Characters and Vice Versa
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
BartelsRankTest

Bartels Rank Test of Randomness
BinomCIn

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

Binary Tree
BinomCI

Confidence Intervals for Binomial Proportions
AxisBreak

Place a Break Mark on an Axis
BinomDiffCI

Confidence Interval for a Difference of Binomials
Between, Outside

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

Benford's Distribution
Cstat

C Statistic (Area Under the ROC Curve)
CrossN

n-dimensional Vector Cross Product
Base Conversions

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

Find the Closest Value
BreuschGodfreyTest

Breusch-Godfrey Test
DivCoef

Rao's Diversity Coefficient
DigitSum

Calculate Digit Sum
Canvas

Canvas for Geometric Plotting
ColToRgb

Color to RGB Conversion
CohenKappa

Cohen's Kappa and Weighted Kappa
ColToGrey

Convert Colors to Grey/Grayscale
CollapseTable

Collapse Levels of a Table
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
CoefVar

Coefficient of Variation
CCC

Concordance Correlation Coefficient
BubbleLegend

Add a Legend to a Bubble Plot
BrierScore

Brier Score for Assessing Prediction Accuracy
Coalesce

Return the First Element Not Being NA
Contrasts

Pairwise Contrasts
ConvUnit

Unit Conversion and Metrix Prefixes
DenseRank

Dense Ranks and Percent Ranks
CorPolychor

Polychoric Correlation
CohenD

Cohen's Effect Size
DrawCircle

Draw a Circle
EtaSq

Effect Size Calculations for ANOVAs
DrawEllipse

Draw an Ellipse
ExpFreq

Expected Frequencies
Format

Format Numbers and Dates
DunnettTest

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

DescTools Options
CountCompCases

Count Complete Cases
GeomTrans

Geometric Transformations
DunnTest

Dunn's Test of Multiple Comparisons
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
Desc

Describe Data
CountWorkDays

Count Work Days Between Two Dates
ColumnWrap

Column Wrap
ColorLegend

Add a ColorLegend to a Plot
Frac

Fractional Part and Maximal Digits of a Numeric Value
Hmean

Harmonic Mean and Its Confidence Interval
GetCurrWrd

Get a Handle to a Running Word Instance
CochranQTest

Cochran's Q test
BarnardTest

Barnard's Unconditional Test
CochranArmitageTest

Cochran-Armitage Test for Trend
BoxedText

Add Text in a Box to a Plot
Herfindahl

Concentration Measures
Gumbel

The Gumbel Distribution
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
CourseData

Get HWZ Datasets
IQRw

The (weighted) Interquartile Range
HmsToSec

Convert h:m:s To/From Seconds
DegToRad

Convert Degrees to Radians and Vice Versa
Date Functions

Basic Date Functions
DurbinWatsonTest

Durbin-Watson Test
KendallTauB

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

Hosmer-Lemeshow Goodness of Fit Tests
KendallW

Kendall's Coefficient of Concordance W
JarqueBeraTest

(Robust) Jarque Bera Test
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
HotellingsT2Test

Hotelling's T2 Test
Extremes

Kth Smallest/Largest Values
Lambda

Goodman Kruskal Lambda
Keywords

List Keywords For R Manual Pages
LogSt

Started Logarithmic Transformation and Its Inverse
ConnLines

Add Connection Lines to a Barplot
LeveneTest

Levene's Test for Homogeneity of Variance
LillieTest

Lilliefors (Kolmogorov-Smirnov) Test for Normality
Midx

Find the Midpoints of a Numeric Vector
MedianCI

Confidence Interval for the Median
ImputeKnn

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

Conover's Test of Multiple Comparisons
MHChisqTest

Mantel-Haenszel Chi-Square Test
Logit

Generalized Logit and Inverse Logit Function
Mar and Mgp

Set Plot Margins and Distances
MixColor

Compute the Convex Combination of Two Colors
MultMerge

Merge Multiple Data Frames
PageTest

Exact Page Test for Ordered Alternatives
Association measures

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

Pairwise Calculations
Entropy

Shannon Entropy and Mutual Information
Mode

Mode, Most Frequent Value(s)
MultinomCI

Confidence Intervals for Multinomial Proportions
Order

Distributions of Order Statistics
FindCorr

Determine Highly Correlated Variables
Frechet

The Frechet Distribution
FindColor

Get Color on a Defined Color Range
Freq

Frequency Table for a Single Variable
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
IsOdd

Checks If An Integer Is Even Or Odd
Permn

Number and Samples for Permutations or Combinations of a Set
Outlier

Outlier
InDots

Is a Specific Argument in the Dots-Arguments?
Gini

Gini Coefficient
IsPrime

IsPrime Property
CutQ

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

Krippendorff's Alpha Reliability Coefficient
PercTable

Percentage Table
DoCall

Fast Alternative To The Internal do.call
PlotLog

Logarithmic Plot
PearsonTest

Pearson Chi-Square Test for Normality
PlotLinesA

Plot Lines
CramerVonMisesTest

Cramer-von Mises Test for Normality
DoBy

Evaluates a Function Groupwise
PlotMarDens

Scatterplot With Marginal Densities
Phrase

Phrasing Results of t-Test
LOCF

Last Observation Carried Forward
ColToHex

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

Empirical Cumulative Distribution Function
ConDisPairs

Concordant and Discordant Pairs
ColToHsv

R Color to HSV Conversion
PlotTernary

Ternary or Triangular Plots
Rename

Change Names of a Named Object
RelRisk

Relative Risk
PlotQQ

QQ-Plot for Any Distribution
MADCI

Confidence Intervals for Median Absolute Deviations
reorder.factor

Reorder the Levels of a Factor
PlotFaces

Chernoff Faces
Datasets for Simulation

Datasets for Probabilistic Simulation
Measures of Accuracy

Measures of Accuracy
Depreciation

Several Methods of Depreciation of an Asset
SD

(Weighted) Standard Deviation
Rev

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

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

Draw Confidence Band
Divisors

Calculate Divisors
DrawBezier

Draw a Bezier Curve
ExtrVal

Distributions of Maxima and Minima
PlotMiss

Plot Missing Data
Conf

Confusion Matrix And Associated Statistics
Factorize

Prime Factorization of Integers
Cor

Covariance and Correlation (Matrices)
ORToRelRisk

Transform Odds Ratio to Relative Risk
Primes

Find All Primes Less Than n
PMT

Periodic Payment of an Annuity.
OddsRatio

Odds Ratio Estimation and Confidence Intervals
ShapiroFranciaTest

Shapiro-Francia Test for Normality
GenExtrVal

The Generalized Extreme Value Distribution
PlotFdist

Frequency Distribution Plot
CorPart

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

Cronbach's Coefficient Alpha
Dot

Scalar Product
PlotFun

Plot a Function
Cross

Vector Cross Product
GetNewWrd

Create a New Word Instance
DrawArc

Draw Elliptic Arc(s)
PlotPolar

Plot Values on a Circular Grid
GetNewXL

Create a New Excel Instance
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
ErrBars

Add Error Bars to an Existing Plot
DrawRegPolygon

Draw Regular Polygon(s)
Dummy

Generate Dummy Codes for a Factor
Fibonacci

Fibonacci Numbers
PlotPyramid

Draw a Back To Back Pyramid Plot
FisherZ

Fisher-Transformation for Correlation to z-Score
PlotViolin

Plot Violins Instead of Boxplots
PseudoR2

Pseudo R2 Statistics
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
FixToTable

Convert a Text to a Table
Gmean

Geometric Mean and Standard Deviation
Stamp

Date/Time/Directory Stamp the Current Plot
GCD, LCM

Greatest Common Divisor and Least Common Multiple
HoeffD

Matrix of Hoeffding's D Statistics
FctArgs

Retrieve a Function's Arguments
StrChop

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

Standardized Model Coefficients
PDFManual

Get PDF Manual of a Package From CRAN
GTest

G-Test for Count Data
IsDate

Check If an Object Is of Type Date
HodgesLehmann

Hodges-Lehmann Estimator of Location
GenPareto

The Generalized Pareto Distribution
PlotWeb

Plot a Web of Connected Points
SysInfo

System Information
GeomSn

Geometric Series
VarCI

Confidence Intervals for the Variance
StrSplit

Split the Elements of a Character Vector
TMod

Comparison Table For Linear Models
StrTrim

Remove Leading/Trailing Whitespace From A String
QuantileCI

Confidence Interval for Any Quantile
GoodmanKruskalGamma

Goodman Kruskal's Gamma
StrCountW

Count Words in a String
GoodmanKruskalTau

Goodman Kruskal's Tau
PtInPoly

Point in Polygon
SpearmanRho

Spearman Rank Correlation
SampleTwins

Sample Twins
Quantile

Weighted Quantiles
Quot

Lagged Quotients
Sample

Random Samples and Permutations
VarTest

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

Sort Strings with Embedded Numbers Based on Their Numeric Order
WrdParagraphFormat

Get or Set the Paragraph Format in Word
WrdPageBreak

Insert a Page Break
RndPairs

Create Pairs of Correlated Random Numbers
UnirootAll

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

Kappa for m Raters
Untable

Recover Original Data From Contingency Table
WrdTableBorders

Draw Borders to a Word Table
KendallTauA

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

Linear Scaling
LineToUser

Convert Line Coordinates To User Coordinates
SetNames

Set the Names in an Object
RobScale

Robust Scaling With Median and Mad
XLDateToPOSIXct

Convert Excel Dates to POSIXct
SplitToCol

Split Data Frame String Column Into Multiple Columns
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
Shade

Produce a Shaded Curve
StrAlign

String Alignment
matpow

Matrix Power
lines.loess

Add a Loess or a Spline Smoother
IsEuclid

Is a Distance Matrix Euclidean?
MeanDiffCI

Confidence Interval For Difference of Means
NPV

Short Selection of Financial Mathematical Functions
MeanCI

Confidence Interval for the Mean
HexToCol

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

Test If a Variable Contains Only Two Unique Values
LOF

Local Outlier Factor
Gompertz

The Gompertz distribution
HexToRgb

Convert a Hexstring Color to a Matrix With Three Red/Green/Blue Rows
Label, Unit

Label, Unit Attribute of an Object
VIF

Variance Inflation Factors
Unwhich

Inverse Which
StrCap

Capitalize the First Letter of a String
StrTrunc

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

Nemenyi Test
TextContrastColor

Choose Textcolor Depending on Background Color
TextToTable

Converts String To a Table
StrVal

Extract All Numeric Values From a String
Trim

Trim a Vector
List Variety Of Objects

List Objects, Functions Or Data in a Package
MeanSE

Standard Error of Mean
MosesTest

Moses Test of Extreme Reactions
MoveAvg

Moving Average
MAD

Median Absolute Deviation
HuberM

Safe (generalized) Huber M-Estimator of Location
Median

(Weighted) Median Value
DescTools Palettes

Some Custom Palettes
PlotBag

Bivariate Boxplot
IsValidHwnd

Check Windows Pointer
ICC

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

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

Yuen t-Test For Trimmed Means
XLView

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

Merges Cells Of a Defined Word Table Range
VecRot

Vector Rotation (Shift Elements)
WrdFormatCells

Format Cells Of a Word Table
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Lc

Lorenz Curve
d.countries

ISO 3166-1 Country Codes
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
PlotACF

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

Vigenere Cypher
PlotArea

Create an Area Plot
LehmacherTest

Lehmacher's Test for Marginal Homogenity
PlotBubble

Draw a Bubble Plot
Mean

(Weighted) Arithmetic Mean
ParseFormula

Parse a Formula and Create a Model Frame
PlotMultiDens

Plot Multiple Density Curves
PlotCorr

Plot a Correlation Matrix
PlotPairs

Extended Scatterplot Matrices
WrdCellRange

Return the Cell Range Of a Word Table
PostHocTest

Post-Hoc Tests
RevCode

Reverse Codes
ParseSASDatalines

Parse a SAS Dataline Command
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
MeanAD

Mean Absolute Deviation From a Center Point
PolarGrid

Plot a Grid in Polar Coordinates
PoissonCI

Poisson Confidence Interval
day.name

Build-in Constants Extension
PlotDot

Cleveland's Dot Plots
PasswordDlg

Password Dialog
identify.formula

Identify Points In a Plot Using a Formula
PlotCashFlow

Cash Flow Plot
PlotConDens

Plot Conditional Densities
PlotMosaic

Mosaic Plots
power.chisq.test

Power Calculations for ChiSquared Tests
PlotTreemap

Create a Treemap
PlotCandlestick

Plot Candlestick Chart
PlotCirc

Plot Circular Plot
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
split.formula

Formula Interface for Split
pRevGumbel

"Reverse" Gumbel Distribution Functions
RSessionAlive

How Long Has the RSession Been Running?
PlotVenn

Plot a Venn Diagram
d.pizza

Data pizza
WrdFont

Get or Set the Font in Word
RomanToInt

Convert Roman Numerals to Integers
wdConst

Word VBA Constants
d.whisky

Classification of Scotch Single Malts
WrdSaveAs

Open and Save Word Documents
WrdPlot

Insert Active Plot to Word
Rotate

Rotate a Geometric Structure
SmoothSpline

Formula Interface For smooth.spline
Range

(Robust) Range
Some

Return Some Randomly Chosen Elements of an Object
RgbToCmy

Conversion Between RGB and CMYK
RgbToCol

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

Saves an R Object Under a Different Name
SomersDelta

Somers' Delta
Recode

Recode a Factor
Sort

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

Send a Mail Using Outlook as Mail Client
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
Str

Compactly Display the Structure of any R Object
SetAlpha

Add an Alpha Channel To a Color
StrAbbr

String Abbreviation
StrRev

Reverse a String
StrPos

Find Position of First Occurrence Of a String
Recycle

Recyle a List of Elements
RevWeibull

The Reverse Weibull Distribution
TOne

Create Table One Describing Baseline Characteristics
SplitPath

Split Path In Drive, Path, Filename
StrDist

Compute Distances Between Strings
SplitAt

Split a Vector Into Several Pieces at Given Positions
TTestA

Student's t-Test Based on Sample Statistics
ToLong, ToWide

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

Remove Attributes from an Object
StrExtract

Extract Part of a String
RoundTo

Round to Multiple
RunsTest

Runs Test for Randomness
Strata

Stratified Sampling
ColToOpaque

Equivalent Opaque Color for Transparent Color
ToWrd

Send Objects to Word
Measures of Shape

Skewness and Kurtosis
StrIsNumeric

Does a String Contain Only Numeric Data
VanWaerdenTest

van der Waerden Test
SignTest

Sign Test
TheilU

Theil's U Index of Inequality
TitleRect

Plot Boxed Annotation
TwoGroups

Describe a Variable by a Factor with Two Levels
Var

Variance
WrdStyle

Get or Set the Style in Word
UncertCoef

Uncertainty Coefficient
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
as.matrix.xtabs

Convert xtabs To matrix
Zodiac

Calculate the Zodiac of a Date
WrdTable

Insert a Table in a Word Document
WrdBookmark

Some Functions to Handle MS-Word Bookmarks
%c%

Concatenates Two Strings Without Any Separator
StrPad

Pad a String With Justification
XLGetRange

Import Data Directly From Excel
XLSaveAs

Save Excel File
WrdCaption

Insert Caption to Word
ZTest

Z Test for Known Population Standard Deviation
DescTools Aliases

Some Aliases Set for Convenience
ZeroIfNA

Replace NAs by 0
StrSpell

Spell a String Using the NATO Phonetic or the Morse Alphabet
%nin%

Find Matching (or Non-Matching) Elements
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
StuartTauC

Stuart \(\tau_{c}\)
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
ToWrdB

Send Objects to Word and Bookmark Them
VonNeumannTest

Von Neumann's Successive Difference Test
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
WithOptions

Execute Function with Temporary Options
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
ToWrdPlot

Send a Plot to Word and Bookmark it
%like%

Like Operator
d.periodic

Periodic Table of Elements
d.diamonds

Data diamonds
lines.lm

Add a Linear Regression Line
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability