Package MKdescr

Matthias Kohl

2020-10-18

Introduction

Package MKdescr includes a collection of functions that I found useful in my daily work. It contains several functions for descriptive statistical data analysis. Most of the functions were extracted from package MKmisc. Due to the growing number functions leading to an increasing number of dependencies required for MKmisc, I decided to split the package into smaller packages, where each package offers specific functionality.

We first load the package.

library(MKdescr)

IQR

I implemented function IQrange before the standard function IQR gained the type argument. Since 2010 (r53643, r53644) the function is identical to function IQR.

x <- rnorm(100)
IQrange(x)
## [1] 1.580145
IQR(x)
## [1] 1.580145

It is also possible to compute a standardized version of the IQR leading to a normal-consistent estimate of the standard deviation.

sIQR(x)
## [1] 1.171364
sd(x)
## [1] 1.166849

Mean Absolute Deviation

The mean absolute deviation under the assumption of symmetry is a robust alternative to the sample standard deviation (see Tukey 1960).

meanAD(x)
## [1] 1.160485

Huber-type Skipped Mean and SD

Huber-type skipped mean and SD are robust alternatives to the arithmetic mean and sample standard deviation (see Hampel 1985).

skippedMean(x)
## [1] -0.02153848
skippedSD(x)
## [1] 1.119567

Five Number Summary

There is a function that computes a so-called five number summary which in contrast to function fivenum uses the first and third quartile instead of the lower and upper hinge.

fiveNS(x)
##     Minimum         25%      Median         75%     Maximum 
## -3.49671096 -0.87829941 -0.04384836  0.70184599  2.77827616

Coefficient of Variation (CV)

There are functions to compute the (classical) coefficient of variation as well as two robust variants. In case of the robust variants, the mean is replaced by the median and the SD is replaced by the (standardized) MAD and the (standardized) IQR, respectively [see Arachchige2019].

## 5% outliers
out <- rbinom(100, prob = 0.05, size = 1)
sum(out)
## [1] 7
x <- (1-out)*rnorm(100, mean = 10, sd = 2) + out*25
CV(x)
## [1] 0.3779439
medCV(x)
## [1] 0.26089
iqrCV(x)
## [1] 0.2626669

Signal to Noise Ratio (SNR)

There are functions to compute the (classical) signal to noise ratio as well as two robust variants. In case of the robust variants, the mean is replaced by the median and the SD is replaced by the (standardized) MAD and the (standardized) IQR, respectively.

SNR(x)
## [1] 2.645895
medSNR(x)
## [1] 3.833032
iqrSNR(x)
## [1] 3.807104

Standardized Mean Difference

We compute the standardized mean difference also known as Cohen's und Hogdes' g. In addition, there is a new proposal in case of unequal variances.

n1 <- 100
x <- rnorm(100)
n2 <- 150
y <- rnorm(n2, mean = 3, sd = 2)
## true value
(0-3)/sqrt((1 + n1/n2*2^2)/(n1/n2+1))
## [1] -2.0226
## estimates
## Aoki's e
SMD(x, y)
## bias-corrected SMD 
##           -2.15975
## Hedges' g
SMD(x, y, var.equal = TRUE)
## bias-corrected SMD 
##          -1.919585
## standardized test statistic of Welch's t-test
SMD(x, y, bias.cor = FALSE)
##       SMD 
## -2.166689
## Cohen's d
SMD(x, y, bias.cor = FALSE, var.equal = TRUE)
##       SMD 
## -1.925415

z-Score

There are functions to compute z-score and robust variants of z-score based on median and MAD, respectively median and IQR.

## 10% outliers
out <- rbinom(100, prob = 0.1, size = 1)
sum(out)
## [1] 13
x <- (1-out)*rnorm(100, mean = 10, sd = 2) + out*25
z <- zscore(x)
z.med <- medZscore(x)
z.iqr <- iqrZscore(x)
## mean without outliers (should by close to 0)
mean(z[!out])
## [1] -0.3571298
mean(z.med[!out])
## [1] -0.09164542
mean(z.iqr[!out])
## [1] -0.0869435
## sd without outliers (should by close to 1)
sd(z[!out])
## [1] 0.3983275
sd(z.med[!out])
## [1] 0.8111975
sd(z.iqr[!out])
## [1] 0.7695785

Box- and Whisker-Plot

In contrast to the standard function boxplot which uses the lower and upper hinge for defining the box and the whiskers, the function qboxplot uses the first and third quartile.

x <- rt(10, df = 3)
par(mfrow = c(1,2))
qboxplot(x, main = "1st and 3rd quartile")
boxplot(x, main = "Lower and upper hinge")

The difference between the two versions often is hardly visible.

Generalized Logarithm

The generalized logarithm, which corresponds to the shifted area hyperbolic sine, \[ \log(x + \sqrt{x^2 + 1}) - \log(2) \] may be useful as a variance stabilizing transformation when also negative values are present.

curve(log, from = -3, to = 5)
## Warning in log(x): NaNs wurden erzeugt
curve(glog, from = -3, to = 5, add = TRUE, col = "orange")
legend("topleft", fill = c("black", "orange"), legend = c("log", "glog"))

As in case of function log there is also glog10 and glog2.

curve(log10(x), from = -3, to = 5)
## Warning in eval(expr, envir = ll, enclos = parent.frame()): NaNs wurden erzeugt
curve(glog10(x), from = -3, to = 5, add = TRUE, col = "orange")
legend("topleft", fill = c("black", "orange"), legend = c("log10", "glog10"))

There are also functions that compute the inverse of the generalized logarithm.

inv.glog(glog(10))
## [1] 10
inv.glog(glog(10, base = 3), base = 3)
## [1] 10
inv.glog10(glog10(10))
## [1] 10
inv.glog2(glog2(10))
## [1] 10

Simulate Correlated Variables

To demonstrate Pearson correlation in my lectures, I have written this simple function to simulate correlated variables and to generate a scatter plot of the data.

res <- simCorVars(n = 500, r = 0.8)

cor(res$Var1, res$Var2)
## [1] 0.8094736

Plot TSH, fT3 and fT4 Values

The thyroid function is usually investigated by determining the values of TSH, fT3 and fT4. The function thyroid can be used to visualize the measured values as relative values with respect to the provided reference ranges.

thyroid(TSH = 1.5, fT3 = 2.5, fT4 = 14, TSHref = c(0.2, 3.0),
        fT3ref = c(1.7, 4.2), fT4ref = c(7.6, 15.0))

Generalized and Negative Logarithm as Transformations

We can use the generalized logarithm for transforming the axes in ggplot2 plots (Wickham 2016).

library(ggplot2)
data(mpg)
p1 <- ggplot(mpg, aes(displ, hwy)) + geom_point()
p1

p1 + scale_x_log10()

p1 + scale_x_glog10()

p1 + scale_y_log10()

p1 + scale_y_glog10()

The negative logrithm is for instance useful for displaying p values. The interesting values are on the top. This is for instance used in a so-called volcano plot.

x <- matrix(rnorm(1000, mean = 10), nrow = 10)
g1 <- rep("control", 10)
y1 <- matrix(rnorm(500, mean = 11.25), nrow = 10)
y2 <- matrix(rnorm(500, mean = 9.75), nrow = 10)
g2 <- rep("treatment", 10)
group <- factor(c(g1, g2))
Data <- rbind(x, cbind(y1, y2))
pvals <- apply(Data, 2, function(x, group) t.test(x ~ group)$p.value,
               group = group)
## compute log-fold change
logfc <- function(x, group){
  res <- tapply(x, group, mean)
  log2(res[1]/res[2])
}
lfcs <- apply(Data, 2, logfc, group = group)
ps <- data.frame(pvals = pvals, logfc = lfcs)
ggplot(ps, aes(x = logfc, y = pvals)) + geom_point() +
    geom_hline(yintercept = 0.05) + scale_y_neglog10() +
    geom_vline(xintercept = c(-0.1, 0.1)) + xlab("log-fold change") +
    ylab("-log10(p value)") + ggtitle("A Volcano Plot")

Change Data from Wide to Long

Often it's better to have the data in a long format than in a wide format; e.g., when plotting with package ggplot2. The necessary transformation can be done with function melt.long.

library(ggplot2)
## some random data
test <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10))
test.long <- melt.long(test)
test.long
##           value variable
## x1   0.45829469        x
## x2   0.76453836        x
## x3  -0.86661983        x
## x4  -0.21453344        x
## x5   0.65951265        x
## x6  -0.24253099        x
## x7  -0.22114971        x
## x8   1.78513916        x
## x9  -2.11841131        x
## x10  0.16416589        x
## y1   1.48565701        y
## y2  -0.12373148        y
## y3  -0.29498405        y
## y4   0.67536041        y
## y5  -0.45034784        y
## y6   0.91202346        y
## y7  -1.30647491        y
## y8  -1.67109360        y
## y9  -0.52616056        y
## y10 -0.14213855        y
## z1   1.24072343        z
## z2   1.77961756        z
## z3   0.80972273        z
## z4   0.35011784        z
## z5   0.25429154        z
## z6  -0.74373160        z
## z7  -0.91282380        z
## z8  -1.79435434        z
## z9  -0.26211296        z
## z10  0.04269098        z
ggplot(test.long, aes(x = variable, y = value)) +
  geom_boxplot(aes(fill = variable))

## introducing an additional grouping variable
group <- factor(rep(c("a","b"), each = 5))
test.long.gr <- melt.long(test, select = 1:2, group = group)
test.long.gr
##     group      value variable
## x1      a  0.4582947        x
## x2      a  0.7645384        x
## x3      a -0.8666198        x
## x4      a -0.2145334        x
## x5      a  0.6595127        x
## x6      b -0.2425310        x
## x7      b -0.2211497        x
## x8      b  1.7851392        x
## x9      b -2.1184113        x
## x10     b  0.1641659        x
## y1      a  1.4856570        y
## y2      a -0.1237315        y
## y3      a -0.2949840        y
## y4      a  0.6753604        y
## y5      a -0.4503478        y
## y6      b  0.9120235        y
## y7      b -1.3064749        y
## y8      b -1.6710936        y
## y9      b -0.5261606        y
## y10     b -0.1421385        y
ggplot(test.long.gr, aes(x = variable, y = value, fill = group)) +
  geom_boxplot()

sessionInfo

sessionInfo()
## R version 4.0.3 Patched (2020-10-12 r79333)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Linux Mint 19.3
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/libf77blas.so.3.10.3
## LAPACK: /home/kohlm/RTOP/Rbranch/lib/libRlapack.so
## 
## locale:
##  [1] LC_CTYPE=de_DE.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=de_DE.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=de_DE.UTF-8   
##  [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggplot2_3.3.2 MKdescr_0.6  
## 
## loaded via a namespace (and not attached):
##  [1] knitr_1.30       magrittr_1.5     tidyselect_1.1.0 munsell_0.5.0   
##  [5] colorspace_1.4-1 R6_2.4.1         rlang_0.4.7      dplyr_1.0.2     
##  [9] stringr_1.4.0    tools_4.0.3      grid_4.0.3       gtable_0.3.0    
## [13] xfun_0.18        withr_2.3.0      htmltools_0.5.0  ellipsis_0.3.1  
## [17] yaml_2.2.1       digest_0.6.25    tibble_3.0.3     lifecycle_0.2.0 
## [21] crayon_1.3.4     farver_2.0.3     purrr_0.3.4      vctrs_0.3.4     
## [25] glue_1.4.2       evaluate_0.14    rmarkdown_2.4    labeling_0.3    
## [29] stringi_1.5.3    compiler_4.0.3   pillar_1.4.6     generics_0.0.2  
## [33] scales_1.1.1     pkgconfig_2.0.3

References

Hampel, Frank R. 1985. “The breakdown points of the mean combined with some rejection rules.” Technometrics 27: 95–107.

Tukey, J. W. 1960. “A survey of sampling from contaminated distribution.” In Contributions to Probability and Statistics. Essays in Honor of H. Hotelling., edited by I. Olkin, 448–85. Stanford University Press.

Wickham, Hadley. 2016. ggplot2: Elegant Graphics for Data Analysis. Springer New York.