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 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.6x:

url <- "http://www.omegahat.net/R/bin/windows/contrib/3.5.1/RDCOMClient_0.93-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.35

License

GPL (>= 2)

Issues

Pull Requests

Stars

Forks

Maintainer

Andri Signorell

Last Published

April 30th, 2020

Functions in DescTools (0.99.35)

BarText

Add the Value Labels to a Barplot
Agree

Raw Simple And Extended Percentage Agreement
AddMonthsYM

Add a Month to a Date in YearMonth Format
AndersonDarlingTest

Anderson-Darling Test of Goodness-of-Fit
AscToChar

Convert ASCII Codes to Characters and Vice Versa
Append

Append Elements to Objects
BinomRatioCI

Confidence Intervals for the Ratio of Binomial and Multinomial Proportions
BarnardTest

Barnard's Unconditional Test
BinomDiffCI

Confidence Interval for a Difference of Binomials
Canvas

Canvas for Geometric Plotting
CoefVar

Coefficient of Variation
CohenD

Cohen's Effect Size
BoxCoxLambda

Automatic Selection of Box Cox Transformation Parameter
Arrow

Insert an Arrow Into a Plot
CCC

Concordance Correlation Coefficient
ExpFreq

Expected Frequencies
CartToPol

Transform Cartesian to Polar/Spherical Coordinates and Vice Versa
CorPolychor

Polychoric Correlation
ColToRgb

Color to RGB Conversion
CountCompCases

Count Complete Cases
ColorLegend

Add a ColorLegend to a Plot
CrossN

n-dimensional Vector Cross Product
ColumnWrap

Column Wrap
Cstat

C Statistic (Area Under the ROC Curve)
Abind

Combine Multidimensional Arrays
BartelsRankTest

Bartels Rank Test of Randomness
CochranQTest

Cochran's Q test
CochranArmitageTest

Cochran-Armitage Test for Trend
DivCoefMax

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

Area Under the Curve
DunnettTest

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

Dunn's Test of Multiple Comparisons
BoxedText

Add Text in a Box to a Plot
Base Conversions

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

Calculate Divisors
GetNewXL

Create a New Excel Instance
CohenKappa

Cohen's Kappa and Weighted Kappa
Clockwise

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

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

Binary Tree
CentralValue

Obtain statistic of centrality
CatTable

Function to write a table
BinomCI

Confidence Intervals for Binomial Proportions
CountWorkDays

Count Work Days Between Two Dates
CutQ

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

Find Complete Columns
CollapseTable

Collapse Levels of a Table
Abstract

Display Compact Abstract of a Data Frame
CourseData

Get HWZ Datasets
ColToGrey

Convert Colors to Grey/Grayscale
DegToRad

Convert Degrees to Radians and Vice Versa
Contrasts

Pairwise Contrasts
EtaSq

Effect Size Calculations for ANOVAs
ConvUnit

Unit Conversion and Metrix Prefixes
Date Functions

Basic Date Functions
DoCall

Fast Alternative To The Internal do.call
DoBy

Evaluates a Function Groupwise
DrawBand

Draw Confidence Band
Fibonacci

Fibonacci Numbers
FindCorr

Determine Highly Correlated Variables
FindColor

Get Color on a Defined Color Range
FctArgs

Retrieve a Function's Arguments
DrawArc

Draw Elliptic Arc(s)
DrawBezier

Draw a Bezier Curve
AddMonths

Add a Month to a Date
Dot

Scalar Product
LOF

Local Outlier Factor
GCD, LCM

Greatest Common Divisor and Least Common Multiple
Datasets for Simulation

Datasets for Probabilistic Simulation
DurbinWatsonTest

Durbin-Watson Test
Freq2D

Bivariate (Two-Dimensional) Frequency Distribution
Entropy

Shannon Entropy and Mutual Information
Atkinson

Atkinson Index - A Measure of Inequality.
FixToTable

Convert a Text to a Table
IsDichotomous

Test If a Variable Contains Only Two Unique Values
LogSt

Started Logarithmic Transformation and Its Inverse
FisherZ

Fisher-Transformation for Correlation to z-Score
BrierScore

Brier Score for Assessing Prediction Accuracy
MeanCI

Confidence Interval for the Mean
GiniSimpson

Gini-Simpson Coefficient and Hunter-Gaston Index
Gini

Gini Coefficient
BoxCox

Box Cox Transformation
AxisBreak

Place a Break Mark on an Axis
IsValidHwnd

Check Windows Pointer
BootCI

Simple Bootstrap Confidence Intervals
MeanAD

Mean Absolute Deviation From a Center Point
Hmean

Harmonic Mean and Its Confidence Interval
GetNewWrd

Create a New Word Instance
IsEuclid

Is a Distance Matrix Euclidean?
Freq

Frequency Table for a Single Variable
GenPareto

The Generalized Pareto Distribution
GoodmanKruskalTau

Goodman Kruskal's Tau
Frechet

The Frechet Distribution
HmsToSec

Convert h:m:s To/From Seconds
ICC

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

Goodman Kruskal's Gamma
ColToHex

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

Kendall's Coefficient of Concordance W
BubbleLegend

Add a Legend to a Bubble Plot
KendallTauB

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

Safe (generalized) Huber M-Estimator of Location
ParseFormula

Parse a Formula and Create a Model Frame
ConDisPairs

Concordant and Discordant Pairs
ColToHsv

R Color to HSV Conversion
Conf

Confusion Matrix And Associated Statistics
Some numeric checks

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

Parse a SAS Dataline Command
PlotArea

Create an Area Plot
Label, Unit

Label, Unit Attribute of an Object
MultinomCI

Confidence Intervals for Multinomial Proportions
NPV

Short Selection of Financial Mathematical Functions
Logit

Generalized Logit and Inverse Logit Function
KrippAlpha

Krippendorff's Alpha Reliability Coefficient
AllDuplicated

Index Vector of All Values Involved in Ties
AllIdentical

Test Multiple Objects for Exact Equality
Some

Return Some Randomly Chosen Elements of an Object
LOCF

Last Observation Carried Forward
Cor

Covariance and Correlation (Matrices)
PlotBag

Bivariate Boxplot
PlotPolar

Plot Values on a Circular Grid
GeomSn

Geometric Series
PlotECDF

Empirical Cumulative Distribution Function
SetAlpha

Add an Alpha Channel To a Color
Asp

Get Aspect Ratio of the Current Plot
Assocs

Association Measures
PlotViolin

Plot Violins Instead of Boxplots
PlotPyramid

Draw a Back To Back Pyramid Plot
Benford

Benford's Distribution
Between, Outside

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

Levene's Test for Homogeneity of Variance
BreslowDayTest

Breslow-Day Test for Homogeneity of the Odds Ratios
CorPart

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

Lilliefors (Kolmogorov-Smirnov) Test for Normality
PlotFaces

Chernoff Faces
HodgesLehmann

Hodges-Lehmann Estimator of Location
MixColor

Compute the Convex Combination of Two Colors
InDots

Is a Specific Argument in the Dots-Arguments?
NemenyiTest

Nemenyi Test
Cross

Vector Cross Product
ORToRelRisk

Transform Odds Ratio to Relative Risk
reorder.factor

Reorder the Levels of a Factor
IsDate

Check If an Object Is of Type Date
CronbachAlpha

Cronbach's Coefficient Alpha
DigitSum

Calculate Digit Sum
PMT

Periodic Payment of an Annuity.
HoeffD

Matrix of Hoeffding's D Statistics
DrawRegPolygon

Draw Regular Polygon(s)
JarqueBeraTest

(Robust) Jarque Bera Test
SetNames

Set the Names in an Object
Lc

Lorenz Curve
DivCoef

Rao's Diversity Coefficient
Midx

Find the Midpoints of a Numeric Vector
JonckheereTerpstraTest

Exact Version of Jonckheere-Terpstra Test
Rename

Change Names of a Named Object
PlotWeb

Plot a Web of Connected Points
StdCoef

Standardized Model Coefficients
LineToUser

Convert Line Coordinates To User Coordinates
BreuschGodfreyTest

Breusch-Godfrey Test
PageTest

Exact Page Test for Ordered Alternatives
Median

(Weighted) Median Value
LehmacherTest

Lehmacher's Test for Marginal Homogenity
Closest

Find the Closest Value
RunsTest

Runs Test for Randomness
Phrase

Phrasing Results of t-Test
ExtrVal

Distributions of Maxima and Minima
SD

(Weighted) Standard Deviation
TMod

Comparison Table For Linear Models
PlotCorr

Plot a Correlation Matrix
LinScale

Linear Scaling
Factorize

Prime Factorization of Integers
PlotACF

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

Date/Time/Directory Stamp the Current Plot
MedianCI

Confidence Interval for the Median
PlotPairs

Extended Scatterplot Matrices
PlotMultiDens

Plot Multiple Density Curves
MoveAvg

Moving Average
Primes

Find All Primes Less Than n
ConoverTest

Conover's Test of Multiple Comparisons
PDFManual

Get PDF Manual of a Package From CRAN
Dummy

Generate Dummy Codes for a Factor
PlotDot

Cleveland's Dot Plots
RSessionAlive

How Long Has the RSession Been Running?
MultMerge

Merge Multiple Data Frames
Quot

Lagged Quotients
Outlier

Outlier
ConnLines

Add Connection Lines to a Barplot
PseudoR2

Pseudo R2 Statistics
PlotBubble

Draw a Bubble Plot
Coalesce

Return the First Element Not Being NA
SomersDelta

Somers' Delta
TOne

Create Table One Describing Baseline Characteristics
Association measures

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

Insert Active Plot to Word
Rotate

Rotate a Geometric Structure
PlotCandlestick

Plot Candlestick Chart
RoundTo

Round to Multiple
CramerVonMisesTest

Cramer-von Mises Test for Normality
Depreciation

Several Methods of Depreciation of an Asset
PlotFdist

Frequency Distribution Plot
PlotFun

Plot a Function
GeomTrans

Geometric Transformations
GenExtrVal

The Generalized Extreme Value Distribution
GTest

G-Test for Count Data
lines.loess

Add a Loess or a Spline Smoother
StrDist

Compute Distances Between Strings
TitleRect

Plot Boxed Annotation
StrExtract

Extract Part of a String
DescToolsOptions

DescTools Options
DenseRank

Dense Ranks and Percent Ranks
GetCurrWrd

Get a Handle to a Running Word Instance
Gumbel

The Gumbel Distribution
DrawCircle

Draw a Circle
WoolfTest

Woolf Test For Homogeneity in 2x2xk Tables
SmoothSpline

Formula Interface For smooth.spline
Sample

Random Samples and Permutations
Measures of Shape

Skewness and Kurtosis
DrawEllipse

Draw an Ellipse
SplitPath

Split Path In Drive, Path, Filename
Herfindahl

Concentration Measures
DescTools-package

Tools for Descriptive Statistics and Exploratory Data Analysis
IQRw

The (weighted) Interquartile Range
IdentifyA

Identify Points in Plot Lying Within a Rectangle or Polygon
PlotTernary

Ternary or Triangular Plots
Desc

Describe Data
PlotQQ

QQ-Plot for Any Distribution
KappaM

Kappa for m Raters
Eps

Greenhouse-Geisser And Huynh-Feldt Epsilons
SpreadOut

Spread Out a Vector of Numbers To a Minimum Interval
Lambda

Goodman Kruskal Lambda
Extremes

Kth Smallest/Largest Values
PtInPoly

Point in Polygon
KendallTauA

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

Stuart \(\tau_{c}\)
YuenTTest

Yuen t-Test For Trimmed Means
Measures of Accuracy

Measures of Accuracy
VarCI

Confidence Intervals for the Variance
StrPad

Pad a String With Justification
ErrBars

Add Error Bars to an Existing Plot
Format

Format Numbers and Dates
SysInfo

System Information
MHChisqTest

Mantel-Haenszel Chi-Square Test
Var

Variance
ToLong, ToWide

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

Send Objects to Word
XLView

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

Mode, Most Frequent Value(s)
StrIsNumeric

Does a String Contain Only Numeric Data
WrdBookmark

Return a Handle to a Word Bookmark Given as Name
Frac

Fractional Part and Maximal Digits of a Numeric Value
Gmean

Geometric Mean and Standard Deviation
VecRot

Vector Rotation (Shift Elements)
MosesTest

Moses Test of Extreme Reactions
ToWrdB

Send Objects to Word and Bookmark Them
WrdFont

Get or Set the Font in Word
matpow

Matrix Power
MeanSE

Standard Error of Mean
Recode

Recode a Factor
MeanDiffCI

Confidence Interval For Difference of Means
VarTest

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

Weighted Quantiles
PasswordDlg

Password Dialog
HexToCol

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

Get or Set the Style in Word
HexToRgb

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

Format Cells Of a Word Table
RgbToCol

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

The Gompertz distribution
WrdTable

Insert a Table in a Word Document
Shade

Produce a Shaded Curve
PearsonTest

Pearson Chi-Square Test for Normality
Range

(Robust) Range
PercTable

Percentage Table
axTicks.POSIXct

Compute Axis Tickmark Locations (For POSIXct Axis)
RndPairs

Create Pairs of Correlated Random Numbers
d.whisky

Classification of Scotch Single Malts
HosmerLemeshowTest

Hosmer-Lemeshow Goodness of Fit Tests
ShapiroFranciaTest

Shapiro-Francia Test for Normality
d.countries

ISO 3166-1 Country Codes
Permn

Number and Samples for Permutations or Combinations of a Set
PlotLinesA

Plot Lines
split.formula

Formula Interface for Split
WrdSaveAs

Open and Save Word Documents
PlotLog

Logarithmic Plot
d.pizza

Data pizza
HotellingsT2Test

Hotelling's T2 Test
IsPrime

IsPrime Property
SiegelTukeyTest

Siegel-Tukey Test For Equality In Variability
PlotTreemap

Create a Treemap
power.chisq.test

Power Calculations for ChiSquared Tests
SignTest

Sign Test
PoissonCI

Poisson Confidence Interval
IsOdd

Checks If An Integer Is Even Or Odd
PlotVenn

Plot a Venn Diagram
StrCountW

Count Words in a String
PolarGrid

Plot a Grid in Polar Coordinates
StrChop

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

"Reverse" Gumbel Distribution Functions
Rev

Reverse Elements of a Vector or the Rows/Columns of Matrices, Tables or Data.frames
StrTrunc

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

Fill in NA values with the values of the nearest neighbours
List Variety Of Objects

List Objects, Functions Or Data in a Package
Keywords

List Keywords For R Manual Pages
RobScale

Robust Scaling With Median and Mad
ScheffeTest

Scheffe Test for Pairwise and Otherwise Comparisons
StrTrim

Remove Leading/Trailing Whitespace From A String
Mar and Mgp

Set Plot Margins and Distances
RomanToInt

Convert Roman Numerals to Integers
TTestA

Student's t-Test Based on Sample Statistics
MAD

Median Absolute Deviation
TukeyBiweight

Calculate Tukey's Biweight Robust Mean
Sort

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

Choose Textcolor Depending on Background Color
SortMixed

Sort Strings with Embedded Numbers Based on Their Numeric Order
TwoGroups

Describe a Variable by a Factor with Two Levels
Mean

(Weighted) Arithmetic Mean
StrCap

Capitalize the First Letter of a String
StrAlign

String Alignment
StrRev

Reverse a String
Unwhich

Inverse Which
OddsRatio

Odds Ratio Estimation and Confidence Intervals
StripAttr

Remove Attributes from an Object
PairApply

Pairwise Calculations
SendOutlookMail

Send a Mail Using Outlook as Mail Client
PlotCashFlow

Cash Flow Plot
Order

Distributions of Order Statistics
Untable

Recover Original Data From Contingency Table
StrPos

Find Position of First Occurrence Of a String
PlotCirc

Plot Circular Plot
PlotMarDens

Scatterplot With Marginal Densities
DescTools Palettes

Some Custom Palettes
WithOptions

Execute Function with Temporary Options
WrdCaption

Insert Caption to Word
StuartMaxwellTest

Stuart-Maxwell Marginal Homogeneity Test
WrdCellRange

Return the Cell Range Of a Word Table
WrdTableBorders

Draw Borders to a Word Table
WrdPageBreak

Insert a Page Break
XLDateToPOSIXct

Convert Excel Dates to POSIXct
Trim

Trim a Vector
ToWrdPlot

Send a Plot to Word and Bookmark it
Zodiac

Calculate the Zodiac of a Date
XLGetRange

Import Data Directly From Excel
PlotMiss

Plot Missing Data
VIF

Variance Inflation Factors
Winsorize

Winsorize (Replace Extreme Values by Less Extreme Ones)
VanWaerdenTest

van der Waerden Test
as.matrix.xtabs

Convert xtabs To matrix
XLSaveAs

Save Excel File
PostHocTest

Post-Hoc Tests
PlotMosaic

Mosaic Plots
PlotMonth

Cycle Plot for Seasonal Effects of an Univariate Time Series
Recycle

Recyle a List of Elements
WrdParagraphFormat

Get or Set the Paragraph Format in Word
DescTools Aliases

Some Aliases Set for Convenience
RelRisk

Relative Risk
PowerPoint Interface

Add Slides, Insert Texts and Plots to PowerPoint
d.periodic

Periodic Table of Elements
lines.lm

Add a Linear Regression Line
%like%

Like Operator
%nin%

Find Matching (or Non-Matching) Elements
d.diamonds

Data diamonds
RevWeibull

The Reverse Weibull Distribution
%c%

Concatenates Two Strings Without Any Separator
ColToOpaque

Equivalent Opaque Color for Transparent Color
SampleTwins

Sample Twins
%overlaps%

Determines If And How Extensively Two Date Ranges Overlap
SaveAs

Saves an R Object Under a Different Name
SplitAt

Split a Vector Into Several Pieces at Given Positions
SpearmanRho

Spearman Rank Correlation
Str

Compactly Display the Structure of any R Object
StrLeft, StrRight

Returns the Left Or the Right Part Of a String
StrAbbr

String Abbreviation
Strata

Stratified Sampling
StrSpell

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

Extract All Numeric Values From a String
TheilU

Theil's U Index of Inequality
TextToTable

Converts String To a Table
UncertCoef

Uncertainty Coefficient
Vigenere

Vigenere Cypher
UnirootAll

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

Von Neumann's Successive Difference Test
identify.formula

Identify Points In a Plot Using a Formula
ZTest

Z Test for Known Population Standard Deviation
ZeroIfNA

Replace NAs by 0
WrdInsertBookmark

Insert a Bookmark, Goto Bookmark and Update the Text of a Bookmark
wdConst

Word VBA Constants
day.name

Build-in Constants Extension
WrdMergeCells

Merges Cells Of a Defined Word Table Range