---
title: "R applications & Exercises - Block 2 (reduced - no solutions)"
subtitle: "STATISTICAL LEARNING IN EPIDEMIOLOGY 2023/2024"
author: "Prof. Giulia Barbati & Paolo Dalena"
date: "19/04/2024"
output:
  html_document:
    toc: true
    toc_float: true
    number_sections: true
    theme: united
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# The randomised controlled trial (RCT) : an example 

```{r,echo=F,warning=F,message=F}
require(psych) #for describeBy
library(rstatix) #for ancova
library(yarrr) # for pirate plots (see below)
library(nlme)
library(lme4)
library(ggpubr)
library(flextable)
library(dplyr)
library(hrbrthemes)
library(ggplot2)

```

The randomised controlled trial (RCT) is regarded by many as the gold standard method for evaluating interventions. We have discussed some of the limitations of this approach that can make it less suitable for evaluating *effectiveness* in the real-world. But in this section we'll look at an example of RCT data and introduce the basic methods that can be used to analyse the results.

A RCT is effective simply because it is designed to counteract all of the systematic biases that can confound the relationship between the exposure and the outcome of interest.

RCTs have become such a bedrock of medical research that standards for reporting them have been developed. The CONSORT flowchart is a useful way of documenting the flow of participants through a trial. CONSORT stands for Consolidated Standards of Reporting Trials, which are endorsed by many medical journals. Indeed, if you plan to publish an intervention study in one of those journals, you are likely to be required to show you have followed the guidelines. The relevant information is available on the 'Enhancing the QUAlity and Transparency Of health Research' [EQUATOR](http://www.equator-network.org) network website. The EQUATOR network site covers not only RCTs but also the full spectrum guidelines of many types of clinical research designs. 


## Statistical analysis of a RCT

Statisticians often complain that researchers will come along with a collection of data and ask for advice as to how to analyse it. Sir Ronald Fisher (one of the most famous statisticians of all time) commented:

> “To consult the statistician after an experiment is finished is often merely to ask him to conduct a post mortem examination. He can perhaps say what the experiment died of.”

-Sir Ronald Fisher, Presidential Address to the First Indian Statistical Congress, 1938.

His point was that very often the statistician would have advised doing something different in the first place, had they been consulted at the outset. Once the data are collected, it may be too late to rescue the study from a fatal flaw.  

The answer to the question "How should I analyse my data?" depends crucially on what hypothesis is being tested. 
In the case of an intervention trial, the hypothesis will usually be "did intervention X make a difference to outcome Y in people with condition Z?"  There is, in this case, a clear null hypothesis – that the intervention was ineffective, and the outcome of the intervention group would have been just the same if it had not been done.  The null hypothesis significance testing approach answers just that question: it tells you how likely your data are if the the null hypothesis was true. To do that, you compare the distribution of outcome scores in the intervention group and the control group. 
In this context we don't just look simply at the difference in means between two groups, usually we consider whether that difference is greater than a pre-specified effect size. 

## Steps to take before data analysis  

- General *sanity check* on dataset - are values within expected range? 
- Check assumptions  
- Plot data to get sense of likely range of results

### Sample dataset with illustrative analysis
To illustrate data analysis, we will use a real dataset that can be retrieved from the [ESRC data archive](https://reshare.ukdataservice.ac.uk/852291/).  We will focus only on a small subset of the data, which comes from an intervention study in which teaching assistants administered an individual reading and language intervention to children with Down syndrome. A *wait-list* RCT design was used, but we will focus here on just the first two phases, in which half the children were randomly assigned to intervention, and the remainder formed a control group.  
Several language and reading measures were included in the study, giving a total of 11 outcomes. Here we will illustrate the analysis with just one of the outcomes - letter-sound coding - which was administered at baseline (t1) and immediately after the intervention (t2). 

```{r ,warning=F,message=F}
library(here)
dsdat <- read.csv(here("datasets", "dse-rli-trial-data-archive.csv"))
dsdat <- dsdat[dsdat$included==1,]
dsdat$group <- as.factor(dsdat$group)
levels(dsdat$group)<-c("Intervention","Control")
dsdat$pretest <- dsdat$letter_sound_t1
dsdat$posttest <- dsdat$letter_sound_t2
pirateplot(posttest~group,theme=1,cex.lab=1.5,data=dsdat, point.o=1, xlab="", ylab="Post-intervention score")

```



Figure shows results on letter-sound coding after one group had received the intervention.  This test had also been administered at baseline, but we will focus first just on the outcome results. 

Raw data should always be inspected prior to any data analysis, in order to just check that the distribution of scores looks sensible. 
One hears of horror stories where, for instance, an error code of 999 got included in an analysis, distorting all the statistics. 
Or where an outcome score was entered as 10 rather than 100. 
Visualising the data is useful when checking whether the results are in the right numerical range for the particular outcome measure.  
The pirate plot (https://www.psychologicalscience.org/observer/yarrr-the-pirates-guide-to-r) is a useful way of showing means and distributions as well as individual data points. 

A related step is to check whether the distribution of the data meets the assumptions of the proposed statistical analysis. 
Many common statistical procedures assume that continuous variables are normally distributed. 
Statistical approaches to checking of assumptions are beyond the scope of this section, but just eyeballing the data is useful, and can detect obvious cases of non-normality, cases of ceiling or floor effects, or *clumpy* data, where only certain values are possible. 
Data with these features may need *special treatment* (as for example the application of scale transformations or non-parametric test). 
For the data in Figure, although neither distribution has an classically normal distribution, we do not see major problems with ceiling or floor effects, and there is a reasonable spread of scores in both groups. To show now only basic methods, we will use parametric approaches (i.e. exploring differences in mean values!)


```{r}
mytab <- psych::describeBy(dsdat$posttest, group=dsdat$group,mat=TRUE,digits=3)
mytab <- mytab[,c(2,4:6)]
colnames(mytab)<-c('Group','N','Mean','SD')
mytab[1:2,1]<-c("Intervention","Control")
ft <- flextable(mytab)
ft
```


The next step is just to compute some basic statistics to get a feel for the effect size. As discussed, the standard deviation (SD) is a key statistic for measuring an intervention effect. In these results, one mean is higher than the other, but there is overlap between the groups.  Statistical analysis gives us a way of quantifying how much confidence we can place in the group difference: in particular, how likely is it that there is no real impact of intervention and the observed results just reflect the play of chance.  In this case we can see that the difference between means is around 6 points and the average SD is around 8, so the effect size (Cohen's _d_) is about .75 - a large effect size for a language intervention. 

### Simple t-test on outcome data  
The simplest way of measuring the intervention effect is therefore to just compare outcome (posttest) measures on a t-test. We can use a one-tailed test with confidence, given that we anticipate outcomes will be better after intervention.  One-tailed tests are often treated with suspicion, because they can be used by researchers engaged in p-hacking, but where we predict a directional effect, they are entirely appropriate and give greater power than a two-tailed test. 
When reporting the result of a t-test, researchers should always report all the statistics: the value of t, the degrees of freedom, the means and SDs, and the confidence interval around the mean difference, as well as the p-value. This not only helps readers understand the magnitude and reliability of the effect of interest: it also allows for the study to readily be incorporated in a meta-analysis. Results from a t-test are shown in the following Table. 
[Note that with a one-tailed test, the confidence interval on one side will extend to infinity: this is because a one-tailed test assumes that the true result is greater than a specified mean value, and disregards results that go in the opposite direction].  

```{r ttestoutcomes,tab.cap='T-test on outcomes',warning=F,message=F}
myt1 <- t.test(dsdat$posttest~dsdat$group,var.equal=T,alternative='greater')

mytabt <- c(round(myt1$statistic,3),round(myt1$parameter,0), round(myt1$p.value,3),round(myt1$estimate[1]-myt1$estimate[2],3),round(myt1$conf.int,3))
mytabt <- as.matrix(mytabt,ncol=6)
mytabt <- as.data.frame(t(mytabt))
colnames(mytabt)<-c('t','df','p','mean diff.','lowerCI','upperCI')
flextable(mytabt)
```


Interpreting this table, we can conclude that data offer evidence in rejecting the null hypothesis, i.e. in the direction of a substantial effect of the intervention. 
The mean difference here can be interpreted as an estimate of the ATE (Average Treatment Effect) in the causal language. 

### T-test on difference scores ?? :-(
The t-test on outcomes is easy to do, but it misses an opportunity to control for one unwanted source of variation, namely individual differences in the initial level of the language measure. For this reason, researchers often prefer to take difference scores: the difference between outcome and baseline measures, and apply a t-test to these. While this had some advantages over reliance on raw outcome measures, it also has disadvantages, because the amount of change that is possible from baseline to outcome is not the same for everyone. A child with a very low score at baseline has more "room for improvement" than one who has an average score. For this reason, analysis of difference scores is not generally recommended.  

### Analysis of covariance on outcome scores  
Rather than taking difference scores, it is preferable to analyse differences in outcome measures after making a statistical adjustment that takes into account the initial baseline scores, using a method known as analysis of covariance or ANCOVA. 
In practice, this method usually gives results that are very similar to those you would obtain from an analysis of difference scores, but the precision, and hence the statistical power is greater.  
However, the data do need to meet certain assumptions of the method. We can for example start with a plot to check if there is a linear relationship between pretest vs posttest scores in both groups - i.e. the points cluster around a straight line.

```{r ds-prepost,fig.cap='Pretest vs posttest scores in the Down syndrome data',warning=F,message=F}
#plot to check linearity by eye
ggscatter(
  dsdat, x = "pretest", y = "posttest",
  color = "group", add = "reg.line"
  )+
  stat_regline_equation(
    aes(label =  paste(..eq.label.., ..rr.label.., sep = "~~~~"), color = group)
    )
```
Inspection of the plot confirms that the relationship between pretest and posttest looks reasonably linear in both groups. 
Note that it also shows that there are rather slightly more children with very low scores at pretest in the control group. This is just a chance finding - the kind of thing that can easily happen when you have relatively small numbers of children randomly assigned to groups.
Randomization does not always guarantees "perfect" balance, especially for small sample size. The important is balance on average...
On average pre-tests scores are not significantly different between the two groups, at is expected from randomization: 

```{r}
mytcheck <- t.test(dsdat$pretest~dsdat$group)
mytcheck
```

Now, let's estimate the ATE (Average Treatment Effect) with only group as a factor, and then instead adding the pretest level: we use different methods (anova test and linear regression) that are substantially equivalent: 

```{r,warning=F,message=F}
aov.1   <- dsdat %>% anova_test(posttest ~ group)
aov.1.full <- aov(posttest ~ group, data=dsdat)
aov.1.full$coefficients # the same as the simple linear regression model 
res.aov <- dsdat %>% anova_test(posttest ~ pretest +group)
resaov.1.full <- aov(posttest ~ pretest +group, data=dsdat)
resaov.1.full$coefficients # the same as the bivariable linear regression model 
mylm1   <- lm(posttest~group,data=dsdat) # is equivalent to run aov.1
mylm    <- lm(posttest~pretest+group,data=dsdat) #is equivalent to run res.aov
```

To better visualize results: 

```{r}
tab1 <- as.data.frame(get_anova_table(aov.1))
tab2 <- as.data.frame(get_anova_table(res.aov))
tab3 <- as.data.frame(summary(mylm1)$coefficients)
tab4 <- as.data.frame(summary(mylm)$coefficients)

source <-c('Intercept','Pretest','Group')
tab4 <- cbind(source,tab4)
colnames(tab4)[5]<-'p'


colnames(tab3)[4]<-'p'

tab1$p <- round(tab1$p,3)
tab2$p <- round(tab2$p,3)
tab3$p <- round(tab3$p,3)
tab4$p <- round(tab4$p,3)


tab1<-tab1[,-6]
tab2<-tab2[,-6]

ft1<-flextable(tab1)
ft1<-set_caption(ft1,'Analysis of posttest only (ANOVA)')
ft1

ft2 <- flextable(tab2)
ft2<-set_caption(ft2,'Analysis adjusted for pretest scores (ANCOVA)')
ft2

# ft3 shows the equivalent results from linear regression
ft3<-flextable(tab3)
ft3<-set_caption(ft3,'Linear regression with group as predictor' )
ft3

ft4<-flextable(tab4)
ft4<-set_caption(ft4,'Linear regression with pretest and group as predictor' )
ft4
```


The table shows the same data analysed first of all by using ANOVA or simple linear regression to compare only the post-test scores (i.e. the ATE effect), then using ANCOVA or the bi-variable linear regression model to adjust scores for the baseline (pretest) values or the linear regression to do the same thing (i.e. the CATE effect: conditional on the pre-test value). 
The *effect size* in the ANOVA/ANCOVA approaches is shown as *ges*, which stands for "generalised eta squared". 
You can notice that the ATE estimated by the regression coefficient of the simple linear regression model with only group as an independent variable is the same as the value of the mean difference reported by the t-test. 
Of note: if you want to deepen this method (ANCOVA),see for example: https://www.datanovia.com/en/lessons/ancova-in-r/.  

# An example of an observational study

As an example of an observational study, consider the *UCBAdmissions* dataset, which is one of the standard R datasets, and refers to the outcome of applications to 6 departments at University of California at Berkeley, by gender. 
The raw original data (4526 observations on 3 variables) have been already cross-tabulated in a 3-dimensional array : for the six largest departments results of admissions are cross-tabulated by sex.


```{r }
UCBAdmissions
```

For convenience in plotting we abbreviate the outcome text:

```{r}
dimnames(UCBAdmissions)[[1]] <- c("Adm", "Rej")
```

The best way to get an overview of multi-way structures is by using the *ftable* function:

```{r}
ftable(UCBAdmissions)
```

Thus, in Department A, 512 males were admitted while 313 were rejected, and so on.

The question of interest is whether there is any bias against admitting female applicants.

The following coerces the contingency table to a data frame:

```{r}
ucb <- as.data.frame(UCBAdmissions)
dim(ucb)
head(ucb)
```
The relationship between the contingency table and the data frame is that each entry in the contingency table becomes a record in the data frame, with a variable *Freq* holding the entry and the classification as variables.

The function *effx* calculates the effects of an exposure on a response, possibly stratified by a stratifying variable, and/or controlled for one or more confounding variables.The function is a wrapper for *glm*. 

Effects are calculated as differences in means for a numerical response, odds ratios/relative risks for a binary response, and rate ratios/rate differences for a failure or count response. The k-1 effects for a categorical exposure with k levels are relative to a baseline which, by default, is the first level. 
The effect of a quantitative numerical exposure is calculated per unit of exposure.The exposure variable can be numeric or a factor, but if it is an ordered factor the order will be ignored.

```{r , warning=FALSE,message = F}
library(Epi)
effx(response=Admit=="Rej", type="binary", exposure=Gender, weight=Freq, data=ucb)
```
Thus, at a first glance, it seems that women are 80% more likely to be rejected, but if we take Department (Dept) into account by adding *control=Dept*, it does not seem to be so: 

```{r , warning=FALSE}
effx(response=Admit=="Rej", type="binary", exposure=Gender, control=Dept,weight=Freq, data=ucb)
```
In fact now it looks like women are 10% less likely to be rejected - though not significantly so (see the confidence interval).

What *effx* does here is to fit a statistical model (logistic regression) for the admission odds that allows each department its own admission odds, but assuming that the admission odds ratio between women and men within each department is the same (i.e. no interaction between Gender and Department). 
And, it is this common odds ratio that is reported. 
What we see here is a classical example of confounding : department is associated with both sex and admission probability, so ignoring department in the analysis will give a distorted picture of the effect of sex per se on admission rates.

We can recover the original data format as follows: 

```{r}
ucb_disagg = ucb[rep(1:nrow(ucb), ucb$Freq), 
                             -grep("Freq", names(ucb))]
ucb_disagg$outcome = ifelse(ucb_disagg$Admit=="Rej", 1,0)
dim(ucb_disagg)
head(ucb_disagg)
```
With this fomat, we can easily apply the *glm* function: 

```{r}
glm.one <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg)
summary(glm.one)

```
As you can see the exponential of the Gender coefficient corresponds to the odds ratio previously estimated. 
Now, if we add in the model also the Department: 

```{r}
glm.two <- glm(outcome ~ Gender+Dept, binomial(link = "logit"), data=ucb_disagg)
summary(glm.two)

```
Again, the exponential of the Gender coefficient is 0.90, as before. Note that being Department a factor variable with 6 levels, one is fixed as the reference value and 5 coefficients are estimated for the other levels vs the reference. 

To recover confidence intervals around the odds ratio we use the standard error of the coefficient's estimate: 

```{r}
lower.b = round(exp(glm.two$coefficients[2]-1.96*0.08085),3)
upper.b = round(exp(glm.two$coefficients[2]+1.96*0.08085),3)
c(round(exp(glm.two$coefficients[2]),3), lower.b, upper.b)
```
If we further look into rejection fractions for women versus men in different departments, replacing *control=Dept* with *strata=Dept*, it seems as if the only Department where there is a substantial sex difference is in A, where women are less likely to be rejected: 

```{r , warning=FALSE}
effx(response=Admit=="Rej", type="binary", exposure=Gender, strata=Dept,weight=Freq, data=ucb)
```

This correspond using glm to : 

```{r}
glm.s1 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="A")
glm.s2 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="B")
glm.s3 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="C")
glm.s4 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="D")
glm.s5 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="E")
glm.s6 <- glm(outcome ~ Gender, binomial(link = "logit"), data=ucb_disagg, subset=Dept=="F")
round(exp(glm.s1$coefficients[2]),3)
round(exp(glm.s2$coefficients[2]),3)
round(exp(glm.s3$coefficients[2]),3)
round(exp(glm.s4$coefficients[2]),3)
round(exp(glm.s5$coefficients[2]),3)
round(exp(glm.s6$coefficients[2]),3)
```
The final analysis shows that there are differences between Departments in the women/men odds ratio of being rejected, although the only one where there is a significantly different rejection rate is in A. 
From the stratified analysis we see that the departments where women are more likely to be rejected are the departments with the highest proportion of women among applicants. 

We can visually appreciate the distribution of rejection rates across Departments by gender using the *mosaicplot*: 


```{r , warning=FALSE}
mosaicplot(UCBAdmissions, sort=3:1, col=TRUE, main="", ylab="", xlab="", off=c(0,1,10))
```

The function basically draws rectangles with an area proportional to each of the entries in the UCBAdmissions.  

Finally, we can make an ad hoc analysis of admissions, excluding Department A to get an indication of whether the other Departments differ with respect to admission odds ratio between men and women: 


```{r , warning=FALSE}
effx(response=Admit=="Rej", type="binary", exposure=Gender, strata=Dept,weight=Freq, 
     data=transform(subset(ucb, Dept!="A"), Dept=factor(Dept)))
```

Note that it is not enough to just restrict the departments not being A, because the variable *Dept* will still be a factor with A as one of the levels. Therefore we must redefine *Dept* to a factor with only the actually occurring levels in the subset. 
We see that there is no indication of differential rejection rates between departments B-F.
However, this p-value is biased since it is based on data where we deliberately excluded a department on the grounds that it was an *outlier* in a specific direction. 

To conclude, when we estimate this kind of association measures from observational data, a lot of attention is devoted to try to disentangle possible confounders or correctly taking into account effect modifiers. 

When a confounder is in fact also an effect modifier, the *strata* analysis is the most correct approach, even if we should take into account that dividing the study population in strata we lose sample size (and therefore statistical power). 

In the regression model approach there is the possibility to explicitly add an interaction term in the equation:


```{r}
glm.int <- glm(outcome ~ Gender+Dept+Gender*Dept, binomial(link = "logit"), data=ucb_disagg)
summary(glm.int)
```

In this case (using all data), we see that a significant interaction is present between Gender and Department: the reference is Dept A; it seems that in Departments C, D, E and F women are more likely to be rejected than men but remind that this is calculated with respect to what happens in Dept A.  Instead in Dept B this there is no significant gender effect with respect to Dept A. 
The *marginal* negative effect for female that we observe in the model (exp(-1.05)) seems therefore only due to the "protective" effect in Dept A.

If we exclude Dept A from the dataset (as before we also did):

```{r}
glm.intNoA <- glm(outcome ~ Gender+Dept+Gender*Dept, binomial(link = "logit"), data=ucb_disagg, subset=Dept!="A")
summary(glm.intNoA)
```

Now as expected we observe no significant marginal effect of gender *at all*. 
The only significant effect in the rejection rates are for the contrasts between Dept C, D, E, and F: they have all a higher risk of rejecting admissions with respect to Dept B.  


# Sample size calculation based on precision

## Estimating the population mean 

Suppose that an estimate is desired of the average price of tablets of a tranquilizer.
A random sample of pharmacies is selected. The estimate is required to be within 10 cents of the true average price with 95% confidence. 
Based on a small pilot study, the standard deviation in price can be estimated as 85 cents. 
How many pharmacies should be randomly selected ? 

We can do this simple calculation not using a particular R library: 

```{r}
z_alpha <- 1.96
sigma   <- 0.85
prec    <- 0.10

n <- (z_alpha^2*sigma^2)/prec^2

sample_size <- ceiling(n)
sample_size
```


As a result, a sample of 278 pharmacies should be taken. 

It is important to note that, to calculate *n*, an anticipated value of
the population standard deviation, is required. 
In the absence of knowledge of this, a rough guide is provided by the largest minus the smallest anticipated values of the measurement of concern divided by 4.

If instead we would to determine the sample size necessary to be 95% confident of estimating the average price of tablets within 5% of the *true value*, and we know, based on pilot survey data, that the *true* price should be about 1 dollar: 

```{r}
z_alpha <- 1.96
sigma   <- 0.85
eps     <- 0.05
hyp_mu  <- 1

n <- (z_alpha^2*sigma^2)/(eps^2*hyp_mu^2)

sample_size <- ceiling(n)
sample_size
```

Hence, 1111 pharmacies should be sampled in order to be 95% confident that the resulting estimate will fall between 0.95 and 1.05 dollars, if the true average price is 1 dollar. 


## Estimating the population proportion (prevalence/cumulative incidence)

The formula below provide the sample size needed under the requirement of population proportion interval estimate at 0.95 confidence level, margin of error *E*, and planned proportion estimate *p*.

Example: Using a 0.50 planned proportion estimate, find the sample size needed to achieve 0.05 margin of error for the estimate at 0.95 confidence level.

```{r }
zstar <- qnorm(.975) 
p = 0.5 
E = 0.05 
n <- zstar^2*p*(1-p) / E^2
minsamp <- ceiling(n)
minsamp
```

## Estimating the confidence interval for an incidence rate

The diet data frame has 337 rows and 14 columns. The data concern a subsample of subjects drawn from larger cohort studies of the incidence of coronary heart disease (CHD). These subjects had all completed a 7-day weighed dietary survey while taking part in validation studies of dietary questionnaire methods. Upon the closure of the MRC Social Medicine Unit, from where these studies were directed, it was found that 46 CHD events had occurred in this group, thus allowing a study of the relationship between diet and the incidence of CHD. We now load the R library required and the dataset. 


```{r}
library(Epi)
data(diet)
```


First of all we want to estimate the overall incidence rate of CHD:we should compute the follow up time in years for each subject in the study. 

```{r}
attach(diet)
y <- cal.yr(dox)-cal.yr(doe)
```

Then we compute the total follow up of the study and the number of incident cases:

```{r}
Y <- sum(y)
D <- sum(chd)
```

Finally, assuming a constant rate, we estimate the incidence rate as follows: 

```{r}
rate <- D/Y
rate
```

And we can use the log(rate) in order to derive the 95% confidence interval:

```{r}
erf <- exp(1.96/sqrt(D))
c(rate, rate/erf, rate*erf)
```
Of note: as we have seen, the likelihood for a constant rate based on the number of events D and the risk time Y is proportional to a Poisson likelihood for the observation D with mean rate*Y. 
Hence we can estimate the rate also using a Poisson regression model; in the model we need the log of the follow up time for each person as the offset variable: 

```{r}
m1 <- glm(chd~1,offset=log(y), family=poisson, data=diet)
ci.exp(m1)
```
the function *glm* with family=Poisson fits a Poisson regression model (see Block 3 for other examples) here with one parameter, the intercept (called '1') while including the log-person-time as a covariate with a fixed coefficient of 1; this is what is called an *offset*.   

Another example using the rate in the original scale: suppose 15 events are observed during 5532 person-years in a given study
cohort.Let's now estimate the underlying incidence rate λ
(in 1000 person-years:  therefore 5.532) and to get an approximate
confidence interval:

```{r}
D <- 15
Y <- 5.532 
rate <- D / Y
SE.rate <- rate/sqrt(D)
c(rate, SE.rate, rate + c(-1.96, 1.96)*SE.rate )
```


Now, if we want to estimate the sample size required in a study to estimate an incidence rate within a pre-specified precision, let's follow this example: 
based on data from previously conducted studies, we expect the rate to be about 50 per 10.000 pyrs. 
We want to determine the size of the sample that will be required to estimate the incidence
rate in that population within ± 5 per 10.000 pyrs.

We are here imposing that the margin of precision should be E=1.96*S.e.(rate), so we can derive the standard error of the rate as: 

```{r}
se.rate <- (5/1.96)
```

then, we can derive the number of cases needed by: 

```{r}
number.cases <- (50/se.rate)**2
number.cases
```

and finally, we need to derive the person-time to observe that number of cases as: 

```{r}
person.years <- number.cases/50
person.years*10000
```

Therefore, we could follow 76832 subjects for one year (or 38416 for two years...etc) in order to observe 384 events and be able to estimate a 95% confidence interval of the required precision.  

# Sample size calculation based on effect size


## Simple random sampling, continuous outcome (means difference)
### Independent samples

We can use the epiR library to do sample size calculations:

```{r warning=FALSE,message=FALSE}
library(epiR)
```

Suppose we wish to test, at the 5% level of significance, the hypothesis
that cholesterol means in a population are equal in two study years against 
the one-sided alternative that the mean is higher in the second of the 
two years.  

Suppose that equal sized samples will be taken in each year, but that these will not from the same individuals (i.e. the two samples are drawn independently).  

Our test is to have a power of 0.95  at detecting a difference of 0.5 mmol/L.
The standard deviation of serum cholesterol is assumed to be 1.4 mmol/L. 

Here we are in a very *standard* situation of random sampling, with two independent samples: the worthwhile difference is 0.5 and since we don't know the actual means in the
groups, we can substitute any values for 'mu1' and 'mu2', so long as the difference is 0.5, in the input of the function:

```{r}
epi.sscompc(treat = 5, control = 4.5, n = NA, sigma = 1.4, power = 0.95, 
            r = 1, design = 1, sided.test = 1, conf.level = 0.95)
```

To satisfy the study requirements 340 individuals need to be tested: 170 in the first year and 170 in the second year. 

This is equivalent to ask for the power of the test, given *n* in each group, using the *power.t.test* formula: 

```{r}
power.t.test(n = 170, delta = 0.5, sd = 1.4,sig.level = 0.05, 
             type = "two.sample",alternative = "one.sided")
```


### Paired samples 

Now, instead of using random sampling of two *independent* groups, we test two times the *same* subjects, for example at 5 years of distance: for sake of simplicity, we assume the same standard deviation as before, even if in this case the standard deviation of the distribution of *differences* should be taken into account: 

```{r}
power.t.test(power=0.95, delta = 0.5, sd = 1.4,sig.level = 0.05, 
             type = "paired",alternative = "one.sided")
```

We need now 87 *pairs* of subjects (the same subject with two measures). 

Note that the sample size requirement is well below that of 170 (per sample) of the unpaired case. 

Provided that the correlation between the *before* and *after* measurements is high and positive (as is likely in practice), pairing will give a considerable *saving* in sample numbers. 

However, there may be costs elsewhere. It may be difficult to keep track of the 87 individuals over the 5-year period. Furthermore, bias may also be present because the individuals concerned may be more health conscious simply by virtue of being studied. This may lead them to (say) consume less saturated fat than other members of the population. Sometimes, moreover, no data can be found from which to calculate the standard deviation of the differences.


## Difference between two proportions 

Let's consider a randomized clinical trial (RCT) to evaluate comparative efficacy of two HIV treatments:

- Primary outcome = % of patients with viral load (VL) below a threshold at 48 week;
- Standard threshold = 60% (p1) of patients in standard treatment are expected to obtain the suppression of VL by the 48 week;
- Expected clinical effect = p2-p1 = 20%

Load the *pwr* library: note that here we are considering the difference between the proportions. 

```{r}
library(pwr)
```

Call the function with the required parameters: the effect size is calculated using a transformation of the difference between proportions (se if interested in details about the formulas used: Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.)):

```{r}
p1=0.8
p2=0.6

h.calc = 2*asin(sqrt(p1))-2*asin(sqrt(p2))

pwr.2p.test(h =h.calc , n =NULL, sig.level =0.05, power =0.80)
```

81 patients per arm should be randomized. 

Note that if you use the one-sided test the required sample size is lower (this is a general finding): 

```{r}
pwr.2p.test(h =h.calc , n =NULL, sig.level =0.05, power =0.80, alternative="greater")
```


Of note, again: samples are sometimes drawn using stratification and/or clustering, in which case a complex sampling design has been used. 
This has a fundamental effect on sample size requirements, compared with the simple random sampling (SRS).
A full discussion is well beyond the scope of this course, but note that in general we should expect sensible stratification to decrease the required sample size (lower variance), but clustering often to increase it, to maintain the same power.


## Simple random sampling, binary outcome, paired samples 

In case of paired binary data (for example: pre-post treatment outcomes) the statistical test to be used is the McNemar's Test. 

The McNemar sample size calculations are not included in the library, so here it is the R code: 

```{r}
pwr.mcnemar <- function(p10, p01, alpha, n, power) {
  pdisc <- p10 + p01
  pdiff <- p10 - p01
  if (missing(power) && !missing(n)) {
    x1 <- (pdiff * sqrt(n) - qnorm(1 - alpha / 2) * sqrt(pdisc)) / 
      sqrt(pdisc - pdiff ^ 2)
    x2 <- (-pdiff * sqrt(n) - qnorm(1 - alpha / 2) * sqrt(pdisc)) / 
      sqrt(pdisc - pdiff ^ 2)
    power <- pnorm(x1) + pnorm(x2)
  } else if (missing(n) && !missing(power)) {
    n <- ((qnorm(1 - alpha / 2) * sqrt(pdisc) + qnorm(power) * 
             sqrt(pdisc - pdiff ^ 2)) / pdiff) ^ 2
  } else {
    stop("Must supply one of `n` or `power`, but not both.")
  }
  c("n" = n, "power" = power)
}

```


Computes sample size or power for McNemar's test for paired categorical data.

p10 : Probability of pre-test success and post-test failure. 

p01 : Probability of pre-test failure and post-test success. 

alpha : Specified significance level

n : Sample size. Cannot be left blank if power is missing.

power:  Statistical power. Cannot be left blank if n is missing.


H0: Both groups have the same success probability.
H1: The success probability is not equal between the Groups.



|          | Post success | Post failure |
|---------:|:-----------:|:------:|
| Pre success    | p11      | p10    | 
| Pre failure | p01       | p00  |



Reference for details:  Connor R. J. 1987. Sample size for testing differences in proportions for the  paired-sample design. Biometrics 43(1):207-211. page 209.

```{r}
pwr.mcnemar(p10=0.20, p01=0.30,alpha=0.05,power=0.90)
```


## Chi-square test of association between categorical variables

We want to see if there's an association between gender and flossing teeth among college students. We randomly sample 100 students (males and females) and ask whether or not they floss daily. We want to carry out a chi-square test of association to determine if there's an association between these two variables. We set our significance level to 0.01. To determine effect size we need to propose an alternative hypothesis, which in this case is a table of proportions. We propose the following:


```{r}
prob <- matrix(c(0.1,0.2,0.4,0.3), ncol=2,
               dimnames = list(c("M","F"),c("Floss","No Floss")))
prob
```

This says we sample even proportions of male and females, but believe that 10% more females floss.

We now use the *ES.w2* function to calculate effect size for chi-square tests of association:

```{r}
ES.w2(prob)
```

Of note: the degrees of freedom of the test are the product of the number of levels df = (2 - 1) * (2 - 1) = 1

And now let's calculate the power:

```{r}
pwr.chisq.test(w = ES.w2(prob), N = 100, df = 1, sig.level = 0.01)
```

Being only 35% this is not a very powerful experiment. 

We can  ask: how many students should I survey if I wish to achieve 90% power?

```{r}
pwr.chisq.test(w = ES.w2(prob), power = 0.9, df = 1, sig.level = 0.01)
```

About 313 students.

If you don't suspect association in either direction, or you don't feel like building a matrix with a specific hypothesis, you can try to use a *conventional* effect size. 

For example, how many students should we sample to detect a *small* effect? [This range of values for the effect size was proposed by Cohen]: 

```{r}
cohen.ES(test = "chisq", size = "small")
```

Therefore:

```{r}
pwr.chisq.test(w = 0.1, power = 0.9, df = 1, sig.level = 0.01)
```


1488 students need to be enrolled in our study. Perhaps more than we thought we might need!

We could consider reframing the question as a simpler two-sample proportion test. 
What sample size do we need to detect a *small* effect in gender on the proportion of students who floss with 90% power and a significance level of 0.01?

```{r}
pwr.2p.test(h = 0.2, sig.level = 0.01, power = 0.9)
```


About 744 per group. 



## Correlation test - test of linear association between continuous variables

A graduate student is investigating the effectiveness of a fitness program. 
She wants to see if there is a correlation between the weight of a participant at the beginning of the program and the participant's weight change after 6 months. 
She suspects there is a a small positive linear relationship between these two quantities (say 0.1). 
She will measure this relationship with the correlation coefficient, r, and conduct a correlation test to determine if the estimated correlation is statistically greater than 0. 
How many subjects does she need to sample to detect this *small* positive (i.e., r > 0) relationship with 80% power and 0.01 significance level?

Here there is nothing tricky about the effect size argument, r. 
It is simply the hypothesized correlation. It can take values ranging from -1 to 1.

```{r}
cohen.ES(test = "r", size = "small")
```

```{r}
pwr.r.test(r = 0.1, sig.level = 0.01, power = 0.8, alternative = "greater")
```

She needs to observe about a 1000 students.

The default is a two-sided test. We specify alternative = "greater" since we believe there is small positive effect.

If she just wants to detect a small effect in either direction (positive or negative correlation), use the default settings of a two.sided test, which we can do by removing the alternative argument from the function:


```{r}
pwr.r.test(r = 0.1, sig.level = 0.01, power = 0.8)
```

Now she needs to observe 1163 students: as always two-sided tests are more "expensive" in terms of sample size.


# Other examples of sample size calculations

## Sample size, power or "detectable" odds ratio for case-control studies

### Example 1

A case-control study of the relationship between smoking and CHD (coronary heart disease) is planned. 
A sample of men with newly diagnosed CHD will be compared for
smoking status with a sample of controls. 
Assuming an equal number of  cases and controls, how many study subject are required to detect an 
odds ratio of 2.0 with 0.90 power using a two-sided 0.05 test? 
Previous surveys have shown that around 0.30 of males without CHD are smokers.

We use the **epi.sscc** function, that require the following arguments:

*OR	= scalar, the expected study odds ratio.

*p0	= scalar, the prevalence of exposure among the controls.

*n	= scalar, the total number of subjects in the study (i.e. the number of cases plus the number of controls).

*power	= scalar, the required study power.

*r	= scalar, the number in the control group divided by the number in the case group.

*phi.coef	= scalar, the correlation between case and control exposures for matched pairs.
Ignored when method = "unmatched".

*design= scalar, the design effect.The design effect is used to take into account the possible presence of clustering in the random sampling of the data. The design effect is a measure of the variability between clusters and is generally calculated as the ratio of the variance calculated assuming a complex sample design divided by the variance calculated assuming simple random sampling.

*sided.test	= Use a two-sided test if you wish to evaluate whether or not the odds of exposure in cases is greater than or less than the odds of exposure in controls. Use a one-sided test to evaluate whether or not the odds of exposure in cases is greater than the odds of exposure in controls.

*conf.level	= scalar, the level of confidence in the computed result.

*method	= a character string defining the method to be used. Options are unmatched or matched.

*fleiss	= logical, indicating whether or not the Fleiss correction should be applied (a continuity correction factor is used when you use a continuous probability distribution to approximate a discrete probability distribution). This argument is ignored when method = "matched".

```{r, warning=F, message=F}
library(epiR)
epi.sscc(OR = 2.0, p0 = 0.30, n = NA, power = 0.90, r = 1, phi.coef = 0, 
         design = 1, sided.test = 2, conf.level = 0.95, method = "unmatched")
```

A total of 376 men need to be sampled: 188 cases and 188 controls.

### Example 2

Suppose we wish to determine the power to detect an odds ratio of 2.0 
using a two-sided 0.05 test when 188 cases and 940 controls
are available (that is, the ratio of controls to cases is 5:1). 
Assume the prevalence of smoking in males without CHD is 0.30.
Here we use the Fleiss correction because we are dealing with an inverse problem (i.e. estimating power given the sample size). 
See for technical details: Fleiss JL et al.,  (2003). Statistical Methods for Rates and Proportions. Wiley, New York, 3rd edition.  


```{r}
n <- 188 + 940
epi.sscc(OR = 2.0, p0 = 0.30, n = n, power = NA, r = 5, phi.coef = 0, 
         design = 1, sided.test = 2, conf.level = 0.95, method = "unmatched", 
         fleiss = TRUE)
```

The power of this study, with the given sample size allocation is 0.99.

### Example 3

We wish to conduct a case-control study to assess whether bladder cancer 
may be associated with past exposure to cigarette smoking. Cases will be 
patients with bladder cancer and controls will be patients hospitalized 
for injury. It is assumed that 20% of controls will be smokers or past 
smokers, and we wish to detect an odds ratio of 2 with power 90%. 
Three controls will be recruited for every case. 

How many subjects need to be enrolled in the study?


```{r}
epi.sscc(OR = 2.0, p0 = 0.20, n = NA, power = 0.90, r = 3, phi.coef = 0, 
         design = 1, sided.test = 2, conf.level = 0.95, method = "unmatched")
```

A total of 619 subjects need to be enrolled in the study: 155 cases and 
464 controls.


## Sample size, power and minimum "detectable" relative risk when comparing binary outcomes

We use the **epi.sscohortc** function, that require the following arguments:

* irexp1	: the expected incidence of the outcome in the exposed group (0 to 1).
* irexp0	: the expected incidence of the outcome in the non-exposed group (0 to 1).
* n	: scalar, defining the total number of subjects in the study (i.e. the number in both the exposed and unexposed groups).
* power	: scalar, the required study power.
* r	: scalar, the number in the exposed group divided by the number in the unexposed group.
* design	: scalar, the estimated design effect.
* sided.test	: use a one- or two-sided test? Use a two-sided test if you wish to evaluate whether or not the outcome incidence risk in the exposed group is greater than or less than the outcome incidence risk in the unexposed group. Use a one-sided test to evaluate whether or not the outcome incidence risk in the exposed group is greater than the outcome incidence risk in the unexposed group.
* conf.level	: scalar, defining the level of confidence in the computed result.


### Example 1

A cohort (exposure-based) study of smoking and coronary heart disease (CHD) in middle aged men is planned. 
A sample of men will be selected at random from the population and those that agree to participate will be asked to complete a questionnaire. 
The follow-up period will be 5 years. 
The investigators would  like to be 0.90 confident of being able to detect when the relative risk of CHD 
is 1.4 for smokers, using a one-sided 0.05 significance test. 
Previous evidence suggests that the incidence rate of death in non-smokers is 413 per 100000 person-years. 
Assuming equal numbers of smokers and non-smokers are  sampled, how many men should be sampled overall?

```{r}
irexp1 = 1.4 * (5 * 413)/100000
irexp0 = (5 * 413)/100000

epi.sscohortc(irexp1 = irexp1, irexp0 = irexp0, n = NA, power = 0.90, r = 1, design = 1, sided.test = 1, conf.level = 0.95)
```

Over a 5-year period the estimated chance of death in the non exposed (irexp0) is  0.02065.
Thus, rounding up to the next highest even number, 12130 men should be sampled (6065
smokers and 6065 nonsmokers).


Since in this design we are extracting a simple random sample from the overall population we could know in advance the expected prevalence of the exposure, and therefore we could also be more flexible, in allowing *unbalancement* between exposed and not exposed. 

The imbalance is set through the parameter *r*. 

If the proportion of men smoking is one-third, then in a random sample we would
expect to find n1 = n/3. Hence n2 = 2n/3 and thus r = n1/n2 = 0.5. Using this new value for r:


```{r}
epi.sscohortc(irexp1 = irexp1, irexp0 = irexp0, n = NA, power = 0.90, r = 0.50, design = 1, sided.test = 1, conf.level = 0.95)
```


Rounding up gives a total sample size requirement of 13544. We would expect that, after
random sampling about a third of these would be nonsmokers. Notice that 13544 is not exactly divisible by 3, but any further rounding up would not be justifiable because we cannot guarantee the
exact proportion of smokers.


### Example 2 

Say, for example, we are only able to enroll 5000 subjects into the study described above. 
What is the minimum and maximum detectable relative risk ?

```{r}
irexp0 = (5 * 413)/100000
epi.sscohortc(irexp1 = NA, irexp0 = irexp0, n = 5000, power = 0.90, 
   r = 1, design = 1, sided.test = 1, conf.level = 0.95)
```

The minimum detectable relative risk > 1 is 1.65. The maximum detectable relative risk < 1 is 0.50.


### Example 3

A study is to be carried out to assess the effect of a new treatment for the reproductive period in dairy cattle. What is the required sample size if we expect the proportion of cows responding in the treatment (exposed) group to be 0.30 and the proportion of cows responding in the control (unexposed) group to be 0.15? 
The required power for this study is 0.80 using a two-sided 0.05 test.

```{r}
epi.sscohortc(irexp1 = 0.30, irexp0 = 0.15, n = NA, power = 0.80, 
   r = 1, design = 1, sided.test = 2, conf.level = 0.95)
```

A total of 242 cows are required: 121 in the treatment (exposed) group and 
121 in the control (unexposed) group.


## YOUR TURN :)

### Problem 1
Calculate the maximum sample size required to estimate the prevalence of
respiratory tract infection, with a precision of 5%, in a target population consisting
of children in a particular region of a developing country.
N.B: An estimate of the population prevalence is not known. However, we can obtain a
range of sample sizes required corresponding to a wide range of values for p, say from
0.1 to 0.9.


### Problem 2
A case-control study is carried out to determine the efficacy of a vaccine for the
prevention of childhood tuberculosis. Assume that 50% of the
controls are not vaccinated. If the number of cases and controls are equal, what
sample size is needed to detect, with 80% power and 5% type I error, an odds ratio
of at least 2 in the target population ?


### Problem 3

A randomised trial is to be conducted comparing two new treatments aimed at
increasing the weights of malnourished children with a control group. 
The minimal worthwhile benefit is an increase in mean weight of 2.5kg, with respect to the controls,  and the standard
deviations of weight changes are believed to be 3.5kg.
What are the required sample sizes, assuming that the control group is twice as
large as each of the two treatment groups and an 80% power is required for each
comparison?

# APPENDIX A: example of initial data analysis

## Introduction

Initial Data Analysis is a crucial first step on the long way to the final result, be it a statistical inference in a scientific paper or a commercial report if you for example are working for a pharma company. 
This long way is often bumpy, highly iterative and time consuming. 
However, IDA might be the most important part of data analysis, because it also helps to generate new/alternative hypothesis, which then determine the final result. 
Thus, we now provide some simplest and effective ways to explore data in R. 
Moreover, we will also show how compare groups with simple statistical tests (WARNING: it is not a matter of a priori defined effect size here, like it is in randomized clinical trials ; we use these tools just for descriptive purposes).
Note that the IDA phase depend heavily on the analysist's experience and knowledge about the "nature" of the dataset; in the following I just put together a series of (uncorrelated) examples in order to give you an overview of the basic tools. 

Let's first of all install some useful libraries:

```{r warning = F,message = F}
library(DataExplorer)       # IDA
library(tidyverse)          # for everything good in R ;)
library(SmartEDA)           # IDA
library(dlookr)             # IDA
library(funModeling)        # IDA
library(ISLR)               # for the Wage dataset
library(ggstatsplot)        # publication ready visualizations with statistical details
library(flextable)          # beautifying tables
library(summarytools)       # IDA
library(psych)              # psychological research: descr. stats, FA, PCA etc.
library(skimr)              # summary stats
library(gtsummary)          # publication ready summary tables
library(moments)            # skewness, kurtosis and related tests
library(ggpubr)             # publication ready data visualization in R
library(PerformanceAnalytics) # econometrics for performance and risk analysis
library(performance)        # Assessment of Regression Models Performance (just for outliers here)
library(PMCMRplus)          # Calculate Pairwise Multiple Comparisons
library(see)                # Model Visualization Toolbox
library(ggcorrplot)         # correlation plots 
library(ggside)             # add metadata to ggplots
```

and then set your working directory: 

```{r}
setwd(here())
```


## Let's start to have a very general idea of a dataset !

We now consider the built-in dataset *airquality* that report daily air quality measurements in New York, from May to September 1973.The data were obtained from the New York State Department of Conservation (ozone data) and the National Weather Service (meteorological data). This is obviously an observational study. 

```{r}
introduce(airquality) %>% t() 
names(airquality)
summary(airquality)
```

This is a data frame with 153 observations on 6 variables. Specifically the 6 variables are:  "Ozone", Solar.R", "Wind",    "Temp",    "Month"   "Day".
We can also plot basic information (from introduce) for the data.

```{r}
plot_intro(airquality)
```


Another useful function is:

```{r}
ft <- status(airquality) %>% flextable()
ft <- colformat_double(
  x = ft,
  digits = 2)
ft
```

For each variable it returns: quantity and percentage of zeros (q_zeros and p_zeros respectively). Same metrics for NA values (q_NA/p_na), and eventually infinite values (q_inf/p_inf). Last two columns indicates data type and quantity of unique values. 

## Explore categorical (discrete) variables

Simple bar plots with frequency distribution of all categorical variables in a dataset are already quite useful, because they provide a quick overview about the meaningfulness of the categorization, and whether there are some typing mistakes in the data. 
{DataExplorer} package provides a simple *plot_bar()* function which does just that. 
However, plotting a target discrete variable by another discrete variable is even more useful. 
It is some sort of a visual contingency table (see the second plot below). 
For this use the *by =* argument and give it the second categorical variable.

Let's use for this example the dataset *diamonds* a dataset containing the prices and other attributes of almost 54,000 diamonds. The variables are as follows:

```{r}
detach("package:yarrr", unload = TRUE) 
# it contains another dataset called 'diamonds', but we want the ggplot2 one

introduce(diamonds) %>% t() 
```
```{r}
summary(diamonds)
```
```{r}
plot_bar(diamonds)
```

This function produce the barplot of the 3 categorical variables in our dataset. 

```{r}
plot_bar(diamonds, by = "cut")
```

This function as explained above produce a stratified barplot, that help us in visualizing a possible relationship across the type of cut with respect to color and clarity. 
The *ExpCatViz* function from {SmartEDA} package also plots each categorical variable with a bar plot, but displays proportions instead of counts.

```{r}
ExpCatViz(diamonds, Page=c(1,3))
```

Now we upload the *Wage* dataset, that report wage and other data for a group of 3000 male workers in the Mid-Atlantic region.

```{r}
introduce(Wage) %>% t() 
summary(Wage)
```

There is a specific research question to be checked here, i.e. if education level is associated with the job.
Namely, the more educated we get, the more likely we’ll end up working with information (e.g. with data...) and the less likely we’ll end up working in a factory. 
Let's just visualize this possible relationship:

```{r}
library(ggplot2)
ExpCatViz(
  Wage %>% 
    select(education, jobclass), 
  target="education")
```


The plot nearly indicates that education level is associated with the job. 
However, taking into account that we are working with a sample of data, without a proper statistical test and a p-value this hypothesis can not be tested and remains … well … a speculation.
Fortunately,the *ggbarstats()* function from {ggstatsplot} package does all the above in one line of code and even goes one step further. 
Namely:

- it counts and calculates percentages for every category,
- it visualizes the “frequency table” in the form of stacked bars 
- it provides numerous statistical details (including p-value!) in addition to visualization, which allows us to make a conclusion or inference already in the exploratory/initial phase of the project! 


```{r}
ggbarstats(
  data  = Wage, 
  x     = jobclass, 
  y     = education, 
  label = "both")
```


How do you interpret the various statistical tests reported? 

[Note that I'm here interested just in the frequentist tests approaches, i.e. the global Pearson's chi-squared test and the proportion test for x variable (jobclass) for each level of y (education)].


## Explore numerical variables

Descriptive statistics (location, dispersion and shape parameters) are usually needed to describe numerical variables, or for a numeric variable separated in groups by some categorical variable, like control & treatment. 
Three functions from {dlookr} package, namely *describe()*, *univar_numeric()* and *diagnose_numeric()* are able do it. 
Be careful with the *describe()* function though, because it also exists in {Hmisc} and {psych} packages too. 
Thus, in order to avoid the confusion, simply write *dlookr::* in front of *describe()* function, which then provides the most common descriptive stats, like counts, number o missing values, mean, standard deviation, standard error of the mean, IQR, skewness, kurtosis and 17 quantiles.

Now we explore the dataset *iris* that is the famous (Fisher's) iris data set with the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.

```{r}
introduce(iris) %>% t() 
summary(iris)
```


```{r}

ft1 <- dlookr::describe(iris) %>% flextable()
ft1 <- colformat_double(
  x = ft1,
  digits = 2)
ft1

#save_as_docx(ft1, path="ft1.docx")
```


```{r}
hist(iris$Sepal.Length)
```

Here, we can also see how useful can be the collaboration of {dlookr} with {tidyverse} packages, like {dplyr} and its *group_by()* function which calculates descriptive statistics per group. 
And if you don’t need such a monstrous table, but only want to have the median instead of 17 quantiles, use *univar_numeric()* function.

```{r}

ft2 <- iris %>% 
  group_by(Species) %>% 
  univar_numeric()

knitr::kable(ft2, digits=2)
```

The *diagnose_numeric()* function reports the usual 5-number-summary (which is actually a box-plot in a table form) and the number of zeros, negative values and outliers:

```{r}
ft3 <- iris %>% 
  diagnose_numeric() %>% 
  flextable()
ft3 <- colformat_double(
  x = ft3,
  digits = 2)
ft3
```

{SmartEDA} with its *ExpNumStat()* function also provides a very comprehensive descriptive statistics table. 
Moreover we can choose to describe the whole variables, grouped variables, or even both at the same time. If we call the argument *by =* with a big letter A, we’ll get statistics for every numeric variable in the dataset. The big G delivers descriptive stats per GROUP, but we’ll need to specify a group in the next argument *gr =*. 
Using GA, would give you both. We can also specify the quantiles we need and identify the lower hinge, upper hinge and number of outliers, if we want to.

```{r}
ft4 <- ExpNumStat(iris, by="A", Outlier=TRUE, Qnt = c(.25, .75), round = 2) %>% flextable()
ft4 <- colformat_double(
  x = ft4,
  digits = 2)
ft4
```

```{r}
ft5 <- ExpNumStat(iris, by="G", gp="Species", Outlier=TRUE, Qnt = c(.25, .75), round = 2) %>% flextable()
ft5 <- colformat_double(
  x = ft5,
  digits = 2)
ft5
```

```{r}

ft6 <- ExpNumStat(iris, by="GA", gp="Species", Outlier=TRUE, Qnt = c(.25, .75), round = 2) %>% flextable()
ft6 <- colformat_double(
  x = ft6,
  digits = 2)
ft6
```

{summarytools} and {psych} packages also provide useful tables with descriptive stats:

```{r}
iris %>% 
  group_by(Species) %>% 
  descr()
```

```{r}
describeBy(iris,
           iris$Species)
```


## Explore the distribution's shape of numerical variables

Why do we need to explore the distribution of numerical variables? 

Well, many statistical tests depend on *symmetric* and (more or less..) *normally distributed* data. 

Histograms and density plots allow us the first glimpse on the data. 
For example, {DataExplorer} package provides very intuitive functions for getting histogram and density plots of all continuous variables at once, namely *plot_histogram()* and *plot_density()*. Moreover, they both collaborate perfectly with {dplyr} package, which is always a good think! 


```{r}
plot_histogram(Wage)
```


```{r}
plot_density(Wage)
```


```{r}
# works perfectly with dplyr!
airquality %>% 
  select(Ozone, Wind) %>% 
  plot_density()
```


So, looking at two variables displayed above, we can see that Wind is distributed kind of symmetric while Ozone is not. But how can we measure the symmetry of data? And when is data symmetric enough?


### Skewness

Skewness measures the lack of symmetry. A data is symmetric if it looks the same to the left and to the right of the central point (usually: the mean!). 
The skewness for a perfectly normal distribution is zero, so that any symmetric data should have a skewness near zero. Positive values for the skewness indicate data that are skewed to the right, which means that most of the data is actually on the left side of the plot, like on our Ozone plot. 
Negative values would then indicate skewness to the left, with most of data being on the right side of the plot. Using *skewness()* function from {moments} package shows that the skewness of Ozone is indeed positive and is far away from the zero, which suggests that Ozone is not-normally distributed.

General guidelines for the measure of skewness are following:

- if skewness is less than -1 or greater than 1, the distribution is highly skewed,
- if skewness is between -1 and -0.5 or between 0.5 and 1, the distribution is moderately skewed 
- if skewness is between -0.5 and 0.5, the distribution is approximately symmetric

But here again, *how far from zero* would be far enough in order to say that data is significantly skewed and therefore not-normally distributed?

Well, D’Agostino skewness test from {moments} package provides a p-value for that. For instance, a p-value for Ozone is small, which rejects the Null Hypothesis about not-skewed data, saying that Ozone data is actually significantly skewed. In contrast the p-value for Wind is above the usual significance threshold of 0.05, so that we can treat Wind data as not-skewed, and therefore - normal. 

Always pay attention the the fact that p-values depend heavily on the sample size: small deviations in large samples could be significant, large deviations in small samples could be not!!!

```{r}
skewness(airquality$Ozone, na.rm = T) 
skewness(airquality$Wind, na.rm = T) 
agostino.test(airquality$Ozone)
agostino.test(airquality$Wind)
```

So, there is a strong evidence for Ozone, instead a p value above the standard threshold of 5% is observed for Wind, therefore there is no enough evidence to reject the null hypothesis of gaussianity for Wind. 


### Kurtosis

Kurtosis is a measure of heavy tails, or outliers present in the distribution. The kurtosis value for a normal distribution is around three. Here again, we’d need to do a proper statistical test which will give us a p-value saying whether kurtosis result is significantly far away from three. {moments} package provides Anscombe-Glynn kurtosis test for that. For instance, Ozone has a Kurtosis value of 4.1 which is significantly far away from 3, indicating a not normally distributed data and probable presence of outliers. In contrast, the Kurtosis for Wind is around 3 and the p-value tells us that Wind distribution is fine.


```{r}
anscombe.test(airquality$Ozone)
anscombe.test(airquality$Wind)
```


### Check the normality of a distribution

Now, finally, the normality of the distribution itself can be checked. It’s useful, because it helps us to determine a correct statistical test. 
For instance, if the data is normally distributed, we should use *parametric* tests, like t-test or ANOVA. 
If, however, the data is not-normally distributed, we should use *non-parametric* tests, like Mann-Whitney or Kruskal-Wallis. 
So, the normality check is not just another strange statistical paranoia, but it’s actually helpful.
There are two main ways to check the normality: using a *Quantile-Quantile plot* and using a proper statistical test. And... we need them both!

{DataExplorer} package provides a simple and elegant *plot_qq()* function, which produces Quantile-Quantile plots either for all continuous variables in the dataset, or, even for every group of a categorical variable, if the argument *by =* is specified. The qq-plot shows on the x-axis the theoretical quantile you would expect from a standard normal distribution. The y-axis show the observed quantiles.If both sets of quantiles came from the same (standardized gaussian) distribution, we should see the points forming a line that's roughly straight.


```{r}
plot_qq(iris)
```


```{r}
plot_qq(iris, by = "Species")
```


Cool, right? But *plot_normality()* function from {dlookr} package visualizes not only Quantile-Quantile plot, but also the histogram of the original data and histograms of two of the most common *normalizing* transformations of data, namely log & square root transformations, in case the normality assumption was not met. This allows us to see, whether transformation actually improves something or not, because its not always the case. Here we could also use {dplyr} syntax in order to quickly visualize several groups.


```{r}
iris %>%
  group_by(Species) %>%
  plot_normality(Petal.Length)
```


However, we still don’t know, when our data is normally distributed. As we have said, the QQ-plot can be interpreted in following way: if points are situated close to the diagonal line, the data is probably normally distributed. 
But here we go again! How *close* is close enough? It’s actually very subjective! That is why, I like to explore QQ-plots using {ggpubr} package, which goes one step further and shows confidence intervals, which help to decide whether the deviation from normality is big or not. 
For example, if all or most of the data fall into these confidence intervals, we can conclude that data is normally distributed. However, in order to to be sure, we’d need to actually do a *statistical test*, which is in most cases a Shapiro-Wilk Normality test (but always remember here the sample size issue!).

```{r warning=FALSE}
ggqqplot(iris, "Sepal.Length", facet.by = "Species")
```

Very intuitive *normality()* function from {dlookr} package performs the Shapiro-Wilk Normality test with every numeric variable in the dataset. 
For example, we have seen that variable Wind in airquality dataset has a nice skewness and kurtosis, so, it suppose to be normally distributed, while variable Ozone suppose to be not-normally distributed, right? And indeed, *normality()* function totally confirms that.

```{r}
normality(airquality) %>%
  mutate_if(is.numeric, ~round(., 3)) %>% 
  flextable()
```

Moreover, via the collaboration with {dplyr} package and it’s *group_by()* function we can conduct around 2000 normality tests in seconds and only few lines of code:


```{r}
diamonds %>%
  group_by(cut, color, clarity) %>%
  normality()
```

So, why don’t we just do our Shapiro-Wilk tests all the time and forget all those skewnesses and visualizations? 
Well, because given enough data, as we said before, due to the relationship between test power and sample size, the Shapiro-Wilk test will *always* find some non-normality even in perfectly symmetric bell-shaped data... 
Here is an example of a vector with less than 300 values, where the Shapiro-Wilk test shows highly significant deviation from normality, while a density plot shows a bell curved data distribution. 
Moreover, tests or skewness, kurtosis and Quantile-Quantile plot all indicate normally distributed data. 
Thus, it’s always better to check several options before making a final conclusion about normality of the data.

```{r}
bla <- Wage %>%
  filter(education == "1. < HS Grad") %>% 
  select(age)

normality(bla) %>% flextable()
```


```{r}
plot_density(bla)
summary(bla)
```


```{r}
agostino.test(bla$age)
anscombe.test(bla$age)
```

```{r warning=FALSE}
ggqqplot(bla$age)
```

## Explore numerical variables with Box-Plots

When numerical variables are not normally distributed, is useful to visualize their box-plots. 
Using the intuitive *plot_boxplot()* function from {DataExplorer} package with an argument *by =* which specifies a grouping, variable, will put all groups of all numeric variables into the boxes. 
Such visualization however immediately creates the next question - do these groups differ significantly? We can not tell that from just staring at the picture…

```{r}
plot_boxplot(iris, by = "Species")
```


or:


```{r}
ExpNumViz(iris, target = "Species", Page = c(2,2))
```

If we use a *ggbetweenstats()* function from {ggstatsplot} package, we’d check hypotheses using only a few intuitive arguments. For instance:

- data
- x axis, where we determine the grouping categorical variable
- y axis, where we have our numeric variable of interest 
- the type of the test [which I would always for caution set to *non-parametric* for initial analysis]


This simple code not only provides you with a p-value which tells you whether there are *significant* differences between groups, but also conducts a correct multiple pairwise comparisons to see between which groups exactly these differences are. *ggbetweenstats()* even adjusts the p-values for *multiple comparisons* with the Holm method automatically and produces bunch of other statistical details on top of the amazing visualization. Violin plots here!

```{r}
ggbetweenstats(
  data = iris, 
  x    = Species, 
  y    = Sepal.Length, 
  type = "np")
```


## Explore missing values


This topic is really very complex! Usually when I prepare data for regression modelling I use another R library called *mice*, but here - just for IDA purposes-  we can highlight the usage of some more *easier* tools. 
The first function *plot_na_intersect()* shows you which variables have missing values and how many. 
The visualization consists of four parts. The bottom left, which is the most basic, visualizes the case of cross(intersection)-combination. The x-axis is the variable including the missing value, and the y-axis represents the case of a combination of variables. And on the marginal of the two axes, the frequency of the case is expressed as a bar graph. Finally, the visualization at the top right expresses the number of variables including missing values in the data set, and the number of observations including missing values and complete cases.  
And the second function *imputate_na()* imputes missing values with different machine learning methods. For instance, using *K nearest neighbors* algorithm, we could impute 37 missing values in Ozone variable, and even visually check the quality of our imputation in only one line of code. Using the *imputate_na()* function, we only need to specify 4 arguments:

- the dataset
- the variable with missing values, that would be Ozone
- the variable which will predict the missing values, for example Temperature 
- the imputation method

```{r}
plot_na_intersect(airquality)
```


```{r}
index1 <- is.na(airquality$Ozone)
index2 <- is.na(airquality$Solar.R)
table(index1,index2)
```

This is the explanation of the above plot: 
we have 111 observations complete, then 2 observation with both the values missing, 5 with only Solar.R missing and 35 with only Ozone missing. 

```{r}
plot(imputate_na(airquality, Ozone, Temp, method = "median"))
```

## Explore the outliers


The *check_outliers()* function from {performance} package provides an easy way to identify and visualize outliers with different methods. 
If you want to have an aggressive method and clean out a lot of outliers, go with the *zscore* method, but if you don’t have much data, go with less conservative method, for example interquartile range. This is a general function, that checks for and locates influential observations (i.e., "outliers") via several distance and/or clustering methods. If several methods are selected, the returned "Outlier" vector will be a composite outlier score, made of the average of the binary (0 or 1) results of each method. It represents the probability of each observation of being classified as an outlier by at least one method. The decision rule used by default is to classify as outliers observations which composite outlier score is superior or equal to 0.5 (i.e., that were classified as outliers by at least half of the methods). The Z-score, or standard score, is a way of describing a data point as deviance from a central value, in terms of standard deviations from the mean.The default threshold to classify outliers is 1.96 (threshold = list("zscore" = 1.96)), corresponding to the 2.5 gaussian percentile (assuming the data is normally distributed). Importantly, the Z-score method is univariate: it is computed column by column. If a dataframe is passed, the Z-score is calculated for each variable separately, and the maximum (absolute) Z-score is kept for each observations. Thus, all observations that are extreme on at least one variable might be detected as outliers. 
Thus, this method is not suitable for high dimensional data (with many columns), returning too liberal results (detecting many outliers). 

```{r}
plot(check_outliers(airquality$Wind, method = "zscore"))
```

The IQR (interquartile range) is a robust method developed by the statistician John Tukey, which often appears in box-and-whisker plots. The interquartile range is the range between the first and the third quartiles. 
Tukey considered as outliers any data point that fell outside of either 1.5 times the IQR below the first or above the third quartile. Similar to the Z-score method, this is a univariate method for outliers detection, returning outliers detected for at least one column, and might thus not be suited to high dimensional data. The distance score for the IQR is the absolute deviation from the median of the upper and lower IQR thresholds. Then, this value is divided by the IQR threshold, to “standardize” it and facilitate interpretation. 


```{r}
check_outliers(airquality$Wind, method = "iqr")
```


The *diagnose_outlier()* function from {dlookr} not only counts outliers in every variable using interquartile range method, but also gets their percentages. 
Moreover, it calculates three different averages: the mean of every variable with outliers, without outliers and the mean of the outliers themselves. 
In this way we can see how strong the influence of outliers for every variable actually is. 
For instance the variable “depth” in “diamonds” data has over 2500 outliers. That’s a lot! However, the means with and without outliers are almost identical. 
Besides, the average of the outliers themselves is very similar to the original average of the whole data. 
In contrast, the variable “price” with over 3500 outliers is heavily influenced by them. 
The average of the outliers is almost 5 times higher, than the average without them.


```{r}
ft7 <- diagnose_outlier(diamonds) %>% flextable()
ft7 <- colformat_double(
  x = ft7,
  digits = 2)
ft7
```

Besides, {dlookr} can visualize the distribution of data with and without outliers, and, thank to collaboration with {dplyr}, we could choose to visualize only variables with over 5% of values being outliers:

```{r}
airquality %>% 
  dplyr::select(Ozone, Wind) %>% 
  plot_outlier()
```


```{r}
# Visualize variables with a ratio of outliers greater than 5%
diamonds %>%
  plot_outlier(diamonds %>%
      diagnose_outlier() %>%
      filter(outliers_ratio > 5) %>%
      select(variables) %>%
      pull())
```

### Eventually...impute outliers 

Similarly to *imputate_na()* function, {dlookr} package provides the *imputate_outlier()* function too, which allows us to impute outliers with several simple methods: mean, median, mode and capping. The last one, *capping*, is the fanciest, and it imputes the upper outliers with 95th percentile, and the bottom outliers with 5th percentile. Wrapping a simple *plot()* command around our result, would give us the opportunity to check the quality of imputation.

```{r}
bla <- imputate_outlier(diamonds, carat, method = "capping")
plot(bla)
```

Remember that we should always investigate the reason why data are missing before try to impute them.. we will briefly discuss this topic in block 3. 

## Evaluating correlations (...useful also for subsequent regression modelling approaches)

In order to quickly check the relationship between numerical variables we can use *correlate()*  function from {dlookr} package, which delivers correlation coefficients. If we don’t specify any target variable or the method, Pearson’s correlation between ALL variables will be calculated pairwise.
{dlookr’s} *plot_correlate()* function is a bit more useful, because it visualizes these relationships. We can of course determine the method of calculations if we need to, be it a default “pearson”, or a non-parametric “kendall” or “spearman” correlations, which are more appropriate for not-normally or non-very-linearly distributed values with some outliers. The shape of each subplot shows the strength of the correlation, while the color shows the direction, where blue is positive and red is negative correlation. It’s fine for the pure initial/exploratory analysis, but, as always, the next logical step would be to test hypothesis and figure out which correlations are significant.

```{r}
cc <- correlate(airquality, method="spearman")
cc
```


```{r}
plot(cc)
```


```{r, warning = F}
zz <- diamonds %>%
  filter(cut %in% c("Premium", "Ideal")) %>% 
  group_by(cut) %>%
  correlate()

plot(zz)

```

The *ggcorrmat()* function from {ggstatsplot} displays:
- correlation coefficients,
- a colored heatmap showing positive or negative correlations, 
- whether a particular correlation is significant or not (significantly different from zero, again pay attention to the sample size !), where not-significant correlations are simply crossed out.

Moreover, we can get the results in a table form with p-values and confidence intervals for correlation coefficients, if we want to, by simply using output = “dataframe” argument.


```{r}
ggcorrmat(data = iris)
```

```{r}
ft8 <- correlation::correlation(data   = iris,
  method= "pearson")
 ft8
```

If any particular correlation catches your attention during the Initial Data Analysis, and you want to display it, use the *ggscatterstats()* function from {ggstatsplot} package, which delivers statistical details, that matter, namely:

- the scatterplot, which helps you to decide to go for a parametric, non-parametric or even robust correlation analysis, if needed,
- the correlation coefficient itself with the name of the method and 95% confidence intervals,
- the p-value of the correlation, and it even displays …
- the distribution of both numeric variables in different ways, for example an histogram, as you see on the current plot


```{r }
ggscatterstats(
  data = airquality,
  x = Ozone,
  y = Temp,
  type = "np" 
)
```


## Summary tools to build the descriptive tables of your report  

Once you have inspected the data and eventually cleaned them from errors/outliers or manipulated some categorical variables in order to collapse categories, or possibly transformed continuous variables...etc etc ... then you can begin to create the descriptive tables for your report. 
First of all, *tbl_summary()* function from {gtsummary} package summarizes all categorical variables by counts and percentages, while all numeric variables by median and IQR. 
The argument *by =* inside of *tbl_summary()* specifies a grouping variable. 
The *add_p()* function then conducts statistical tests with all variables and provides p-values. Remind: these statistical tests are just used for descriptive purposes and should be interpreted with caution!
For numeric variables it uses the non-parametric Wilcoxon rank sum test for comparing two groups and the non-parametric Kruskal-Wallis rank sum test for more then two groups. Categorical variables are checked with Fisher’s exact test, if number of observations in any of the groups is below 5, or with Pearson’s Chi-squared test for more data.
We use as example the dataset *mtcars* . 
The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).

```{r warning=FALSE,message=FALSE}
mtcars %>% 
  select(mpg, hp, am, gear, cyl) %>% 
  tbl_summary(by = am) %>% 
  add_p()
```

As another example, for the dataset wage :

```{r warning=FALSE,message=FALSE}
Wage %>%
  select(age, wage, education, jobclass) %>% 
  tbl_summary(by = education) %>% 
  add_p()
```

