---
title: "Working with aggregate functions"
author: 
  - name: Giulia Pais
    affiliation: | 
     San Raffaele Telethon Institute for Gene Therapy - SR-Tiget, 
     Via Olgettina 60, 20132 Milano - Italia
    email: giuliapais1@gmail.com, calabria.andrea@hsr.it
output: 
  BiocStyle::html_document:
    self_contained: yes
    toc: true
    toc_float: true
    toc_depth: 2
    code_folding: show
date: "`r doc_date()`"
package: "`r pkg_ver('ISAnalytics')`"
vignette: >
  %\VignetteIndexEntry{aggregate_function_usage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}  
---

```{r include = FALSE}
knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    crop = NULL
    ## Related to
    ## https://stat.ethz.ch/pipermail/bioc-devel/2020-April/016656.html
)
```

```{r vignetteSetup, echo=FALSE, message=FALSE, warning = FALSE}
## Bib setup
library("RefManageR")

## Write bibliography information
bib <- c(
    R = citation(),
    BiocStyle = citation("BiocStyle")[1],
    knitr = citation("knitr")[1],
    RefManageR = citation("RefManageR")[1],
    rmarkdown = citation("rmarkdown")[1],
    sessioninfo = citation("sessioninfo")[1],
    testthat = citation("testthat")[1],
    ISAnalytics = citation("ISAnalytics")[1]
)
```

# Introduction

In this vignette we're going to explain in detail how to use functions of the 
aggregate family, namely:

1. `aggregate_metadata()`
2. `aggregate_values_by_key()`

```{r echo=FALSE}
inst_chunk_path <- system.file("rmd", "install_and_options.Rmd", package = "ISAnalytics")
```

```{r child=inst_chunk_path}

```

# Aggregating metadata

We refer to information contained in the association file as "metadata": 
sometimes it's useful to obtain collective information based on a certain 
group of variables we're interested in. The function `aggregate_metadata()` 
does just that: according to the grouping variables, meaning the names of 
the columns in the association file to perform a `group_by` operation with,it 
creates a summary. You can fully customize the summary by providing a 
"function table" that tells the function which operation should be 
applied to which column and what name to give to the output column.
A default is already supplied:

```{r echo=FALSE}
library(ISAnalytics)
print(default_meta_agg(), width = Inf)
```

You can either provide purrr-style lambdas (as given in the example above),
or simply specify the name of the function and additional parameters as a 
list in a separated column. If you choose to provide your own table you
should maintain the column names for the function to work properly.
For more details on this take a look at the function documentation 
`?default_meta_agg`.

## Typical workflow

1. Import the association file via `import_assocition_file()`. If you need more 
information on import function please view the vignette 
"How to use import functions": 
`vignette("how_to_import_functions", package="ISAnalytics")`.
2. Perform aggregation

```{r}
data("association_file", package = "ISAnalytics")
aggregated_meta <- aggregate_metadata(association_file = association_file)
```

```{r echo=FALSE}
print(aggregated_meta)
```

# Aggregation of values by key

`ISAnalytics` contains useful functions to aggregate the values contained in 
your imported matrices based on a key, aka a single column or a combination of 
columns contained in the association file that are related to the samples.

## Typical workflow

1. Import your association file
2. Import integration matrices via `import_parallel_Vispa2Matrices()`
3. Perform aggregation

```{r}
data("integration_matrices", package = "ISAnalytics")
data("association_file", package = "ISAnalytics")
aggreg <- aggregate_values_by_key(
  x = integration_matrices, 
  association_file = association_file,
  value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(aggreg, width = Inf)
```

The function `aggregate_values_by_key` can perform the aggregation both on the 
list of matrices and a single matrix.

### Changing parameters to obtain different results

The function has several different parameters that have default values that 
can be changed according to user preference.

1. **Changing the `key` value**  
You can change the value of the parameter key as you see fit. This parameter 
should contain one or multiple columns of the association file that you want 
to include in the grouping when performing the aggregation. 
The default value is set to `c("SubjectID", "CellMarker",
"Tissue", "TimePoint")`
(same default key as the `aggregate_metadata` 
function).

```{r}
agg1 <- aggregate_values_by_key(
    x = integration_matrices,
    association_file = association_file,
    key = c("SubjectID", "ProjectID"),
    value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(agg1, width = Inf)
```

2. **Changing the `lambda` value**  
The `lambda` parameter indicates the function(s) to be applied to the 
values for aggregation. 
`lambda` must be a named list of either functions or purrr-style lambdas:
if you would like to specify additional parameters to the function 
the second option is recommended.
The only important note on functions is that they should perform some kind of 
aggregation on numeric values: this means in practical terms they need
to accept a vector of numeric/integer values as input and produce a 
SINGLE value as output. Valid options for this purpose might be: `sum`, `mean`, 
`median`, `min`, `max` and so on.

```{r}
agg2 <- aggregate_values_by_key(
    x = integration_matrices,
    association_file = association_file,
    key = "SubjectID",
    lambda = list(mean = ~ mean(.x, na.rm = TRUE)),
    value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(agg2, width = Inf)
```

Note that, when specifying purrr-style lambdas (formulas), the first 
parameter needs to be set to `.x`, other parameters can be set as usual.

You can also use in `lambda` functions that produce data frames or lists.
In this case all variables from the produced data frame will be included
in the final data frame. For example:

```{r}
agg3 <- aggregate_values_by_key(
    x = integration_matrices,
    association_file = association_file,
    key = "SubjectID",
    lambda = list(describe = ~ list(psych::describe(.x))),
    value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(agg3, width = Inf)
```

3. **Changing the `value_cols` value**  
The `value_cols` parameter tells the function on which numeric columns 
of x the functions should be applied. 
Note that every function contained in `lambda` will be applied to every
column in `value_cols`: resulting columns will be named as 
"original name_function applied".

```{r}
agg4 <- aggregate_values_by_key(
    x = integration_matrices,
    association_file = association_file,
    key = "SubjectID",
    lambda = list(sum = sum, mean = mean),
    value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(agg4, width = Inf)
```

4. **Changing the `group` value**  
The `group` parameter should contain all other variables to include in the 
grouping besides `key`. By default this contains 
`c("chr", "integration_locus","strand", "GeneName", "GeneStrand")`. 
You can change this grouping as you see 
fit, if you don't want to add any other variable to the key, just set it to 
`NULL`.

```{r}
agg5 <- aggregate_values_by_key(
    x = integration_matrices,
    association_file = association_file,
    key = "SubjectID",
    lambda = list(sum = sum, mean = mean),
    group = c(mandatory_IS_vars()),
    value_cols = c("seqCount", "fragmentEstimate")
)
```

```{r echo=FALSE}
print(agg5, width = Inf)
```

# Reproducibility

`R` session information.

```{r reproduce3, echo=FALSE}
## Session info
library("sessioninfo")
options(width = 120)
session_info()
```

# Bibliography

This vignette was generated using `r Biocpkg("BiocStyle")` `r Citep(bib[["BiocStyle"]])`
with `r CRANpkg("knitr")` `r Citep(bib[["knitr"]])` and `r CRANpkg("rmarkdown")` `r Citep(bib[["rmarkdown"]])` running behind the scenes.

Citations made with `r CRANpkg("RefManageR")` `r Citep(bib[["RefManageR"]])`.

```{r vignetteBiblio, results = "asis", echo = FALSE, warning = FALSE, message = FALSE}
## Print bibliography
PrintBibliography(bib, .opts = list(hyperlink = "to.doc", style = "html"))
```
