-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4b_scRNA-TCR_pbmc.Rmd
2230 lines (1913 loc) · 92.9 KB
/
4b_scRNA-TCR_pbmc.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
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
571
572
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
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
784
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
810
811
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
837
838
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "scRNA/TCR analysis - PBMC"
author: "Daniel Shu"
date: 'Compiled: `r format(Sys.Date(), "%B %d, %Y")`'
output:
html_document:
keep_md: yes
toc: true
toc_float: true
collapsed: true
toc_depth: 3
number_sections: true
theme: lumen
editor_options:
markdown:
wrap: 72
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = F,
warning = F, cache=F,
tidy = T,
dpi = 600, fig.width = 12, fig.height = 8)
```
# I. Setup
## A. Load libraries
```{r libraries}
library(Seurat)
library(ggplot2)
library(ggpubr)
library(patchwork)
library(ggprism)
library(tidyverse)
library(tools)
library(scRepertoire)
library(gridExtra)
library(kableExtra)
library(RColorBrewer)
library(pals)
library(ggnewscale)
library("grid")
library("gridExtra")
library("cowplot")
```
## B. Define export settings
```{r settings}
source = "10x"
analysis = "sc"
#Define the repertoire under study: "T" or "B"
repertoire = "T"
#define type of repertoire
type = "pbmc" #pbmc or til
#set azimuth level for analysis
az_level = "l3"
output.path = paste0("./output/single_cell/",
ifelse(repertoire=="T", "T", "B"),
"_", type, "_azimuth_", az_level,
"/")
#creates output.path directory if not already present
ifelse(!dir.exists(output.path), dir.create(output.path), paste0(output.path, " ", "directory already exists"))
```
## C. Load scripts
```{r scripts}
source("scripts/multibarHeatmap.R") # Load multibarHeatmap script
source("./scripts/T_cell_goi.R") # Define GOI
```
# II. Load data
### A. First load TCR/BCR filtered contig files
```{r}
#Create data.dir for clonotypes and filtered contig files
vdj.dir <- "./data/single_cell/vdj"
#Create list of filtered contig files, named for each sample, sample type (PBMC or TIL), and type of repertoire (T or B cell)
fc.filenames <- list.files(vdj.dir, pattern="filtered_contig_annotations.csv", recursive=T, full.names = T)
# the files now need to be reordered such in same order as the order in which the suffixes were barcode suffixes were applied in the pre-processing code. otherwise, matching TCRs to cell barcodes will fail due to the incorrect suffix.
fc.filenames = c(
fc.filenames[grep("PBMC_P02_",fc.filenames)],
fc.filenames[grep("PBMC_P03_",fc.filenames)],
fc.filenames[grep("PBMC_P07_",fc.filenames)],
fc.filenames[grep("PBMC_P08_",fc.filenames)],
fc.filenames[grep("PBMC_P12_",fc.filenames)],
fc.filenames[grep("PBMC_OT1_",fc.filenames)],
fc.filenames[grep("PBMC_OT6_",fc.filenames)],
fc.filenames[grep("TIL_OT6_",fc.filenames)]) #this preserves order where the _B repertoire comes before its corresponding _T repertoire
fc.list <- list()
for(i in fc.filenames){
fc.list[[i]] = read.table(i,
header = T,
stringsAsFactors = F,
as.is = T,
fill = T,
comment.char = "",
sep = ',')
}
fc.filenames.short <- list.files(vdj.dir, pattern="filtered_contig_annotations.csv", recursive=T, full.names = F) %>%
str_replace("/.*", "")
names(fc.list) = fc.filenames.short
names(fc.list)
# For the filtered contigs, the barcode suffixes for each sample are "-1". To facilitate integration with the seurat object, for each patient we need to remove "-1" from the suffix of the barcode and append "-" followed by the corresponding number of the sample ("1" through "8"). This makes the barcodes for each sample distinct.
# first create vector of character strings to make barcodes of filtered contig$barcode match barcodes in seurat object
suffix <- rep(c(1:8),each=2) %>% as.character()
# then replace "-1" with "-1", "-2", "-3"..."-8" according to the sample number
for(i in 1:length(fc.list)) {
fc.list[[i]][,1] = gsub("-.*",
paste0("-",
suffix[i]
)
, fc.list[[i]][,1]
)
}
#subset the list according to repertoire under analysis ("T or B")
if (repertoire == "T") {
contig_list <- fc.list[grep("_T",names(fc.list))]
} else {
contig_list <- fc.list[grep("_B",names(fc.list))]
}
names(contig_list)
rm(fc.list)
# Combine the T and B cell contigs using combineTCR and combineBCR functions
#Code below is based on 'Starting work with scRepertoire v1.5.2.' (https://ncborcherding.github.io/vignettes/vignette.html) Website is dated 5/12/2022. I accessed it on 5/24/2022
if (repertoire == "T") {
combined <- combineTCR(contig_list,
samples = gsub(".*[_]([^_]+)[_].*", "\\1", names(contig_list)), #returns "HCC02" "HCC08" "HCC09" "HCC13" "HCC14" "OT1" "OT6" "OT6"
ID = sub("\\_.*", "", names(contig_list)), #returns: "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "TIL"
cells = "T-AB")
rm(contig_list)
} else {
combined <- combineBCR(contig_list,
samples = gsub(".*[_]([^_]+)[_].*", "\\1", names(contig_list)), #returns "HCC02" "HCC08" "HCC09" "HCC13" "HCC14" "OT1" "OT6" "OT6"
ID = sub("\\_.*", "", names(contig_list)) #returns: "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "PBMC" "TIL"
)
rm(contig_list)
}
#Cleanup the 'combined' object for subsequent analysis by replacing the initial string from the barcodes in each list with T or B -- this facilitates later integration with the seurat object
if (repertoire == "T") {
for(i in 1:length(combined)) {
combined[[i]][,1] = gsub(".*[_]([^_]+)[_]_*", "T-", combined[[i]][,1])
}
} else {
for(i in 1:length(combined)) {
combined[[i]][,1] = gsub(".*[_]([^_]+)[_]_*", "B-", combined[[i]][,1])
}
}
# saveRDS(combined, file = paste0(output.path, "combined.rds"))
# combined <- readRDS(paste0(output.path,"combined.rds"))
```
### B. Load the seurat object produced from data pre-processing.
For preprocessing code, see "./scRNA-all-preprocessing.Rmd."
Note that in the object seurat, the scaled data in the SCT assay is not present in the refAssay. This website (<https://github.com/satijalab/seurat/issues/5959>) notes that the refAssay lacks corrected UMI counts, so I switched the active.assay to SCT. see also here <https://github.com/satijalab/seurat/issues/2163>
```{r load_seurat}
#load seurat
seurat <- readRDS("./output/single_cell/10x_scRNASeq_all_seurat_az_pbmc.rds")
#set active assay to SCT
DefaultAssay(seurat) <- "SCT"
#Assign identities based on azimuth
Idents(seurat) <- paste0("predicted.celltype.", az_level)
#Re-order idents, which are out of order.
if (az_level == "l2") {
levels.manual <- c("B naive","B intermediate","B memory", "Plasmablast",
"CD4 Naive","CD4 Proliferating","CD4 TCM","CD4 TEM","CD4 CTL",
"CD8 Naive","CD8 Proliferating","CD8 TCM","CD8 TEM","NK","NK Proliferating",
"Treg","dnT","gdT","MAIT",
"CD14 Mono","CD16 Mono","Platelet")
}
if (az_level == "l3") {
levels.manual <- c("B naive kappa","B naive lambda", "B intermediate kappa", "B intermediate lambda", "B memory kappa","B memory lambda", "Plasma",
"CD14 Mono","CD16 Mono",
"CD4 Naive","CD4 Proliferating", "CD4 TCM_1","CD4 TCM_2","CD4 TCM_3","CD4 TEM_1","CD4 TEM_2","CD4 TEM_3","CD4 CTL",
"CD8 Naive","CD8 Naive_2","CD8 Proliferating",
"CD8 TCM_1","CD8 TCM_2","CD8 TCM_3",
"CD8 TEM_1","CD8 TEM_2","CD8 TEM_3","CD8 TEM_4","CD8 TEM_5","CD8 TEM_6",
"NK Proliferating","NK_1","NK_2",
"Treg Naive", "Treg Memory","dnT_1","dnT_2", "gdT_1","gdT_2","gdT_3","gdT_4","MAIT",
"ILC","Platelet")
}
Idents(seurat) <- factor(x = Idents(seurat), levels = levels.manual)
Idents(seurat) %>% levels
cells.by.type <- table(Idents(seurat)) %>% as.data.frame()
ggplot(cells.by.type, aes(x = Var1, #reorder(Var1, desc(Freq)),
y = Freq, fill=Var1))+
geom_col()+ #scale_fill_manual(values=pals::kovesi.rainbow_bgyr_35_85_c72(nrow(cells.by.type)))+
ggprism::theme_prism()+theme(axis.text.x = element_text(angle=45, hjust=1, vjust=1))+theme(legend.position="null")+ggtitle("Single cells per cluster")+xlab("Cluster")+ylab("Cell count")
ggsave(paste0(output.path,"summary_all_B_and_T_asbarplot.pdf"), height=10, width=10)
cells.by.type %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total"))%>%
kbl(caption = "Summary of all cell types (B and T)", align = 'c') %>%
kable_classic(full_width=F) %>%
save_kable(., paste0(output.path, "summary_all_B_and_T.pdf"))
cells.by.type %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total"))
DimPlot(seurat)+guides(colour = guide_legend(ncol = 2))
ggsave(paste0(output.path, "dimplot_all_T_and_B.pdf"), height=10, width=10)
#Subset for sample under analysis and add initial "T-" or "B-" to barcode
if (repertoire == "T") {
T.clustOfInterest = "CD4|CD8|Treg|dnT|gdT|ILC|MAIT|NK"
seurat.idents = unique(Idents(seurat))
T.idents <- seurat.idents[grep(T.clustOfInterest, seurat.idents)]
seurat <- subset(seurat, idents = T.idents)
seurat <- RenameCells(seurat, new.names = paste0("T-", rownames(seurat[[]])))
} else {
# this is the case where repertoire == "B"
B.clustOfInterest = "B naive|B intermediate|B memory|Plasma"
seurat.idents = unique(Idents(seurat))
B.idents <- seurat.idents[grep(B.clustOfInterest, seurat.idents)]
seurat <- subset(seurat, idents = B.idents)
seurat <- RenameCells(seurat, new.names = paste0("B-", rownames(seurat[[]])))
}
table(Idents(seurat)) %>% as.data.frame() %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total"))
## Subset to remove outlier singletons using cellSelector
DimPlot(seurat#,cols=cluster_colors
) +ggtitle(paste0("T cell clusters in TIL prior to singletons removal (n=", nrow([email protected]), ")"))
ggsave(filename = paste0(output.path, "dimplot_before_singleton_removal.pdf"),width = 12, height = 8)
plot <- DimPlot(seurat)
likelyB <- CellSelector(plot = plot) #select cells on far right where B cells clusters were
likelyTIL <- CellSelector(plot = plot) #select singleton cells in northeast of UMAP where TIL was
expected = [email protected] %>% nrow - length(c(likelyB,likelyTIL)) #predict expected # of cells after subsetting out likelyB and likelyTIL
expected
seurat <- subset(seurat, cells = c(likelyB, likelyTIL), invert=T)
nrow([email protected]) == expected #confirm correct subsetting
rm(plot)
DimPlot(seurat#,cols=cluster_colors
) +ggtitle(paste0("T cell clusters in PBMC after singletons removal (n=", nrow([email protected]), ")"))
ggsave(filename = paste0(output.path, "dimplot_after_singleton_removal.pdf"),width = 12, height = 8)
# saveRDS(seurat, paste0(output.path, "seurat_after_singleton_removal.rds"))
# seurat <- readRDS(file=paste0(output.path,"seurat_after_singleton_removal.rds"))
```
### C. Run FindAllMarkers and make heatmap to refine cluster idents
```{r}
markers <- FindAllMarkers(seurat, test.use = "MAST", only.pos = TRUE, min.pct = 0.1, logfc.threshold = 0.25)
# saveRDS(markers, file=paste0(output.path,"findAllMarkers.rds"))
# markers <- readRDS(paste0(output.path,"findAllMarkers.rds"))
markers %>%
group_by(cluster) %>%
slice_max(n = 3, order_by = avg_log2FC)
markers %>%
group_by(cluster) %>%
top_n(n =10, wt = avg_log2FC) -> top10
markers %>%
group_by(cluster) %>%
top_n(n =5, wt = avg_log2FC) -> top5
markers %>%
group_by(cluster) %>%
top_n(n =3, wt = avg_log2FC) -> top3
#getting this error when I try to do DoHeatmap
# Error in Seurat::DoHeatmap(seurat, features = top10, size = 2) :
# No requested features found in the scale.data slot for the SCT assay.
# so rescaling the data per https://github.com/satijalab/seurat/issues/2960
seurat<-ScaleData(seurat, features=c(markers$gene,goi.all), verbose = FALSE)#this line makes sure that all of the variable features (in markers object) and all of the genes of interest are included in the scaledata used for the heatmap
pdf(paste0(output.path,"FindAllMarkers_before_cluster_annotation.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=top5$gene,size=1)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 5))
dev.off()
Seurat::DoHeatmap(seurat,features=top3$gene,size=1)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 5))
dev.off()
pdf(paste0(output.path,"GOI_all_before_cluster_annotation.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=goi.all,size = 1)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 5))
dev.off()
# saveRDS(seurat, paste0(output.path, "seurat_after_singleton_removal_findallmarkers_round1.rds"))
# seurat <- readRDS(file=paste0(output.path,"seurat_after_singleton_removal_findallmarkers_round1.rds"))
```
### D.1 Reassign cluster idents
```{r load_seurat2}
## Collapse the clusters that are not the focus of this analysis (i.e. e.g. Treg naive + Treg memory -> Treg, etc.). Here I have applied this to NKT)
cluster_merge = data.frame(old_id = levels(seurat), new_id = NA, level=NA)
write.csv(cluster_merge,"output/single_cell/cluster_merge_PBMC.csv",row.names=F)
#edit that file with manual cluster assignments then reupload
cluster_merge_DS <- read.csv("output/single_cell/cluster_merge_DS.csv")
cluster_merge_DS = cluster_merge_DS[order(cluster_merge_DS$level),] #reorder by level column, which will be used below to facilitate levels assignment
#set colors for clusters
cluster_colors = pals::alphabet(n=length(unique(cluster_merge_DS$new_id))+2)
cluster_colors = cluster_colors[-grep("iron|ebony",names(cluster_colors))] #drops black
names(cluster_colors) = unique(cluster_merge_DS$new_id)
cluster_colors %>% pal.bands()
#######################
#assign new identities
new.cluster.ids = cluster_merge_DS$new_id
names(new.cluster.ids) = cluster_merge_DS$old_id
new.cluster.ids
if (all(unique(Idents(seurat)) %in% names(new.cluster.ids)) == T) { #doublechecks that the new.cluster.ids has a new ident for each old ident, before subsetting the new.cluster.ids object for what is in Idents(seura)
new.cluster.ids <- new.cluster.ids[names(new.cluster.ids) %in% Idents(seurat)] #rename the clusteres that are present in the dataset
}
seurat <- RenameIdents(seurat, new.cluster.ids)
#add active.ident column to seurat object (will be used below for stacked barplots)
seurat$active.ident <- Idents(seurat)
Idents(seurat) %>% table #check idents
#set levels
levels.manual = unique(cluster_merge_DS$new_id)
Idents(seurat) <- factor(x = Idents(seurat), levels = levels.manual)
pdf(paste0(output.path,"DimPlot_after_annotation.pdf"))
DimPlot(seurat,cols=cluster_colors)
dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_labeled.pdf"))
DimPlot(seurat,cols=cluster_colors,label=T,repel=T)
dev.off()
# ## subset to remove clusters where there are fewer than 50 cells (in this case, CD4 Proliferating, CD8 Proliferating)
seurat <- subset(x = seurat, idents = c("CD4 Proliferating",
"CD8 Proliferating"), invert=T)
cluster_colors = cluster_colors[!names(cluster_colors) %in% c("CD8 Proliferating","CD4 Proliferating")]
levels.manual = levels.manual[levels.manual %in% Idents(seurat)]
Idents(seurat) <- factor(x = Idents(seurat), levels = levels.manual)
pdf(paste0(output.path,"DimPlot_after_annotation_lessthan50removed.pdf"));DimPlot(seurat,cols=cluster_colors);dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_labeled_lessthan50removed.pdf"));DimPlot(seurat,cols=cluster_colors,label=T,repel=T);dev.off()
#
# saveRDS(seurat, paste0(output.path, "seurat_after_singleton_removal_after_annotation_final.rds"))
# seurat <- readRDS(file=paste0(output.path, "seurat_after_singleton_removal_after_annotation_final.rds"))
```
### D.2 Manual curation
#### A. Check gdT
There are scattered cells in the MAIT and a few other clusters with increased TRDV2 and TRGV9 expression, suggesting that these should be re-assigned to the gdt cluster. Here we make plots to identify those cells, then reassign them to the gdT cluster. We define gdt as any cell with both TRDV2 and TRGV9 > 0.
```{r}
pdf(paste0(output.path,"Heatmap_before_MAITgdT_reassignment.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=top3$gene,size = 2)+
theme(
# legend.text = element_text(size = 5),
axis.text.y = element_text(size = 5))&NoLegend()
Seurat::DoHeatmap(seurat,features = c("TRDV2", "TRGV9"), #features=top3$gene,
size = 2)+
theme(
# legend.text = element_text(size = 5),
axis.text.y = element_text(size = 5))&NoLegend()
dev.off()
pdf(paste0(output.path,"gdT_qc_plots.pdf"),width=14,height=8)
RidgePlot(seurat,features=c("TRDV2","TRGV9"))
VlnPlot(seurat,features=c("TRDV2","TRGV9"))
FeaturePlot(seurat,features=c("TRDV2","TRGV9"))
FeaturePlot(seurat,features=c("TRDV2","TRGV9"),blend=T)
FeatureScatter(seurat, feature1 = "TRDV2", feature2 = "TRGV9",pt.size=2,cols=cluster_colors,jitter=T)
dev.off()
```
#### B. Reassign non-gdT -> gdt
what we found is 3 populations.
- 1 population, with TRDV2 and TRGV9 both > 0. We will pull those out and reassign them to gdT.
- Within the pre-existing gdT population, 1 population TRDV2 and TRGV9 both at 0. We will pull those out and reassign them to another cluster.
- Within the pre-existing gdT population, other cells that have TRDV2 or TRGV9 > 0, but not both. We will leave those in the gdT population, assuming that the clustering
```{r}
gdt_in <- subset(x = seurat, subset = TRDV2 > 0 & TRGV9 > 0)
[email protected] %>% table
[email protected] %>% table
select.cells <- colnames(gdt_in)
select.cells
Idents(seurat, cells = select.cells) <- "NewCells"
[email protected][[email protected]=="gdT"] %>% length
FeatureScatter(seurat, feature1 = "TRDV2", feature2 = "TRGV9",pt.size=2,cols=cluster_colors,jitter=T)
#doublecheck these cells by running findmarkers
newcells.markers <- FindMarkers(seurat, ident.1 = "NewCells", ident.2 = "CD8 TEM_GZMB", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
#findmarkers output is c/w gdT, specifically there is high expression of KLRC1, TRGC1, TRDC, TRGV9, TRGDV2. so we assign this population to gdT
Idents(seurat, cells = select.cells) <- "gdT"
Idents(seurat) %>% table
```
#### C. Reassign gdT -> non-gdT
```{r}
###################################
#### now part 2, we extract from the gdT cluster those cells that express TRDV2 and TRGV9 at 0
gdt_out <- subset(x = seurat, idents = "gdT",
subset = TRDV2 == 0 & TRGV9 == 0)
[email protected] %>% table
select.cells <- colnames(gdt_out)
select.cells
Idents(seurat, cells = select.cells) <- "OutCells"
FeatureScatter(gdt_out, feature1 = "TRDV2", feature2 = "TRGV9",pt.size=2,cols=cluster_colors) #checks that expression is 0
#checks whether these are CD8 or CD4
FeatureScatter(seurat, cells=select.cells,feature1 = "CD4", feature2 = "CD8A")
VlnPlot(seurat, idents="OutCells",
features=c("CCR7", "LEF1", "TCF7",
"LTB", "NR4A2",
"CD4", "CD8A", "CD8B",
"CXCL13","ICOS", "PDCD1", "CTLA4",
"GZMK", "GZMB","TOX","MAF",
"RTKN2", "FOXP3", "IK2F2",
"TRDC"), #Treg
ncol=4)
VlnPlot(seurat,idents="OutCells",
features = c("TRDC", "TRGC1", "TRGC2",
"KLRC1", "NKG7", "TRDV2", "CD7",
"TRGV9", "KLRD1", "KLRG1")) #gdT markers
#based on above markers, these appear to be CD8 Naive or C8 TCM, or gamma delta (based on high TRDC)
#doublecheck these cells by running findmarkers
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "CD8 Naive", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "CD8 TCM", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "gdT", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
outcell_check <- subset(x = seurat,
idents = c(
"CD8 Naive", "CD8 TCM",
"gdT", "OutCells"))
pdf(paste0(output.path,"gdT_qc_plots_outCell_check.pdf"),width=14,height=8)
Seurat::DoHeatmap(outcell_check,features=top3$gene,size = 2)+
theme(
# legend.text = element_text(size = 5),
axis.text.y = element_text(size = 5))&NoLegend()
dev.off()
#based on this heatmap, there apepars to be two populations within OutCells. One that has TRDV1 or TRDC high expression, which is likely a gdT population, and a second that has high CD8A/C8B expression. that is likely a naive-like population
FeatureScatter(seurat, cells=select.cells,feature1 = "TRDV1", feature2 = "CD8A")
FeatureScatter(seurat, cells=select.cells,feature1 = "TRDC", feature2 = "CD8A")
#so i'll put out those expressors of TRDV1 and put them back with the gdTs
gdT_putBack <- subset(x = seurat,
subset = TRDV1 > 0 |
TRDC > 0 |
TRGC1 > 0 |
TRGC2 > 0,
idents = "OutCells")
select.cells_putback <- colnames(gdT_putBack)
select.cells_putback
Idents(seurat,cells=select.cells_putback) <- "gdT"
#### now re-plot the previous QC plots
#checks whether these are CD8 or CD4
VlnPlot(seurat, idents="OutCells",
features=c("CCR7", "LEF1", "TCF7",
"LTB", "NR4A2",
"CD4", "CD8A", "CD8B",
"CXCL13","ICOS", "PDCD1", "CTLA4",
"GZMK", "GZMB","TOX","MAF",
"RTKN2", "FOXP3", "IK2F2"), #Treg
ncol=4)
VlnPlot(seurat,idents="OutCells",
features = c("TRDC", "TRGC1", "TRGC2",
"KLRC1", "NKG7", "TRDV2", "CD7",
"TRGV9", "KLRD1", "KLRG1")) #gdT markers
#based on above markers, these appear to be CD8 Naive or C8 TCM, or gamma delta (based on high TRDC)
#doublecheck these cells by running findmarkers
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "CD8 Naive", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "CD8 TCM", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
newcells.markers <- FindMarkers(seurat, ident.1 = "OutCells", ident.2 = "gdT", min.diff.pct = 0.3,
only.pos = TRUE)
newcells.markers %>% arrange(.,avg_log2FC)
outcell_check <- subset(x = seurat,
idents = c(
"CD8 Naive", "CD8 TCM",
"gdT", "OutCells"))
pdf(paste0(output.path,"gdT_qc_plots_outCell_check_2.pdf"),width=14,height=8)
Seurat::DoHeatmap(outcell_check,features=top3$gene,size = 2)+
theme(
# legend.text = element_text(size = 5),
axis.text.y = element_text(size = 5))&NoLegend()
dev.off()
#finally, assign cells to OutCells group to CD8 Naive
[email protected] %>% table
gdT_OutCells <- subset(x = seurat,
idents = c("OutCells"))
select.cells.OutCells <- colnames(gdT_OutCells)
select.cells.OutCells
Idents(seurat, cells = select.cells.OutCells) <- "CD8 Naive"
Idents(seurat) %>% table
```
#### C. Re-set levels and set active.ident column
```{r}
#need to re-set the levels
levels(seurat)
Idents(seurat) <- factor(x = Idents(seurat), levels = levels.manual)
#set active.ident column
seurat$active.ident <- Idents(seurat)
## make new dimplot and save
pdf(paste0(output.path,"DimPlot_after_annotation_gdT_reassigned.pdf"));
DimPlot(seurat,cols=cluster_colors);
dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_gdT_reassigned.pdf_noLegend.pdf"));
DimPlot(seurat,cols=cluster_colors)&NoLegend();
dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_gdT_reassigned.pdf_noLegend_noAxes.pdf"));
DimPlot(seurat,cols=cluster_colors)&NoLegend()&NoAxes();
dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_gdT_reassigned.pdf_yesLegend_noAxes.pdf"));
DimPlot(seurat,cols=cluster_colors)&NoAxes()#&NoLegend()
dev.off()
pdf(paste0(output.path,"DimPlot_after_annotation_gdT_reassigned.pdf"));
DimPlot(seurat,cols=cluster_colors,label=T,repel=T);
dev.off()
# saveRDS(seurat, paste0(output.path, "seurat_after_annotation_gdT_reassigned.rds"))
# seurat <- readRDS(seurat, file=paste0(output.path, "seurat_after_annotation_gdT_reassigned.rds"))
```
### E.1. Re-run findallmarkers and make new figures
```{r}
markers <- FindAllMarkers(seurat, test.use = "MAST", only.pos = TRUE, min.pct = 0.1, logfc.threshold = 0.25)
#
# saveRDS(markers, file=paste0(output.path,"findAllMarkers_post_clusterassignment.rds"))
# markers <- readRDS(paste0(output.path,"findAllMarkers_post_clusterassignment.rds"))
markers.list <- markers %>% split(.,.$cluster)
writexl::write_xlsx(markers.list, path=paste0(output.path,"markers_list.xlsx"))
#subset to remove mitochondrial genes
nrow(markers)
grep("MT-",markers$gene)
markers$gene[grep("MT-",markers$gene)]
markers = markers[-grep("MT-",markers$gene),]
grep("MT-",markers$gene)
nrow(markers)
markers %>%
group_by(cluster) %>%
slice_max(n = 3, order_by = avg_log2FC)
markers %>%
group_by(cluster) %>%
top_n(n =10, wt = avg_log2FC) -> top10
markers %>%
group_by(cluster) %>%
top_n(n =5, wt = avg_log2FC) -> top5
markers %>%
group_by(cluster) %>%
top_n(n =3, wt = avg_log2FC) -> top3
seurat<-ScaleData(seurat, features=c(markers$gene,goi.all), verbose = FALSE)
#make new heatmaps
pdf(paste0(output.path,"FindAllMarkers_after_singleton_removal_after_cluster_annotation.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=top5$gene,size=2)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 6))
Seurat::DoHeatmap(seurat,features=top10$gene,size=2)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 5))
dev.off()
pdf(paste0(output.path,"FindAllMarkers_after_singleton_removal_after_cluster_annotation_top3.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=top3$gene,size=2)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 6))
dev.off()
#make another version of this that is downsampled for the heatmap
seurat_downsampled <- subset(x = seurat, downsample = 150)
pdf(paste0(output.path,"FindAllMarkers_after_singleton_removal_after_cluster_annotation_top3_downsampled.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat_downsampled,features=top3$gene,size=2)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 6))
dev.off()
rm(seurat_downsampled)
pdf(paste0(output.path,"GOI_all__after_singleton_removal_after_cluster_annotation.pdf"),width=12,height=8)
Seurat::DoHeatmap(seurat,features=goi.all,size = 2)+
theme(legend.text = element_text(size = 4),
axis.text.y = element_text(size = 5))
dev.off()
```
### E.2. make figures and tables for final object
```{r load_seurat_plots}
#############################################################################
##### make figures and tables for final object
# make dimplot of final clustering of all samples
DimPlot(seurat, cols=cluster_colors)+
ggtitle(paste0(ifelse(repertoire=="T", "T", "B"),
" cell clusters in sc", str_to_upper(type),
" (n = ", nrow([email protected]), ")")) +
ggprism::theme_prism()+
theme(legend.position = "right", legend.text = element_text(size=10))
ggsave(filename = paste0(output.path, "dimplot_all_including_cells_without_TCR.pdf"),width = 12, height = 8)
#make barplot and table
cells.by.type.t.only <- table(Idents(seurat)) %>% as.data.frame()
ggplot(cells.by.type.t.only, aes(x = reorder(Var1, Freq),
y = Freq, fill=Var1))+
geom_col()+ scale_fill_manual(values=cluster_colors)+
geom_text(aes(label = Freq), hjust =-0.2)+
ggprism::theme_prism()+theme(axis.text.x = element_text(angle=45, hjust=1,vjust=1))+
theme(legend.position="null")+ggtitle("Single cells per cluster")+xlab("")+ylab("Cell count")+coord_flip(clip="off")+
theme(plot.margin = unit(c(1,2,1,1), "lines"))
ggsave(paste0(output.path,"summary_all_T_only_asbarplot.pdf"), width=5, height=7)
cells.by.type.t.only %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total")) %>%
kbl(caption = "Summary of all cell types (after subsetting for T cells, low counts not removed)", align = 'c') %>%
kable_classic(full_width=F) %>%
save_kable(., paste0(output.path, "summary_all_T_only.pdf"))
#DimPlot by patient
DimPlot(seurat, cols=cluster_colors, split.by = 'Patient', ncol=3)+
ggprism::theme_prism()
ggsave(filename = paste0(output.path, "dimplot_all_including_cells_without_TCR_byPatient.pdf"),width = 12, height = 8)
df <- [email protected] %>% select(Patient, active.ident) %>% group_by(Patient, active.ident) %>% summarise(activeIdent_n=n()) %>% ungroup() #%>% bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total"))
ggplot(df, aes(fill = Patient, x=reorder(active.ident, activeIdent_n), y=activeIdent_n))+
geom_bar(position="stack",stat="identity")+ ggprism::theme_prism()+coord_flip()+
scale_fill_manual(values=pals::brewer.rdylbu(7))+
ggtitle("Single cells per cluster, by patient")+xlab("")+ylab("Cell count")
ggsave(paste0(output.path,"dimplot_all_including_cells_without_TCR_byPatient_asbarplot.pdf"), width=5, height=7)
```
### F.1 Add scTCR/BCR data to seurat
```{r add_tcrbcr}
#combine TCR or BCR data with seurat object
#note that I have previously changed the barcodes in the combined file for each sample to match the barcodes in the seurat object
seurat <- combineExpression(combined, seurat,
cloneCall="gene", group.by = "sample", proportion = FALSE,
cloneTypes=c(Single=1, Small=5, Medium=20, Large=100, Hyperexpanded=500))
[email protected]$cloneType <- factor([email protected]$cloneType, levels = c(
"Hyperexpanded (100 < X <= 500)",
"Large (20 < X <= 100)",
"Medium (5 < X <= 20)",
"Small (1 < X <= 5)",
"Single (0 < X <= 1)", NA))
#Subset seurat object to remove cells lacking a barcode (i.e. without TCR/BCR)
#Before doing this, create 2 table to give sense of # of cells removed
[email protected]$hasTCR = if_else(is.na([email protected]$barcode), "No", "Yes")
[email protected] %>% count(hasTCR, sort=T) %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total")) %>%
kbl(caption = "Summary of cells with and without TCRs", align = 'c') %>%
kable_classic(full_width=F) %>%
save_kable(., paste0(output.path, "summary_cells_with_without_TCR.pdf"))
[email protected] %>% count(active.ident, hasTCR) %>% group_by(active.ident) %>% arrange(desc(hasTCR), .by_group=T) %>% ungroup %>% bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total")) %>%
kbl(caption = "Summary of cells with and without TCRs, by cluster", align = 'c') %>%
kable_classic(full_width=F) %>%
save_kable(., paste0(output.path, "summary_cells_with_without_TCR_byCluster.pdf"))
#
# #Save seurat object
# seurat <- readRDS(paste0(output.path,"seurat_after_TCR.rds"))
# saveRDS(seurat, file=paste0(output.path,"seurat_after_TCR.rds"))
```
### G. Add Adaptive TLS TCR/IGH data
```{r map_clonotypes}
#load adaptive HCC_immdata with additional info re: specific TLS
adaptiveTLS <- readRDS("output/adaptive/TCRB/HCC_immdata_TLS_TCRB_final_for_seurat.rds")
adaptiveTLS$meta$Patient.ID = factor(adaptiveTLS$meta$Patient.ID, levels = unique(adaptiveTLS$meta$Patient.ID))
names(adaptiveTLS$data)
names(adaptiveTLS$data) = names(adaptiveTLS$data) %>% str_replace("J17136", "")
adaptiveTLS$meta$Sample = adaptiveTLS$meta$Sample %>% str_replace("J17136", "")
#make pseudoTIL object
adaptive <- adaptiveTLS$data %>%
bind_rows(.,.id="Patient") %>%
mutate_at("Patient",str_replace,"-.*", "") %>%
uncount(.,Clones) %>% #uncount clones column
select(-Proportion) %>%
select(Patient,CDR3.aa) %>% #,V.name,D.name,J.name,Sequence) %>%
group_by(Patient,CDR3.aa) %>%
mutate(Clones=n(), .after = "Patient") %>%
distinct(CDR3.aa, .keep_all=T) %>%
ungroup() %>% group_by(Patient) %>%
mutate(Proportion = Clones/sum(.$Clones), .after=Clones) %>%
arrange(desc(Clones)) %>%
mutate(Rank=1:n(), .before = "Patient") %>% ungroup() %>%
split(.,.$Patient)
adaptive %>% names
adaptive = adaptive[levels(adaptiveTLS$meta$Patient.ID)] #reorder adaptive object
adaptive %>% names
#this is housekeeping to doublecheck the number of duplicated CDR3aa and CDRnt per sample in the adaptive data
x<- lapply(1:length(adaptive), function(i) {
adaptive[[i]][duplicated(adaptive[[i]]$CDR3.aa) | duplicated(adaptive[[i]]$CDR3.aa, fromLast =T),] %>%
nrow
}) %>% unlist
df <- tibble(names(adaptive), sapply(adaptive, nrow), x)
colnames(df) = c("sample", "total.clonotypes", "duplicated.cdr3.aa")#, "duplicated.cdr3.nt"
df
#########
#create adaptive.bindrows object, which will be used to determine which TCRs are present in TLS
adaptive.bindrows <- adaptive %>% #removes OT1-TDLN and OT6-TDLN
bind_rows(., .id = "Sample") %>% #collapses list into one dataframe
dplyr::select(-'Patient') #removes "Patient" column, leaving "Sample" which will be used below
#Add column to seurat object for TCRB or IGH data (this allows cross-referencing of single cell against Adaptive datasets)
seurat$TCRB_or_IGH <- gsub(".*_", "", [email protected]$CTaa)
# add the second column for TCRB or IGH
seurat$TCRB_or_IGH2 = NA
# find entries that should be split by ;
tosplit = grep(";",seurat$TCRB_or_IGH )
# split by ";" and add the second part to TCRB_or_IGH2
[email protected][tosplit,"TCRB_or_IGH2"] <- sapply(strsplit([email protected][tosplit,"TCRB_or_IGH"],";"), function(x) x[[2]])
# and replace TCRB_or_IGH with the first half
# you need to do it in this order, otherwise you will loose the second part
[email protected][tosplit,"TCRB_or_IGH"] <- sapply(strsplit([email protected][tosplit,"TCRB_or_IGH"],";"), function(x) x[[1]])
#these 3 lines doublecheck that this worked
[email protected][tosplit, "TCRB_or_IGH"]
[email protected][tosplit, "TCRB_or_IGH2"]
grep(";",seurat$TCRB_or_IGH ) %>% length
##########
#now add column to seurat metadata and adaptive.bindrows with sample name_tcrb -- this will facilitate adding a column to single cell metadata that shows if the TCRB is present in patient's TLS
seurat$patient_tcrb <- paste([email protected]$Patient, [email protected]$TCRB_or_IGH, sep="_") #this and belone line does create instances of HCC02_NA, etc. but this is okay because there are no NAs in the CDR3.aa in the adaptive data
seurat$patient_tcrb2 <- paste([email protected]$Patient, [email protected]$TCRB_or_IGH2, sep="_")
adaptive.bindrows$Sample_CDR3.aa <- paste(adaptive.bindrows$Sample, adaptive.bindrows$CDR3.aa, sep="_")
#Add column to seurat object if there is any match in TLS sequencing data for that particular patient
seurat$TLS.present1 <- ifelse([email protected]$patient_tcrb %in% adaptive.bindrows$Sample_CDR3.aa, 1, 0)
seurat$TLS.present2 <- ifelse([email protected]$patient_tcrb2 %in% adaptive.bindrows$Sample_CDR3.aa, 1, 0)
#consolidate the two columns into one column, which is true if either of the two TCRBs were found in the patient's TLS
seurat$TLS.present = ifelse(seurat$TLS.present1+seurat$TLS.present2 >= 1, 1, 0)
[email protected][tosplit,c("TLS.present", "TLS.present1", "TLS.present2")]
#########
#Now create adaptive.excludeSingletons which is adaptive.bindrows subsetted for Clones > 1, i.e. the TLS data excluding singletons
#Then add column to seurat object if the clone is expanded in TLS (count > 1), i.e. present in the now .excludeSingletons object
adaptive.excludeSingletons = adaptive.bindrows[adaptive.bindrows$Clones > 1,]
seurat$TLS.expanded1 <- ifelse([email protected]$patient_tcrb %in% adaptive.excludeSingletons$Sample_CDR3.aa, 1,0)
seurat$TLS.expanded2 <- ifelse([email protected]$patient_tcrb2 %in% adaptive.excludeSingletons$Sample_CDR3.aa, 1,0)
seurat$TLS.expanded = ifelse(seurat$TLS.expanded1+seurat$TLS.expanded2 >= 1, 1, 0)
#create object seurat.TLS, which is a subset of seurat metadata that contains only cells present in TLS (clones >=1)
seurat.TLS <- [email protected] %>% filter(TLS.present==1)
#Create object seurat.TLS.excludeSingletons, which is a subset of seurat metadata that contains only cells with TCRs expanded in TLS (clones >1)
seurat.TLS.excludeSingletons <- [email protected] %>% filter(TLS.expanded == 1)
#create 2 lists with the suffix .bypatient, which are seurat.TLs and seurat.TLS.excludeSingletons split by orig.ident
seurat.TLS.bypatient <- split(seurat.TLS, f=seurat.TLS$orig.ident)
seurat.TLS.excludeSingletons.bypatient <- split(seurat.TLS.excludeSingletons, f=seurat.TLS.excludeSingletons$orig.ident)
#remove adaptive.bindrows object
rm(adaptive.bindrows)
# saveRDS(seurat, file=paste0(output.path,"seurat_post_addition_of_TCR.rds"))
# seurat <- readRDS(paste0(output.path,"seurat_post_addition_of_TCR.rds"))
```
### H. Summarize cross-referenced single cell and TLS data
```{r basic statistics-1}
summaryTable_by_cluster <- [email protected] %>% group_by(active.ident) %>%
summarise(
Total_cells=n(),
Total_cells_with_TCR=sum(hasTCR=="Yes"),
Total_cells_with_TCR_expanded=sum(Frequency>1, na.rm=T),
# Total_unique_TCRB=(n_distinct(c(TCRB_or_IGH,TCRB_or_IGH2))),
Cells_with_TCR_in_TLS=sum(TLS.present)
) %>%
bind_rows(summarise(.,across(where(is.numeric), sum), across(where(is.factor), ~"Total"))) %>%
mutate(Total_cells_with_TCR_expanded = paste0(Total_cells_with_TCR_expanded, " (", round(100*Total_cells_with_TCR_expanded/Total_cells_with_TCR,1), ")")) %>%
mutate(Cells_with_TCR_in_TLS = paste0(Cells_with_TCR_in_TLS, " (", round(100*Cells_with_TCR_in_TLS/Total_cells_with_TCR,1), ")")) %>%
rename(c(
'Cluster' = active.ident,
'Cells, n' = Total_cells,
'Cells with TCR, n' = Total_cells_with_TCR,
'Cells with expanded TCRs, n (%)' = Total_cells_with_TCR_expanded,
'Cells with TCR\u03B2 in TLS, n (%)' = Cells_with_TCR_in_TLS#,
# 'Unique TCR\u03B2 in TLS, n (%)'= Unique_TCRs_in_TLS
))
summaryTable_by_cluster
summaryTable_by_cluster %>%
writexl::write_xlsx(.,paste0(output.path, "summaryTable_by_cluster_final.xlsx"))
summaryTable_by_cluster %>%
kbl(caption = "Summary of cross-referenced single cell data by cluster", align = 'c') %>%
kable_classic(full_width=F) %>%
save_kable(., paste0(output.path, "summaryTable_by_cluster_final.pdf"))
rm(summaryTable_by_cluster)
#####################
names.Patient <- unique([email protected]$Patient)
all.TCR = c()
all.TCR.recovered = c()
unique.TCR = c()
unique.TCR.recovered = c()
unique.TCR.singleton = c()
unique.TCR.singleton.recovered = c()
unique.TCR.expanded = c()
unique.TCR.expanded.recovered = c()
for (i in 1:length(names.Patient)) {
all.TCR = c(all.TCR, sum(adaptive[[i]]$Clones))
all.TCR.recovered = c(all.TCR.recovered, length(seurat.TLS[seurat.TLS$Patient == names.Patient[i],]$TCRB_or_IGH))
unique.TCR = c(unique.TCR, nrow(adaptive[[i]]))
unique.TCR.recovered = c(unique.TCR.recovered, length(unique(seurat.TLS[seurat.TLS$Patient == names.Patient[i],]$TCRB_or_IGH)))
uniqueSharedTCR= unique(seurat.TLS[seurat.TLS$Patient == names.Patient[i],]$TCRB_or_IGH)
unique.TCR.singleton = c(unique.TCR.singleton, nrow(adaptive[[i]][adaptive[[i]]$Clones == 1,]))
unique.TCR.singleton.recovered = c(unique.TCR.singleton.recovered,
nrow(adaptive[[i]][adaptive[[i]]$Clones ==1 & adaptive[[i]]$CDR3.aa%in% uniqueSharedTCR,]))
unique.TCR.expanded = c(unique.TCR.expanded, nrow(adaptive[[i]][adaptive[[i]]$Clones > 1,]))
unique.TCR.expanded.recovered = c(unique.TCR.expanded.recovered,
nrow(adaptive[[i]][adaptive[[i]]$Clones > 1 & adaptive[[i]]$CDR3.aa%in% uniqueSharedTCR,]))
}
top10.pct = c()
top10.pct.recovered = c()
top1.pct = c()
top1.pct.recovered = c()
top01.pct = c()
top01.pct.recovered = c()
for (i in 1:length(names.Patient)) {
uniqueSharedTCR= unique(seurat.TLS[seurat.TLS$Patient == names.Patient[i],]$TCRB_or_IGH)
top10.pct = c(top10.pct, round(nrow(adaptive[[i]]) *.1))
top10.pct.recovered = c(top10.pct.recovered,
sum(adaptive[[i]][1:round(nrow(adaptive[[i]]) *.1),]$CDR3.aa %in% uniqueSharedTCR))
top1.pct = c(top1.pct, round(nrow(adaptive[[i]]) *.01))
top1.pct.recovered = c(top1.pct.recovered,
sum(adaptive[[i]][1:round(nrow(adaptive[[i]]) *.01),]$CDR3.aa %in% uniqueSharedTCR))
top01.pct = c(top01.pct, round(nrow(adaptive[[i]]) *.001))
top01.pct.recovered = c(top01.pct.recovered,
sum(adaptive[[i]][1:round(nrow(adaptive[[i]]) *.001),]$CDR3.aa %in% uniqueSharedTCR))
}
df3 = data.frame("Patient" = names.Patient,
unique.TCR,unique.TCR.recovered,
top10.pct, top10.pct.recovered,
top1.pct, top1.pct.recovered,
top01.pct,top01.pct.recovered) %>%
bind_rows(summarise_all(., ~if(is.numeric(.)) {sum(.)} else "Total")) %>%
mutate(., 'Total TCR\u03B2 matched, n (%)' = paste0(unique.TCR.recovered, "/", unique.TCR,
" (", signif(unique.TCR.recovered/unique.TCR *100, digits = 2), ")"),
.after = unique.TCR) %>%
mutate(., 'Top 10% of TCR\u03B2 matched, n (%)' = paste0(top10.pct.recovered, "/", top10.pct,
" (",
signif(top10.pct.recovered/top10.pct *100, digits = 2),
")"), .after = top10.pct) %>%
mutate(., 'Top 1% of TCR\u03B2 matched, n (%)' = paste0(top1.pct.recovered, "/", top1.pct,
" (",
signif(top1.pct.recovered/top1.pct *100, digits = 3),
")"), .after = top1.pct) %>%
mutate(., 'Top 0.1% of TCR\u03B2 matched, n (%)' = paste0(top01.pct.recovered, "/", top01.pct,
" (",
signif(top01.pct.recovered/top01.pct *100, digits = 2),
")"), .after = top01.pct) %>%
select(-c(unique.TCR,
unique.TCR.recovered,
top10.pct, top10.pct.recovered,
top1.pct, top1.pct.recovered,
top01.pct,top01.pct.recovered)) # %>% #removes redundant columns
# rename('Unique TCR\u03B2 in TLS, n' = unique.TCR#,
# 'Top 10% of TCR\u03B2, n' = top10.pct, 'Top 1% of TCR\u03B2, n' = top1.pct, 'Top 0.1% of TCR\u03B2, n' = top01.pct
# )
df3
df3 %>%
kbl(caption = "Summary of cross-referenced TLS data (v. 3)", align = 'c') %>%
kable_classic(full_width=F) %>%
# add_header_above(c(" " = 1, "Unique" = 2, "Top 10%" = 2, "Top 1%" = 2, "Top 0.1%" = 2)) %>%
save_kable(., paste0(output.path, "summaryTable_TLS_TCRB_matching_to_singleCell_final.pdf"))
df3 %>%
writexl::write_xlsx(.,paste0(output.path, "summaryTable_TLS_TCRB_matching_to_singleCell_final.xlsx"))
```
### I. Set levels
```{r}
[email protected]$Patient = factor([email protected]$Patient, levels=unique([email protected]$Patient))
[email protected]$orig.ident = factor([email protected]$orig.ident, levels=unique([email protected]$orig.ident))
# if loading previously saved, uncomment all 3 lines below
saveRDS(seurat, file=paste0(output.path,"seurat_pbmc_final.rds"))
# seurat <- readRDS(paste0(output.path,"seurat_pbmc_final.rds"))
# levels.manual = Idents(seurat) %>% levels
saveRDS(cluster_colors, file=paste0(output.path,"cluster_colors_final.rds"))
# cluster_colors <- readRDS(paste0(output.path,"cluster_colors_final.rds"))
```
# III. Analysis
### A. RNA-seq analysis
#### 1. FindAllMarkers Heatmaps
```{r plot_FindAllMarkers}
hasTCR_colors = c("darkblue", "lightblue")
names(hasTCR_colors) = c("Yes","No")
cloneType_colors = rev(pals::brewer.purd(3+length(levels([email protected]$cloneType)))[4:(3+length(levels([email protected]$cloneType)))])
names(cloneType_colors) = levels([email protected]$cloneType)