---
title: "Data handling for bioinformatics"
author: "Bernd Klaus"
date: "`r doc_date()`"
output:
BiocStyle::html_document:
toc: true
self_contained: true
toc_float: false
code_download: true
df_print: paged
toc_depth: 2
highlight: tango
BiocStyle::pdf_document:
toc: true
toc_depth: 2
bibliography: stat_methods_bioinf.bib
---
```{r options, include=FALSE}
library(knitr)
options(digits=3, width=80)
golden_ratio <- (1 + sqrt(5)) / 2
opts_chunk$set(echo=TRUE,tidy=FALSE,include=TRUE,
dev=c('png', 'pdf', 'svg'), fig.height = 5, fig.width = 4 * golden_ratio, comment = ' ', dpi = 300,
cache = TRUE)
```
**LAST UPDATE AT**
```{r, echo=FALSE, cache=FALSE}
print(date())
```
# Required packages and other preparations
```{r required_packages_and_data, echo = TRUE, cache=FALSE, message=FALSE}
library("readxl")
library("BiocStyle")
library("knitr")
library("matrixStats")
library("RColorBrewer")
library("stringr")
library("pheatmap")
library("purrr")
library("fdrtool")
library("readr")
library("gtools")
library("factoextra")
library("magrittr")
library("entropy")
library("forcats")
library("plotly")
library("corrplot")
library("car")
library("forcats")
library("openxlsx")
library("readxl")
library("limma")
library("ggthemes")
library("tidyverse")
theme_set(theme_solarized(base_size = 18))
data_dir <- file.path("data/")
```
# Introduction to (single cell) RNA--Seq data
The advent of next-generation sequencing over a decade ago
spurred the development of a host of sequencing-based technologies. One
major innovation, RNA--sequencing (RNA--seq) enabled transcriptomic profiling at
unprecedented sensitivity and breadth, leading to the discovery of
new RNA species and deepening our understanding of transcriptome
dynamics. In recent years, low-input RNA-seq methods have been
adapted to work in single cells. These single-cell RNA-seq (scRNA-
seq) technologies can quantify intra-population heterogeneity and
enable study of cell states and transitions at very high resolution,
potentially revealing cell subtypes or gene expression dynamics that
are masked in bulk, population-averaged measurements.
In RNA--Seq, RNA is captured for reverse transcription into cDNA. This
cDNA is pre-amplified and then used to prepare libraries for
sequencing and downstream analysis. In single cell RNA--Seq (scRNA--Seq), the cells
have to be lysed first. The capture effeciency of scRNA--Seq is quite
only around 10%, so the data obtained is often quite sparse: Many genes
are simply not captured.
# The Brennecke et. al. mTEC data
The ability of the immune system to distinguish self from foreign
("self--antigen--tolerance") is largely established in the thymus,
a primary lymphoid organ where T cells develop.
Intriguingly, T--cells encounter most tissue--specific
constituents already there, thus imposing
a broad scope of tolerance before T cells circulate through the body.
This "training" of the T--cells is neccessary to prevent autoimunity. It
happens by the "promiscuous" expression of numerous tissue-specific antigens
(TRAs) in medullary thymic epithelial cells (mTECs, @Kyewski_2006).
However, it is poorly understood how this process is regulated in
single mTECs and is coordinated at the population level. @Brennecke_2015
obtained scRNA--Seq data of mTECs and find evidence of numerous recurring
TRA--co--expression patterns, each present in only a subset of mTECs.
Thus, they could show that the gene expression in mTEC cells rather "mosaic"
and coordianted rather than entirely stochastic.
Before we dive more deeply into the data, we review important R basics.
# Basics of arithmetics and data handling in R
## Elementary data types and arithmetics
The elementary unit in R is an object and the simplest objects are scalars,
vectors and matrices. R is designed with interactivity in mind, so you can get
started by simply typing:
```{r simple_ex, echo = TRUE}
4 + 6
```
What does R do? It sums up the two numbers and returns the scalar value 10.
In fact, R returns a vector of length 1 - hence the [1] denoting first element
of the vector.
We can assign objects values for subsequent use. For example:
```{r simple_ex_2, echo = TRUE}
x <- 6
y <- 4
z <- x + y
z
```
does the same calculation as above, storing the result in an object called `z`.
We can look at the contents of the object by simply typing its name. At any
time we can
list the objects which we have created:
```{r simple_ex_3, echo = TRUE}
ls()
```
Notice that `ls` is actually an object itself. Typing `ls`
ould result in a display of the contents of
this object, in this case, the commands of the function. The use of parentheses,
`ls()`, ensures that
the function is executed and its result --- in this case, a list of the objects
in the current environment --- displayed.
More commonly, a function will operate on an object, for example
```{r simple_ex_4, echo = TRUE}
sqrt(16)
```
calculates the square root of 16. Objects can be removed from the current
workspace with the
function `rm()`. There are many standard functions available in R,
and it is also possible to create new ones. Vectors can be created in R in
a number of ways.
For example, we can list all of the elements:
```{r simple_ex_5, echo = TRUE}
z <- c(5, 9, 1, 0)
```
Note the use of the function `c` to concatenate or "glue together" individual
elements. This function
can be used much more widely, for example
```{r simple_ex_5b, echo = TRUE}
x <- c(5, 9)
y <- c(1, 0)
z <- c(x, y)
```
would lead to the same result by gluing together two vectors to create
a single vector.
Sequences can be generated as follows:
```{r simple_ex_6, echo = TRUE}
seq(1, 9, by = 2)
seq(8, 20, length = 6)
```
These examples illustrate that many functions in R have optional arguments,
in this case, either the step length or the total length of the sequence
(it doesn't make sense to use both). If you leave
out both of these options, R will make its own default choice, in this case
assuming a step length
of 1. So, for example,
```{r simple_ex_7, echo = TRUE}
x <- seq(1, 10)
```
also generates a vector of integers from 1 to 10.
At this point it's worth mentioning the help facility again.
If you don't know how to use a function,
or don't know what the options or default values are,
type `help(functionname)`
or simply `?functionname` where
`functionname` is the name of the function you are interested in.
This will usually help and will often include
examples to make things even clearer.
Another useful function for building vectors is the `rep` command for
repeating things:
the first command will repeat the vector `r 1:3` six times, will the second
one will repeat each element six times.
```{r simple_ex_8, echo = TRUE}
rep(1:3, 6)
rep(1:3, times = c(6, 6, 6))
```
R will often adapt to the objects it is asked to work on. An example is the
vectorized arithmetic used in R:
```{r vec}
x <- 1:5
y <- 5:1
x + y
x^2
x * y
```
showing that R uses component-wise arithmetic on vectors. R will also try to
make sense of a statement if objects
are mixed. For example:
```{r vec-2}
x <- c(6, 8 , 9 )
x + 2
```
Two particularly useful functions worth remembering are `length`,
which returns the length of a vector (i.e. the number of elements it contains)
and `sum` which calculates the sum of the elements
of a vector. R also has basic calculator capabilities:
* `a+b`, `a-b`, `a\*b`, `a\*\*b` (a to the power of b)
* additionally: `sqrt(a)`, `sin(a)` ...
and some simple statistics:
* ` mean(a)`
* ` summary(a)`
* ` var(a)`
* ` min(a,b)`, `max(a,b)`
## Subscripting and useful vector functions
Let's suppose we've collected some data from an experiment and stored them
in an object `x`.
Some simple summary statistics of these data can be produced:
```{r summary_1, echo = TRUE}
x <- c(7.5, 8.2, 3.1, 5.6, 8.2, 9.3, 6.5, 7.0, 9.3, 1.2, 14.5, 6.2)
mean(x)
var(x)
summary(x)
```
It may be, however, that we subsequently learn that the first
6 data points correspond to measurements made in one experiment,
and the second six on another experiment.
This might suggest summarizing the two sets of data separately,
so we would need to extract from
`x` the two relevant subvectors. This is achieved by subscripting:
```{r subscr, echo = TRUE}
x[1:6]
x[7:12]
summary(x[1:6])
summary(x[7:12])
```
You simply put the indexes of the element you want to access in square brackets.
Note that R starts counting from 1 onwards.
Other subsets can be created in the obvious way. Putting a minus in
front, excludes
the elements:
```{r subscr_2, echo = TRUE}
x[c(2, 4, 9)]
x[-(1:6)]
head(x)
```
The function `head` provides a preview of the vector. There are also
useful functions to order and sort vectors:
* `sort`: sort in increasing order
* `order`: orders the indexes is such a way that the elements
of the vector are sorted, i.e `sort(v) = v[order(v)]`
* `rank`: gives the ranks of the elements
of a vector, different options for handling *ties* are
available.
```{r sort-rank, echo = TRUE}
x <- c(1.3, 3.5, 2.7, 6.3, 6.3)
sort(x)
order(x)
x[order(x)]
rank(x)
```
## Matrices
Matrices are two--dimensional vectors and
can be created in R in a variety of ways. Perhaps the simplest is to
create the columns
and then glue them together with the command `cbind`. For example:
```{r cbind-ex, echo = TRUE}
x <- c(5, 7 , 9)
y <- c(6, 3 , 4)
z <- cbind(x, y)
z
dim(z)
```
We can also use the function `matrix()` directly to create a matrix.
```{r matrix_direct, echo = TRUE}
z <- matrix(c(5, 7, 9, 6, 3, 4), nrow = 3)
```
There is a similar command, `rbind`, for building matrices by
gluing rows together.
The functions `cbind` and `rbind` can also be applied to matrices themselves
(provided the dimensions match) to form larger matrices.
Notice that the dimension of the matrix is determined
by the size of the vector and the requirement that the number of
rows is 3 in the example above, as specified by the
argument `nrow = 3`. As an alternative we could have specified
the number of columns with the argument `ncol = 2` (obviously, it is
unnecessary to give both). Notice that the matrix is "filled up"
column-wise. If instead you wish to fill up row-wise, add the option
`byrow=TRUE`.
```{r Matrix-ex, echo = TRUE}
z <- matrix(c(5, 7 , 9 , 6 , 3 , 4), nrow = 3, byrow = TRUE)
z
```
R will try to interpret operations on matrices in a natural way.
For example, with z as above, and y defined below we get:
```{r Matrix-op, echo = TRUE}
y <- matrix(c(1, 3, 0, 9, 5, -1), nrow = 3, byrow = TRUE)
y
y + z
y * z
```
Notice that multiplication here is component--wise.
As with vectors it is useful to be able to extract sub-components of matrices. In this case, we
may wish to pick out individual elements, rows or columns. As before, the `[ ]`
notation is used to subscript. The following examples illustrate this:
```{r Matrix-op-4, echo = TRUE}
z[1, 1]
z[, 2]
z[1:2, ]
z[-1, ]
z[-c(1, 2), ]
```
So, in particular, it is necessary to specify which rows and columns are required,
whilst omitting the index for either dimension implies that every element
in that dimension is selected.
## Data frames (tibbles) and lists
A data frame is a matrix where the columns can have different data types.
As such, it is usually used to represent a whole data set, where the rows
represent the samples and columns the variables. Essentially, you can think
of a data frame as an excel table.
Here, we will meet the first tidyverse member, namely the `r CRANpkg("tibble") `
package, which improves the conventional R `data.frame` class. A tibble
is a `data.frame` which a lot of tweaks and more sensible defaults that make your
life easier. For details on the tweaks, see the help on tibble: `?tibble`
so that you never have to use a standard data frame anymore.
Let's illustrate this by the small data set
saved in comma--separated-format (csv) ---
`patients`. We load it in from a website using the function
`read_csv`, which is used to import a data file in
*comma separated format --- csv* into R. In a .csv--file the data
are stored row--wise, and the entries in each row are separated by commas.
The function `read_csv` is from the `r CRANpkg("readr")` package and will
give us a tibble as the result. The function `glimpse()` gives a nice summary
of a tibble.
```{r load-Patients, echo = TRUE}
pat <- read_csv("http://www-huber.embl.de/users/klaus/BasicR/Patients.csv")
pat
glimpse(pat)
```
It has weight, height and gender of three people.
## Accessing data in data frames
Now that we have imported the small data set, you might be wondering how to
actually access the data. For this the functions `filter` and `select` from
the `r CRANpkg("dplyr")` package of the `r CRANpkg("tidyverse")` are useful.
`filter` will select certain rows (observations),
while `select` will subset the columns (variables of the data). In the following
command, we get all the patients that are less tall than 1.5 and select their Height and
Gender as well as their Id:
```{r subset_data}
pat_tiny <- filter(pat, Height < 1.7)
select(pat_tiny, PatientId, Height, Gender)
```
There are a couple of operators useful for comparisons:
* `Variable == value`: equal
* `Variable != value`: un--equal
* `Variable < value`: less
* `Variable > value`: greater
* `&: and`
* `|` or
* `!`: negation
* `%in%`: is element?
The function `filter` allows us to combine multiple conditions easily,
if you specify multiple of them, they will automatically concatenated via a `&`.
For example, we can easily get light and female patients via:
```{r light_and_small_patients, echo = TRUE}
filter(pat, Height < 1.7, Gender == "f")
```
We can also retrieve small OR female patients via
```{r light_or_small_patients, echo = TRUE}
filter(pat, (Height < 1.5) | (Gender == "f"))
```
## Vectors with arbitrary contents: Lists
Lists can be viewed as vectors that contain not only elementary objects such
as number or strings but can potentially arbitrary objects. The following example
will make this clear. The list that we create contains a number, two vectors
and a string that is itself part of a list.
```{r list_example, echo = TRUE}
L <- list(one = 1, two = c(1, 2), five = seq(1, 4, length = 5),
list(string = "Hello World"))
L
```
Lists are the most general data type in R. In fact, data frames (tibbles) are
lists with elements of equal lengths. List elements can either be accessed by
their name using the dollar sign `$` or via their position via a double
bracket operator `[[]]`.
```{r list_access, echo = TRUE}
names(L)
L$five + 10
L[[3]] + 10
```
Using only a single bracket (`[]`) will extract a sublist, so the result will
always be a list, while the dollar sign `$` or the double bracket operator
`[[]]` removes a level of the list hierarchy. Thus, in order to access the
string, we would first have to extract the sublist containing the string from `L`
and then get the actual string from the sublist, `[[` drills down into the list
while `[` returns a new, smaller list.
```{r}
L[[4]]$string
L[2]
```
Since data frames are just a special kind of lists,
they can actually be accessed in the same way.
```{r list-example_df, echo = TRUE}
pat$Height
pat[[2]]
pat[["Gender"]]
```
More on lists can be found in the respective chapter of "R for data science"
[here](http://r4ds.had.co.nz/vectors.html#lists).
## Summary: data access in R
We prape a simple vector to illustrate the access options again:
```{r acces_recap}
sample_vector <- c("Alice" = 5.4, "Bob" = 3.7, "Claire" = 8.8)
sample_vector
```
### Access by index
The simplest way to access the elements in a vector is via their indices.
Specifically, you provide a vector of indices to say which
elements from the vector you want to retrieve. A minus sign excludes the respective
positions
```{r access_index, dependson="accesRecap"}
sample_vector[1:2]
sample_vector[-(1:2)]
```
### Access by boolean
If you generate a boolean vector the same size as your actual vector you can use
the positions of the true values to pull out certain positions from the full set.
You can also use smaller boolean vectors and they will be concatenated
to match all of the positions in the vector, but this is less common.
```{r access_boolean, dependson="acces_recap"}
sample_vector[c(TRUE, FALSE, TRUE)]
```
This can also be used in conjunction with logical tests
which generate a boolean result. Boolean vectors can be combined
with logical operators
to create more complex filters.
```{r access_boolean2, dependson="acces_recap"}
sample_vector[sample_vector < 6]
```
### Access by name
if there are names such as
column names present (note that rowname are not preserved in the tidyverse),
you can access by name as well:
```{r access_name}
sample_vector[c("Alice", "Claire")]
```
# mTEC quality control data
For each single-cell transcriptome of the mTEC data, the sequenced
fragments were mapped to the Mouse reference genome. For each sample the reads
were classified as either:
* mapping uniquely to the reference genome,
* mapping multiple times to the reference genome
* reads which could not be assigned to any position of the reference genome
* others (e.g read pairs were only one read pair mate could be mapped).
We look at the data after importing it via a `load` command from an `RData`
file.
```{r load_inspect_qc_data}
load(file.path(data_dir, "sc_qc_stats.RData"))
sc_qc_stats
```
# Introducing tibbles: a data.frame replacement
`sc_qc_stats` is a `r CRANpkg("tibble")`. A tibble
is a data.frame which a lot of tweaks and more sensible defaults that make your
life easier, among other things it ...
1. Never coerces inputs (i.e. strings stay as strings!)
1. Never adds row.names
1. Never munges column names (they stay as they are)
1. Only recycles length 1 inputs.
1. Automatically adds column names.
The data is a typical data set in a tabular format, where multipe mapping
statistics are given for each single cell. The table is in a "long" format,
meaning that each single cell has data in multiple rows.
The columns give the annotation variables (a.k.a. "keys"): `type`, `cell`
and `batch` as well as on measuremnt (`percent`).
An important concept in data handling is "tidy data"
and we will explain what that means next.
# The concept of tidy data
In a nutshell, a dataset is a collection of values, usually either numbers
(if quantitative) or strings (if qualitative). Values are organized in two ways:
Every value belongs to a variable and an observation.
A variable contains all values that measure an underlying attribute
(like height, temperature, duration, or here: percentage of reads) across units.
An observation contains all values measured on the same unit (like a person,
a day or a single cell) across attributes.
Now, a tidy data frame has:
1. one row per observation
2. one column per variable
3. on cell per value
Tidy data will result in a "long" data table and is the most appropriate
format for
data handling. It allows straighforward subestting and group--wise
computations. However, a "wide" data table is better for viewing.
In our quality control data, the requirements for tidy data are fullfilled.
However, for viewing, it would be nice to make the data "wider" by spreading
the columns `type` and `percent across multiple columns, so that
we all data for one single cell in one single row.
The package `r CRANpkg("tidyr")` has two main functions that allows
us to go back and forth:
* `gather()` takes multiple columns, and gathers them
into key--value pairs: it makes "wide" data longer.
* `spread()` takes two columns (key & value) and
spreads into multiple columns, it makes "long" data wider.
Widening our data frame is simple: we provide a column to spread (a key column)
and a column containing the values use (a value column).
Our key column is `type` and our value column is `percent`
```{r spread_qc_stats}
sc_qc_stats_wide <- spread(sc_qc_stats, key = type, value = percent)
sc_qc_stats_wide
```
We now have separate columns for every mapping type, which makes it easier to
view the data. This data is not "tidy", as the columns we created contain both
ther pecent as well as the type variable --- We have multiple variables
per column.
The function `gather` can be used to obtain the original
format again:
```{r gather_qc_stats}
sc_qc_stats_org <- gather(sc_qc_stats_wide, key = "type",
value = "percent", concordantMult:others)
```
We specify to gather the percentages in a column `percent`
and the mapping type in a column `type`. The `type` column allows
the matching of the percentages to the corresponding column in the
wide data frame. Hence it is called a key column.
# Basic data manipulation with dplyr verbs
The package `r CRANpkg("dplyr")` provides a "grammar" of data manipulation.
We will also use them extensively later on when discussing the
"split--apply--combine" strategy for data analysis.
Since the first thing you do in a data manipulation task is to subset/transform
your data, it includes "verbs" that provide basic functionality. We will
introduce these in the following. The command structure for all
`r CRANpkg("dplyr")`
verbs is :
* first argument is a data frame
* return value is a data frame
* nothing is modified in place
Note that `r CRANpkg("dplyr")` generally does not preserve row names.
## Selecting rows (observations) by their values with `filter()`
The function `filter()` allows you to select a subset of the rows of
a data frame. The first argument is the name of the data frame, and the
second and subsequent are filtering expressions evaluated in the context of
that data frame. In the command below, we get all cells with at least 80%
of concordantly mapped read pairs.
```{r mapped_reads}
filter(sc_qc_stats_wide, concordantUniq > 80 )
```
`filter()` works similarly to `subset()` except
that you can give it any number of filtering
conditions which are joined together with & (not &&
which is easy to do accidentally otherwise).
```{r filter_data_and}
head(filter(sc_qc_stats_wide, concordantUniq > 80, others < 5 ))
```
You can use other boolean operators explicitly as in:
```{r filter_data_or}
head(filter(sc_qc_stats_wide, concordantUniq > 80 | nomap < 10 ))
```
## Arrange rows (samples) with `arrange()`
`arrange()` works similarly to `filter()` except that
instead of filtering or selecting rows, it reorders them.
It takes a data frame, and a set of column names
(or more complicated expressions) to order by.
If you provide more than one column name, each additional column will be
used to break ties in the values of preceding columns:
```{r arange_asc}
arrange(sc_qc_stats_wide, concordantUniq, nomap)
```
Use `desc()` to order a column in descending order:
```{r arange_desc}
arrange(sc_qc_stats_wide, desc(concordantUniq), nomap)
```
## Select columns (variables) by their names with `select()`
Often you work with large data sets with many columns where only a few are
actually of interest to you. `select()`
allows you to rapidly zoom in on a useful subset using operations that usually
only work on numeric variable positions. This way, we can e.g. select only
the column giving the percentage of uniquely mapping reads.
```{r select}
select(sc_qc_stats_wide, concordantUniq)
```
The `select` is similar to the basic R acccess options for data
frame: the square bracket for index/name based access.
```{r base_r_select}
sc_qc_stats_wide[, "concordantUniq"]
idx <- which(colnames(sc_qc_stats_wide) == "concordantUniq")
idx
sc_qc_stats_wide[, idx]
```
There are two options for obtaining a vector as a return type, the double
bracket `[[` and the dollar sign `$`.
```{r base_r_select_vec}
head(sc_qc_stats_wide$concordantUniq, 5)
head(sc_qc_stats_wide[[idx]], 5)
```
## Create new variables using existing ones with `mutate()`
`dplyr::mutate()` allows to add columns using existing columns as input.
We implement a column holding a sum of all percentages as sanity check:
```{r mutate-example}
sc_qc_stats_wide <- mutate(sc_qc_stats_wide,
sum_perc = concordantMult + concordantUniq + nomap
+ others)
all(round(sc_qc_stats_wide$sum_perc) == 100)
```
Indeed, all of the mapped reads are assigned to at least one category for
every single cell.
## Grouped summaries: `group_by()` and `summarize()`
While the basic `r CRANpkg("dplyr")` verbs merely replicate base R functionality,
they become really powerful when used in conjuction with grouped data frames.
The function `group_by()` creates groups in a data frame to which you
can then apply any set of functions and finally obtain a new data frame
with the results via a call to `summarize()`.
Let's look at the mean alignment rates per batch:
```{r mean_per_batch}
sc_qc_stats_per_batch <- group_by(sc_qc_stats, type, batch)
sc_qc_mean_align_per_batch <- filter(summarize(sc_qc_stats_per_batch,
mean_align_rate = mean(percent)),
type == "concordantUniq")
sc_qc_mean_align_per_batch
```
Here, we first group the data by type and batch, then summarize
the percentages per read category and finally subset the result so that
only the mean rate for the concordant read pairs are given.
Note that each call to summarize peels off one level of grouping.
The function `ungroup()` can be used to remove the grouping again.
# The piping / chaining operator
Our code in the previous code chunk is neither very elegent nor clear:
we create an intermediate data table for the grouped data and then use this
in a line of code that has to be read from the inside to outside.
To change this, we use the chaining (or piping) operator `%>%`.
x %>% f(y) simply means f(x, y). Thus, the current data frame can
be put into a function (or even multiple processing steps), which in turn
returns a data frame.
This allows us to code multiple operations in such a way that they can be read
from you can read from left--to--right,
top--to--bottom.
A simple example will make that clear: We create
two vectors and calculate Euclidean distance between them. Instead of
the usual way:
```{r chainingSimpleExample_1}
x1 <- 1:5; x2 <- 2:6
sqrt(sum((x1 - x2)^2))
```
We can use the piping operator
```{r chainingSimpleExample_2}
(x1 - x2)^2 %>%
sum() %>%
sqrt()
```
Which makes the set of operations much easier to digest and understand.
We can simplify our code like this:
```{r mean_per_batch_pipe}
sc_qc_mean_align_per_batch <- group_by(sc_qc_stats, batch, type ) %>%
summarize(mean_align_rate = mean(percent)) %>%
filter(type == "concordantUniq")
```
It is now clear that you group first,
then you summarize and then you filter.
## Filtering per group
Filtering also works on grouped data frames, we can identify the cell with
the worst alignment rate in each batch like this:
```{r worst_cell}
worst_cells <- group_by(sc_qc_stats, batch, type ) %>%
filter(percent == min(percent),
type == "concordantUniq") %>%
arrange(percent)
worst_cells
```
# Combining tables with related information
Often, one wants to combine two (or more) tables that contain related information.
This is often the case after a summarization on grouped data.
Consider the following data table showing qPCR data for
various genes (`target\_Name`) in various cell lines (`sample\_name`)
in two replicates. In quantitative real time PCR,
the complete PCR amplification process is monitored and a florescence intensity
is obtained for each cycle. A common way to reduce the data for the complete
process to a single number, is to give the number of times the fluorescence
is higher than a certain background threshold. This values is commonly referred
to as *C_T* value.
```{r data_q_pcr}
q_pcr <- read_csv(file.path(data_dir, "qPCR.csv"))
head(q_pcr, 5)
```
## Adding columns group--wise
As we have two replicates per sample, it is a natural to
add this annotation information to the table. In the code below, we
add a column *replicate* to each subgroup of the data frame
and the return the augmented data table.
```{r add_rep_info}
q_pcr <- q_pcr %>%
group_by(sample_name, target_Name) %>%
mutate(replicate = c("r_1", "r_2")) %>%
ungroup()
head(q_pcr)
```
## Performing a join operation
As a first analysis step, we might want to infer the mean
and the variability of the *C_T* values, in order to assess both gene
expression and reproducibility. We assess reproducibility by a
spread value, which is simply the difference between the two
*C_T* values per experimental sample.
```{r sum_across_reps, dependson="add_rep_info"}
summary_across_reps <- group_by(q_pcr,
sample_name,
target_Name) %>%
dplyr::summarize(mean = mean(C_T, na.rm = TRUE),
spread = abs(diff(C_T))) %>%
ungroup()
head(summary_across_reps, 5)
```
We now might want to combine this information to the original data table, this
can be done use the various join functions in `r CRANpkg("dplyr") `. Join operations
combine tables based on common columns. In our case a left join operation is useful,
which includes all observations in your primary table, regardless of whether they
match or not. This is the most commonly used join because it ensures that you
don't loose observations from your primary table. More information on various
join types can be found here: .
```{r left_join_summ, dependson="sum_across_reps"}
augmented_table <- left_join(q_pcr, summary_across_reps )
head(augmented_table, 5)
```
`r CRANpkg("dplyr") ` will automatically try to identify matching columns, and
tell you which ones it has used, but you can always specify them manually
using the __by__ argument.
## Alternative: a grouped mutate
Instead of creating a summary of the data and then joining the summary to
the original table, we can also directly use the `mutate` function on
a grouped data set:
```{r grouped_mutate}
augmented_table_mutate <- group_by(q_pcr, sample_name,
target_Name) %>%
mutate(mean = mean(C_T, na.rm = TRUE),
spread = abs(diff(C_T)))
head(augmented_table_mutate, 5)
```
### Exercise: High quality cells
1. Assume a you want to retain only high quality cells defined by an
percentage of greater than 60% of uniquely and concordantly mapping
read pairs.
Which proportion of cells are of high quality? Use filtering
and the function `count()` to answer this. Make sure to ungroup the
data set before using the function `count()`!
```{r ex_high_qual, echo=FALSE, results="hide"}
hq_cells <- mutate(sc_qc_stats, high_qual = percent > 60) %>%
filter(type == "concordantUniq")
prop_high_qual <- dplyr::count(hq_cells, high_qual) %>%
arrange(high_qual) %>%
mutate(perc_qual = n / sum(n))
```
2. Compute the proportion of high quality per batch.
```{r ex_high_qual_batch, echo=FALSE, results="hide"}
group_by(hq_cells, batch) %>%
dplyr::count(high_qual) %>%
mutate(perc_qual = n / sum(n)) %>%
filter(high_qual == TRUE) %>%
arrange(perc_qual)
```
# Session Info
```{r sessionInfo, cache = FALSE}
sessionInfo()
```
# References