data_handling_bioinf.Rmd 31.4 KB
Newer Older
1 2 3 4 5
---
title: "Data handling for bioinformatics"
author: "Bernd Klaus"
date: "`r doc_date()`"
output: 
6
    BiocStyle::html_document:
7 8 9 10
        toc: true
        self_contained: true
        toc_float: false
        code_download: true
11 12
        df_print: paged
        toc_depth: 2
13
        highlight: tango
14
    BiocStyle::pdf_document:
15 16
        toc: true
        toc_depth: 2
17
bibliography: stat_methods_bioinf.bib
18 19
---

20 21
<!--
graphics.off();rm(list=ls());rmarkdown::render('data_handling_bioinf.Rmd', 
22
output_format = "BiocStyle::html_document");purl('data_handling_bioinf.Rmd')
23

24
rmarkdown::render('data_handling_bioinf.Rmd', output_format = 
25
          BiocStyle::pdf_document(toc = TRUE, highlight = "tango", 
26
          df_print = "paged", toc_depth = 2))
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
-->

```{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


49
```{r required_packages_and_data, echo = TRUE, cache=FALSE, message=FALSE}
50 51 52
library("readxl")
library("BiocStyle")
library("knitr")
53
library("matrixStats")
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
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")
72
library("ggthemes")
73
library("tidyverse")
74 75 76

theme_set(theme_solarized(base_size = 18))

77

78
data_dir <- file.path("data/")
79

80
```
81 82


83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
# 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 
118
(TRAs) in medullary thymic  epithelial cells (mTECs, @Kyewski_2006).
119 120

However, it is poorly understood how this process is regulated in
121
single mTECs and is coordinated at the population level. @Brennecke_2015
122 123
obtained scRNA--Seq data of mTECs and find evidence of numerous recurring 
TRA--co--expression patterns, each present in only a subset of mTECs.
124 125
Thus, they could show that the gene expression in mTEC cells rather "mosaic" 
and coordianted rather than entirely stochastic. 
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

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. 
145 146
In  fact, R returns a vector of length 1 - hence the [1] denoting first element 
of the vector.
147 148 149 150 151 152 153 154 155 156 157
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`. 
158 159
We can look at the contents of the object by simply typing its name. At any 
time we can 
160 161 162 163 164 165 166 167
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
168 169 170 171
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.
172 173 174 175 176 177
More commonly, a function will operate on an object, for example

```{r simple_ex_4, echo = TRUE}
sqrt(16)
```

178 179
calculates the square root of 16. Objects can be removed from the current
workspace with the 
180
function `rm()`. There are many standard functions available in R, 
181 182
and it is also possible to create new ones. Vectors can be created in R in
a number of ways.
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
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:
204

205 206 207 208 209 210

```{r simple_ex_6, echo = TRUE}
seq(1, 9, by = 2)
seq(8, 20, length = 6)
```

211 212 213 214 215
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
216 217 218 219 220
of 1. So, for example,


```{r simple_ex_7, echo = TRUE}
x <- seq(1, 10)
221 222
```

223 224 225 226 227 228 229 230 231
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.
232 233
Another useful function for building vectors is the `rep` command for 
repeating things:
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
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
```  
261

262 263 264 265
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:
266

267

268 269
* `a+b`, `a-b`, `a\*b`,  `a\*\*b` (a to the power of b) 
* additionally: `sqrt(a)`, `sin(a)` ...
270

271
and some simple statistics: 
272

273 274 275 276
*  ` mean(a)`
*  ` summary(a)`
*  ` var(a)`
*  ` min(a,b)`, `max(a,b)`
277 278


279
## Subscripting and useful vector functions
280

281 282 283
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:
284

285 286 287 288 289
```{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)
290
```
291 292 293
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.
294 295
This might suggest summarizing the two sets of data separately, 
so we would need to extract from
296 297 298 299 300 301 302 303 304 305 306
`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.
307 308
Other subsets can be created in the obvious way. Putting a minus in 
front, excludes
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
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 
342 343
can be created in R  in a variety of ways. Perhaps the simplest is to 
create the columns
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
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
368 369 370 371 372
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`. 
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
 

```{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}
478
filter(pat, Height < 1.7, Gender == "f")
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
```
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
571 572
which generate a boolean result. Boolean vectors can be combined 
with logical operators
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
 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). 
601 602 603 604 605 606 607 608 609 610

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
```


611
# Introducing tibbles: a data.frame replacement
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635

`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.

636
# The concept of tidy data
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

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


657 658
Tidy data will result in a "long" data table and is  the most appropriate 
format for 
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
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 
687 688
ther pecent as well as the type variable --- We have multiple variables 
per column.
689 690 691 692 693 694 695 696 697 698 699 700 701 702

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.

703
# Basic data manipulation with dplyr verbs
704 705 706 707 708 709 710

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
711 712
introduce these in the following. The command structure for all 
`r CRANpkg("dplyr")` 
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
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) 
```

784
The `select` is similar to the basic R acccess options for data
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
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, 
810 811
                           sum_perc = concordantMult + concordantUniq + nomap
                           + others)
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

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, 
837 838
          mean_align_rate = mean(percent)),
         type == "concordantUniq")
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

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 
```


913 914 915 916 917 918
# 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 
919 920
various genes (`target\_Name`) in various cell lines (`sample\_name`) 
in two replicates. In quantitative real time PCR, 
921 922 923 924 925 926 927 928
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}
929
q_pcr <- read_csv(file.path(data_dir, "qPCR.csv"))
930
head(q_pcr, 5)
931 932 933 934 935 936
```


## Adding columns group--wise 

As we have two replicates per sample, it is a natural to
937
add this annotation information to the table. In the code below, we 
938 939 940 941 942
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 %>% 
943 944 945
  group_by(sample_name, target_Name) %>%
  mutate(replicate =  c("r_1", "r_2")) %>% 
  ungroup()
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

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()

967
head(summary_across_reps, 5)
968 969 970 971 972 973 974 975 976 977 978 979
```

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: <https://cran.r-project.org/web/packages/dplyr/vignettes/two-table.html>.

```{r left_join_summ, dependson="sum_across_reps"}
augmented_table <- left_join(q_pcr, summary_across_reps )
980
head(augmented_table, 5)
981 982 983 984 985 986
```

`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.

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
## 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) 
```



1004
### Exercise: High quality cells
1005 1006 1007 1008 1009

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. 

1010
Which proportion of cells are of high quality? Use filtering 
1011 1012 1013 1014
and the function `count()` to answer this. Make sure to ungroup the 
data set before using the function `count()`!


1015
```{r ex_high_qual, echo=FALSE, results="hide"}
1016
hq_cells <- mutate(sc_qc_stats, high_qual = percent > 60) %>%
1017 1018
                filter(type == "concordantUniq") 

1019
prop_high_qual <- dplyr::count(hq_cells, high_qual) %>%
1020
                    arrange(high_qual) %>%
1021 1022 1023 1024
                    mutate(perc_qual = n / sum(n))

```

1025
2. Compute the proportion of high quality per batch.
1026 1027


1028
```{r ex_high_qual_batch, echo=FALSE, results="hide"}
1029

1030 1031 1032 1033 1034
group_by(hq_cells, batch) %>%
        dplyr::count(high_qual) %>%
        mutate(perc_qual = n / sum(n))  %>%
        filter(high_qual == TRUE) %>%
        arrange(perc_qual)
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

```


# Session Info

```{r sessionInfo, cache = FALSE}
sessionInfo()
```

1045
# References
1046 1047 1048