-
Notifications
You must be signed in to change notification settings - Fork 9
/
README.Rmd
executable file
·488 lines (370 loc) · 14.1 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
478
479
480
481
482
483
484
485
486
487
488
---
title: "tidySingleCellExperiment - part of tidytranscriptomics"
output: github_document
always_allow_html: true
---
<!-- badges: start -->
[![Lifecycle:maturing](https://img.shields.io/badge/lifecycle-maturing-blue.svg)](https://www.tidyverse.org/lifecycle/#maturing) [![R build status](https://github.com/stemangiola/tidySingleCellExperiment/workflows/R-CMD-check-bioc/badge.svg)](https://github.com/stemangiola/tidySingleCellExperiment/actions)
<!-- badges: end -->
```{r echo=FALSE}
knitr::opts_chunk$set(fig.path = "inst/extdata/readme_figures/")
```
**Brings SingleCellExperiment to the tidyverse!**
Website: [tidySingleCellExperiment](https://stemangiola.github.io/tidySingleCellExperiment/articles/introduction.html)
Please also have a look at
- [tidySummarizedExperiment](https://stemangiola.github.io/tidySummarizedExperiment/) for tidy manipulation of SummarizedExperiment objects)
- [tidyseurat](https://stemangiola.github.io/tidyseurat/) for tidy manipulation of Seurat objects
- [tidybulk](https://stemangiola.github.io/tidybulk/) for tidy bulk RNA-seq data analysis
- [tidygate](https://github.com/stemangiola/tidygate) for adding custom gate information to your tibble
- [tidyHeatmap](https://stemangiola.github.io/tidyHeatmap/) for heatmaps produced with tidy principles
# Introduction
tidySingleCellExperiment provides a bridge between Bioconductor single-cell packages [@amezquita2019orchestrating] and the tidyverse [@wickham2019welcome]. It enables viewing the
Bioconductor *SingleCellExperiment* object as a tidyverse tibble, and provides SingleCellExperiment-compatible *dplyr*, *tidyr*, *ggplot* and *plotly* functions. This allows users to get the best of both Bioconductor and tidyverse worlds.
## Functions/utilities available
SingleCellExperiment-compatible Functions | Description
------------ | -------------
`all` | After all `tidySingleCellExperiment` is a SingleCellExperiment object, just better
tidyverse Packages | Description
------------ | -------------
`dplyr` | All `dplyr` tibble functions (e.g. `select`)
`tidyr` | All `tidyr` tibble functions (e.g. `pivot_longer`)
`ggplot2` | `ggplot` (`ggplot`)
`plotly` | `plot_ly` (`plot_ly`)
Utilities | Description
------------ | -------------
`as_tibble` | Convert cell-wise information to a `tbl_df`
`join_features` | Add feature-wise information, returns a `tbl_df`
`aggregate_cells` | Aggregate cell gene-transcription abundance as pseudobulk tissue
## Installation
```{r, eval=FALSE}
if (!requireNamespace("BiocManager", quietly=TRUE))
install.packages("BiocManager")
BiocManager::install("tidySingleCellExperiment")
```
Load libraries used in this vignette.
```{r message=FALSE}
# Bioconductor single-cell packages
library(scater)
library(scran)
library(SingleR)
library(SingleCellSignalR)
# Tidyverse-compatible packages
library(purrr)
library(magrittr)
library(tidyHeatmap)
# Both
library(tidySingleCellExperiment)
```
# Data representation of `tidySingleCellExperiment`
This is a *SingleCellExperiment* object but it is evaluated as a tibble. So it is compatible both with SingleCellExperiment and tidyverse.
```{r}
data(pbmc_small, package="tidySingleCellExperiment")
```
**It looks like a tibble**
```{r}
pbmc_small
```
**But it is a SingleCellExperiment object after all**
```{r}
assay(pbmc_small, "counts")[1:5, 1:5]
```
The `SingleCellExperiment` object's tibble visualisation can be turned off, or back on at any time.
```{r}
# Turn off the tibble visualisation
options("restore_SingleCellExperiment_show" = TRUE)
pbmc_small
```
```{r}
# Turn on the tibble visualisation
options("restore_SingleCellExperiment_show" = FALSE)
```
# Annotation polishing
We may have a column that contains the directory each run was taken from, such as the "file" column in `pbmc_small`.
```{r}
pbmc_small$file[1:5]
```
We may want to extract the run/sample name out of it into a separate column. Tidyverse `extract` can be used to convert a character column into multiple columns using regular expression groups.
```{r}
# Create sample column
pbmc_small_polished <-
pbmc_small |>
extract(file, "sample", "../data/([a-z0-9]+)/outs.+", remove=FALSE)
# Reorder to have sample column up front
pbmc_small_polished |>
select(sample, everything())
```
# Preliminary plots
Set colours and theme for plots.
```{r}
# Use colourblind-friendly colours
friendly_cols <- dittoSeq::dittoColors()
# Set theme
custom_theme <-
list(
scale_fill_manual(values=friendly_cols),
scale_color_manual(values=friendly_cols),
theme_bw() +
theme(
panel.border=element_blank(),
axis.line=element_line(),
panel.grid.major=element_line(size=0.2),
panel.grid.minor=element_line(size=0.1),
text=element_text(size=12),
legend.position="bottom",
aspect.ratio=1,
strip.background=element_blank(),
axis.title.x=element_text(margin=margin(t=10, r=10, b=10, l=10)),
axis.title.y=element_text(margin=margin(t=10, r=10, b=10, l=10))
)
)
```
We can treat `pbmc_small_polished` as a tibble for plotting.
Here we plot number of features per cell.
```{r plot1}
pbmc_small_polished |>
ggplot(aes(nFeature_RNA, fill=groups)) +
geom_histogram() +
custom_theme
```
Here we plot total features per cell.
```{r plot2}
pbmc_small_polished |>
ggplot(aes(groups, nCount_RNA, fill=groups)) +
geom_boxplot(outlier.shape=NA) +
geom_jitter(width=0.1) +
custom_theme
```
Here we plot abundance of two features for each group.
```{r}
pbmc_small_polished |>
join_features(features=c("HLA-DRA", "LYZ")) |>
ggplot(aes(groups, .abundance_counts + 1, fill=groups)) +
geom_boxplot(outlier.shape=NA) +
geom_jitter(aes(size=nCount_RNA), alpha=0.5, width=0.2) +
scale_y_log10() +
custom_theme
```
# Preprocess the dataset
We can also treat `pbmc_small_polished` as a *SingleCellExperiment* object and proceed with data processing with Bioconductor packages, such as *scran* [@lun2016pooling] and *scater* [@mccarthy2017scater].
```{r preprocess}
# Identify variable genes with scran
variable_genes <-
pbmc_small_polished |>
modelGeneVar() |>
getTopHVGs(prop=0.1)
# Perform PCA with scater
pbmc_small_pca <-
pbmc_small_polished |>
runPCA(subset_row=variable_genes)
pbmc_small_pca
```
If a tidyverse-compatible package is not included in the tidySingleCellExperiment collection, we can use `as_tibble` to permanently convert `tidySingleCellExperiment` into a tibble.
```{r pc_plot}
# Create pairs plot with GGally
pbmc_small_pca |>
as_tibble() |>
select(contains("PC"), everything()) |>
GGally::ggpairs(columns=1:5, ggplot2::aes(colour=groups)) +
custom_theme
```
# Identify clusters
We can proceed with cluster identification with *scran*.
```{r cluster}
pbmc_small_cluster <- pbmc_small_pca
# Assign clusters to the 'colLabels' of the SingleCellExperiment object
colLabels(pbmc_small_cluster) <-
pbmc_small_pca |>
buildSNNGraph(use.dimred="PCA") |>
igraph::cluster_walktrap() %$%
membership |>
as.factor()
# Reorder columns
pbmc_small_cluster |> select(label, everything())
```
And interrogate the output as if it was a regular tibble.
```{r cluster count}
# Count number of cells for each cluster per group
pbmc_small_cluster |>
count(groups, label)
```
We can identify and visualise cluster markers combining SingleCellExperiment, tidyverse functions and tidyHeatmap [@mangiola2020tidyheatmap]
```{r}
# Identify top 10 markers per cluster
marker_genes <-
pbmc_small_cluster |>
findMarkers(groups=pbmc_small_cluster$label) |>
as.list() |>
map(~ .x |>
head(10) |>
rownames()) |>
unlist()
# Plot heatmap
pbmc_small_cluster |>
join_features(features=marker_genes) |>
group_by(label) |>
heatmap(.feature, .cell, .abundance_counts, .scale="column")
```
# Reduce dimensions
We can calculate the first 3 UMAP dimensions using the SingleCellExperiment framework and *scater*.
```{r umap}
pbmc_small_UMAP <-
pbmc_small_cluster |>
runUMAP(ncomponents=3)
```
And we can plot the result in 3D using plotly.
```{r umap plot, eval=FALSE}
pbmc_small_UMAP |>
plot_ly(
x=~`UMAP1`,
y=~`UMAP2`,
z=~`UMAP3`,
color=~label,
colors=friendly_cols[1:4]
)
```
![plotly screenshot](inst/extdata/plotly.png)
# Cell type prediction
We can infer cell type identities using *SingleR* [@aran2019reference] and manipulate the output using tidyverse.
```{r eval=FALSE}
# Get cell type reference data
blueprint <- celldex::BlueprintEncodeData()
# Infer cell identities
cell_type_df <-
assays(pbmc_small_UMAP)$logcounts |>
Matrix::Matrix(sparse = TRUE) |>
SingleR::SingleR(
ref = blueprint,
labels = blueprint$label.main,
method = "single"
) |>
as.data.frame() |>
as_tibble(rownames="cell") |>
select(cell, first.labels)
```
```{r}
# Join UMAP and cell type info
data(cell_type_df)
pbmc_small_cell_type <-
pbmc_small_UMAP |>
left_join(cell_type_df, by="cell")
# Reorder columns
pbmc_small_cell_type |>
select(cell, first.labels, everything())
```
We can easily summarise the results. For example, we can see how cell type classification overlaps with cluster classification.
```{r}
# Count number of cells for each cell type per cluster
pbmc_small_cell_type |>
count(label, first.labels)
```
We can easily reshape the data for building information-rich faceted plots.
```{r}
pbmc_small_cell_type |>
# Reshape and add classifier column
pivot_longer(
cols=c(label, first.labels),
names_to="classifier", values_to="label"
) |>
# UMAP plots for cell type and cluster
ggplot(aes(UMAP1, UMAP2, color=label)) +
geom_point() +
facet_wrap(~classifier) +
custom_theme
```
We can easily plot gene correlation per cell category, adding multi-layer annotations.
```{r}
pbmc_small_cell_type |>
# Add some mitochondrial abundance values
mutate(mitochondrial=rnorm(dplyr::n())) |>
# Plot correlation
join_features(features=c("CST3", "LYZ"), shape="wide") |>
ggplot(aes(CST3 + 1, LYZ + 1, color=groups, size=mitochondrial)) +
geom_point() +
facet_wrap(~first.labels, scales="free") +
scale_x_log10() +
scale_y_log10() +
custom_theme
```
# Nested analyses
A powerful tool we can use with tidySingleCellExperiment is tidyverse `nest`. We can easily perform independent analyses on subsets of the dataset. First we classify cell types into lymphoid and myeloid, and then nest based on the new classification.
```{r}
pbmc_small_nested <-
pbmc_small_cell_type |>
filter(first.labels != "Erythrocytes") |>
mutate(cell_class=dplyr::if_else(`first.labels` %in% c("Macrophages", "Monocytes"), "myeloid", "lymphoid")) |>
nest(data=-cell_class)
pbmc_small_nested
```
Now we can independently for the lymphoid and myeloid subsets (i) find variable features, (ii) reduce dimensions, and (iii) cluster using both tidyverse and SingleCellExperiment seamlessly.
```{r warning=FALSE}
pbmc_small_nested_reanalysed <-
pbmc_small_nested |>
mutate(data=map(
data, ~ {
.x <- runPCA(.x, subset_row=variable_genes)
variable_genes <-
.x |>
modelGeneVar() |>
getTopHVGs(prop=0.3)
colLabels(.x) <-
.x |>
buildSNNGraph(use.dimred="PCA") |>
igraph::cluster_walktrap() %$%
membership |>
as.factor()
.x |> runUMAP(ncomponents=3)
}
))
pbmc_small_nested_reanalysed
```
We can then unnest and plot the new classification.
```{r}
pbmc_small_nested_reanalysed |>
# Convert to tibble otherwise SingleCellExperiment drops reduced dimensions when unifying data sets.
mutate(data=map(data, ~ .x |> as_tibble())) |>
unnest(data) |>
# Define unique clusters
unite("cluster", c(cell_class, label), remove=FALSE) |>
# Plotting
ggplot(aes(UMAP1, UMAP2, color=cluster)) +
geom_point() +
facet_wrap(~cell_class) +
custom_theme
```
We can perform a large number of functional analyses on data subsets. For example, we can identify intra-sample cell-cell interactions using *SingleCellSignalR* [@cabello2020singlecellsignalr], and then compare whether interactions are stronger or weaker across conditions. The code below demonstrates how this analysis could be performed. It won't work with this small example dataset as we have just two samples (one for each condition). But some example output is shown below and you can imagine how you can use tidyverse on the output to perform t-tests and visualisation.
```{r, eval=FALSE}
pbmc_small_nested_interactions <-
pbmc_small_nested_reanalysed |>
# Unnest based on cell category
unnest(data) |>
# Create unambiguous clusters
mutate(integrated_clusters=first.labels |> as.factor() |> as.integer()) |>
# Nest based on sample
nest(data=-sample) |>
mutate(interactions=map(data, ~ {
# Produce variables. Yuck!
cluster <- colData(.x)$integrated_clusters
data <- data.frame(assays(.x) |> as.list() |> extract2(1) |> as.matrix())
# Ligand/Receptor analysis using SingleCellSignalR
data |>
cell_signaling(genes=rownames(data), cluster=cluster) |>
inter_network(data=data, signal=_, genes=rownames(data), cluster=cluster) %$%
`individual-networks` |>
map_dfr(~ bind_rows(as_tibble(.x)))
}))
pbmc_small_nested_interactions |>
select(-data) |>
unnest(interactions)
```
If the dataset was not so small, and interactions could be identified, you would see something like below.
```{r}
data(pbmc_small_nested_interactions)
pbmc_small_nested_interactions
```
# Aggregating cells
Sometimes, it is necessary to aggregate the gene-transcript abundance from a group of cells into a single value. For example, when comparing groups of cells across different samples with fixed-effect models.
In tidySingleCellExperiment, cell aggregation can be achieved using the `aggregate_cells` function.
```{r}
pbmc_small |>
aggregate_cells(groups, assays = "counts")
```