-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathauxilliary.R
1740 lines (1525 loc) · 51.9 KB
/
auxilliary.R
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
## Giotto auxiliary functions ####
#' @title pDataDT
#' @name pDataDT
#' @description show cell metadata
#' @inheritParams data_access_params
#' @param ... additional params to pass
#' @returns data.table with cell metadata
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' pDataDT(g)
#' @export
pDataDT <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
...) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (!inherits(gobject, c("ExpressionSet", "SCESet", "seurat", "giotto"))) {
stop("only works with ExpressionSet (-like) objects")
}
if (inherits(gobject, c("ExpressionSet", "SCESet"))) {
return(data.table::as.data.table(Biobase::pData(gobject)))
} else if (inherits(gobject, "giotto")) {
if (is.null(match.call(expand.dots = TRUE)$output)) {
output <- "data.table"
} else {
output <- match.call(expand.dots = TRUE)$output
}
return(getCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = output
))
} else if (inherits(gobject, "seurat")) {
return(data.table::as.data.table([email protected]))
}
}
#' @title fDataDT
#' @name fDataDT
#' @description show feature metadata
#' @inheritParams data_access_params
#' @param ... additional params to pass
#' @returns data.table with feature metadata
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' fDataDT(g)
#' @export
fDataDT <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
...) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (!inherits(gobject, c("ExpressionSet", "SCESet", "giotto"))) {
stop("only works with ExpressionSet (-like) objects")
} else if (inherits(gobject, "giotto")) {
if (is.null(match.call(expand.dots = TRUE)$output)) {
output <- "data.table"
} else {
output <- match.call(expand.dots = TRUE)$output
}
return(getFeatureMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = output
))
}
return(data.table::as.data.table(Biobase::fData(gobject)))
}
## Feature & Cell metadata functions ####
#' @title Annotate Giotto object
#' @name annotateGiotto
#' @description Map user provided annotations/labels based on another
#' existing metadata column (usually clustering labels)
#' @param gobject `giotto` object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param annotation_vector named `character` vector. Vector names are labels
#' in the cluster column. Labels to assign are the vector values.
#' @param cluster_column `character`. Cell metaadata column to map annotation
#' values based on.
#' @param name new name for annotation column
#' @returns `giotto` object
#' @details You need to specify which (cluster) column you want to annotate
#' and you need to provide an annotation vector like this:
#' \itemize{
#' \item{1. identify the cell type of each cluster}
#' \item{2. create a vector of these cell types, e.g.
#' cell_types = c('T-cell', 'B-cell', 'Stromal')}
#' \item{3. provide original cluster names to previous vector,
#' e.g. names(cell_types) = c(2, 1, 3)}
#' }
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' annotation <- c(
#' "1" = "cell_type_1",
#' "2" = "cell_type_2",
#' "3" = "cell_type_3",
#' "4" = "cell_type_4",
#' "5" = "cell_type_5",
#' "6" = "cell_type_6",
#' "7" = "cell_type_7",
#' "8" = "cell_type_8"
#' )
#'
#' g <- annotateGiotto(g,
#' annotation_vector = annotation,
#' cluster_column = "leiden_clus"
#' )
#' @export
annotateGiotto <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
annotation_vector = NULL,
cluster_column = NULL,
name = "cell_types") {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
# data.table: set global variable
temp_cluster_name <- NULL
if (is.null(annotation_vector) || is.null(cluster_column)) {
stop("\n You need to provide both a named annotation vector and
the corresponding cluster column \n")
}
cell_metadata <- getCellMetadata(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
# 1. verify if cluster column exist
if (!cluster_column %in% colnames(cell_metadata[])) {
stop("\n Cluster column is not found in cell metadata \n")
}
# 2. verify if each cluster has an annotation
uniq_names <- names(annotation_vector)
uniq_clusters <- unique(cell_metadata[][[cluster_column]])
missing_annotations <- uniq_clusters[!uniq_clusters %in% uniq_names]
no_matching_annotations <- uniq_names[!uniq_names %in% uniq_clusters]
# stop if not all clusters in cluster column got a mapped annotation value
if (length(missing_annotations) > 0) {
wrap_msg(
"Not all clusters have an accompanying annotation in the
annotation_vector: \n", "These names are missing: ",
as.character(missing_annotations), "\n",
"These annotations have no match: ",
as.character(no_matching_annotations)
)
stop("Annotation interrupted \n")
}
# 3. remove previous annotation name if it's the same
# but only if new name is not the same as cluster to be used
if (name %in% colnames(cell_metadata[])) {
wrap_msg('annotation name "', name,
'" was already used and will be overwritten',
sep = ""
)
cell_metadata[][, temp_cluster_name := annotation_vector[[
as.character(get(cluster_column))
]], by = seq_len(nrow(cell_metadata[]))]
cell_metadata[][, (name) := NULL]
} else {
cell_metadata[][, temp_cluster_name := annotation_vector[[
as.character(get(cluster_column))
]], by = seq_len(nrow(cell_metadata[]))]
}
data.table::setnames(cell_metadata[], old = "temp_cluster_name", new = name)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setGiotto(gobject, cell_metadata,
verbose = FALSE, initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
return(gobject)
}
#' @title Remove cell annotation
#' @name removeCellAnnotation
#' @description Removes cell annotation from a Giotto object for a specific
#' feature modality (default = 'rna')
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param columns names of columns to remove
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @returns giotto object
#' @details if \code{return_gobject = FALSE}, it will return the cell metadata
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' annotation <- c(
#' "1" = "cell_type_1",
#' "2" = "cell_type_2",
#' "3" = "cell_type_3",
#' "4" = "cell_type_4",
#' "5" = "cell_type_5",
#' "6" = "cell_type_6",
#' "7" = "cell_type_7",
#' "8" = "cell_type_8"
#' )
#'
#' g <- annotateGiotto(g,
#' annotation_vector = annotation,
#' cluster_column = "leiden_clus"
#' )
#'
#' g <- removeCellAnnotation(g, columns = "cell_types")
#' @export
removeCellAnnotation <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
columns = NULL,
return_gobject = TRUE) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (is.null(columns)) {
stop("\t You need to provide a vector of metadata column names to
remove \t")
}
# get cell metadata
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
# remove columns
cell_metadata[] <- cell_metadata[][, (columns) := NULL]
# return giotto object or cell metadata
if (return_gobject == TRUE) {
gobject <- setCellMetadata(gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
return(gobject)
} else {
cell_metadata[]
}
}
#' @title Remove feature annotation
#' @name removeFeatAnnotation
#' @description Removes feature annotation from a Giotto object for a
#' specific feature modality
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param columns names of columns to remove
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @returns giotto object
#' @details if \code{return_gobject = FALSE}, it will return the gene metadata
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' g <- removeFeatAnnotation(g, columns = "hvf")
#' @export
removeFeatAnnotation <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
columns = NULL,
return_gobject = TRUE) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (is.null(columns)) {
stop("\t You need to provide a vector of metadata column names
to remove \t")
}
# get feat metadata
feat_metadata <- getFeatureMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "featMetaObj",
copy_obj = TRUE
)
# remove columns
feat_metadata[] <- feat_metadata[][, (columns) := NULL]
# return giotto object or cell metadata
if (return_gobject == TRUE) {
gobject <- setFeatureMetadata(gobject,
x = feat_metadata,
verbose = FALSE,
initialize = FALSE
)
return(gobject)
} else {
feat_metadata[]
}
}
#' @title Add cell metadata
#' @name addCellMetadata
#' @description Adds cell metadata to the giotto object
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param new_metadata new cell metadata to
#' use (data.table, data.frame, vector, factor, ...)
#' @param vector_name (optional) custom name for new metadata column if single
#' vector or factor is provided
#' @param by_column merge metadata based on \emph{cell_ID} column in
#' \code{\link{pDataDT}} (default = FALSE)
#' @param column_cell_ID column name of new metadata to use if
#' \code{by_column = TRUE}
#' @details You can add additional cell metadata in several manners:
#' \itemize{
#' \item{1. Provide a data.frame-like object, vector, or factor with cell
#' annotations in the same order as the \emph{cell_ID} column in
#' pDataDT(gobject). This is a bit risky and not the most recommended.}
#' \item{2. Provide a data.frame-like object with cell annotations and
#' specify which column contains the cell IDs, these cell IDs need to match
#' with the \emph{cell_ID} column in pDataDT(gobject)}
#' \item{3. Provide a vector or factor that is named with the cell IDs they
#' correspond to. These names will be matched against the \emph{cell_ID}
#' column in pDataDT(gobject).}
#' }
#'
#' @returns giotto object
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' m <- pDataDT(g)
#' m <- m[, c("cell_ID", "leiden_clus")]
#' m$cell_type <- paste0("cell_type_", m$leiden_clus)
#' m <- m[, c("cell_ID", "cell_type")]
#'
#' g <- addCellMetadata(
#' g,
#' new_metadata = m,
#' by_column = TRUE,
#' column_cell_ID = "cell_ID"
#' )
#'
#' pDataDT(g)
#' @export
addCellMetadata <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
new_metadata,
vector_name = NULL,
by_column = FALSE,
column_cell_ID = NULL) {
# NSE variables
cell_ID <- NULL
# 0. set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
# 1. check hierarchical slots
# Expression information must first exist in the gobject for the
# corresponding metadata information to be added.
avail_ex <- list_expression(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (is.null(avail_ex)) {
.gstop(
"No matching expression information discovered for:
spat_unit:", spat_unit, "\nfeature type:", feat_type,
"\nPlease add expression information first"
)
}
# 2. get the cell metadata to add to
cell_metadata <- getCellMetadata(
gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "cellMetaObj",
copy_obj = TRUE
)
# record initial order
ordered_cell_IDs <- spatIDs(cell_metadata)
# 3. format input metadata
# [vector/factor input]
# Values are assumed to be in the same order as the existing metadata info.
# Convert vector or factor into a single-column data.table
# Colname is the variable name of the vector or factor.
# [all other inputs]
# Coerce to data.table
if (is.vector(new_metadata) || is.factor(new_metadata)) {
original_name <- deparse(substitute(new_metadata))
new_metadata <- data.table::as.data.table(
new_metadata,
keep.rownames = TRUE
)
if ("rn" %in% colnames(new_metadata) && ncol(new_metadata) > 1L) {
# should only be TRUE when an "rn" col for rownames was added based
# on the vector or factor's names
data.table::setnames(new_metadata, old = "rn", new = "cell_ID")
}
# add column name for new meta info.
# if a cell_ID col was added via rownames, it should be in the first
# position.
# ncol(new_metadata) should be the col index of the new information.
if (!is.null(vector_name) && is.character(vector_name)) {
colnames(new_metadata)[ncol(new_metadata)] <- vector_name
} else {
colnames(new_metadata)[ncol(new_metadata)] <- original_name
}
} else {
# [DF or DT-like input]
new_metadata <- data.table::as.data.table(new_metadata)
}
# If no specific column_cell_ID is provided, assume "cell_ID"
if (is.null(column_cell_ID)) {
column_cell_ID <- "cell_ID"
}
# 4. combine with existing metadata
# get old and new meta colnames that are not the ID col
new_col_names <- colnames(new_metadata)
new_col_names <- new_col_names[new_col_names != column_cell_ID]
old_col_names <- colnames(cell_metadata)
old_col_names <- old_col_names[old_col_names != "cell_ID"]
# overwrite columns with same name
same_col_names <- new_col_names[new_col_names %in% old_col_names]
if (length(same_col_names) >= 1) {
wrap_msg(
"\nThese column names were already used: ", same_col_names, "\n",
"and will be overwritten \n"
)
cell_metadata[][, (same_col_names) := NULL]
}
if (!isTRUE(by_column)) {
cell_metadata[] <- cbind(cell_metadata[], new_metadata)
} else {
if (!column_cell_ID %in% colnames(new_metadata)) {
stop("'by_column' is TRUE and 'column_cell_ID' not found
in new_metadata")
}
cell_metadata[] <- data.table::merge.data.table(
x = cell_metadata[],
by.x = "cell_ID",
y = new_metadata,
by.y = column_cell_ID,
all.x = TRUE
)
}
# 5. ensure data is in same order as start and set data
cell_metadata[] <- cell_metadata[][match(ordered_cell_IDs, cell_ID)]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setCellMetadata(gobject,
x = cell_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
return(gobject)
}
#' @title Add feature metadata
#' @name addFeatMetadata
#' @description Adds feature metadata to the giotto object
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param new_metadata new metadata to use)
#' @param vector_name (optional) custom name if you provide a single vector
#' @param by_column merge metadata based on \emph{feat_ID} column
#' in \code{\link{fDataDT}}
#' @param column_feat_ID column name of new metadata to use if by_column = TRUE
#' @returns giotto object
#' @details You can add additional feature metadata in several manners:
#' \itemize{
#' \item{1. Provide a data.table or data.frame with feature annotations in
#' the same order as the \emph{feat_ID} column in fDataDT(gobject) This is
#' a bit risky and not the most recommended.}
#' \item{2. Provide a data.table or data.frame with feature annotations and
#' specify which column contains the feature IDs, these feature IDs need to
#' match with the \emph{feat_ID} column in fDataDT(gobject)}
#' \item{3. Provide a vector or factor that is named with the feature IDs
#' they correspond to. These names will be matched against
#' the \emph{feat_ID} column in fDataDT(gobject).}
#' }
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' m <- fDataDT(g)
#' m <- m[, "feat_ID"]
#' m$new_feat_ID <- paste0("gene_", m$feat_ID)
#'
#' g <- addFeatMetadata(
#' g,
#' new_metadata = m,
#' by_column = TRUE,
#' column_feat_ID = "feat_ID"
#' )
#'
#' fDataDT(g)
#' @export
addFeatMetadata <- function(gobject,
feat_type = NULL,
spat_unit = NULL,
new_metadata,
vector_name = NULL,
by_column = FALSE,
column_feat_ID = NULL) {
# NSE variables
feat_ID <- NULL
# 0. set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
# 1. check hierarchical slots
# Expression information must first exist in the gobject for the
# corresponding metadata information to be added.
avail_ex <- list_expression(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
if (is.null(avail_ex)) {
.gstop(
"No matching expression information discovered for:
spat_unit:", spat_unit, "\nfeature type:", feat_type,
"\nPlease add expression information first"
)
}
# 2. get the cell metadata to add to
feat_metadata <- getFeatureMetadata(
gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "featMetaObj",
copy_obj = TRUE
)
ordered_feat_IDs <- featIDs(feat_metadata)
# 3. format input metadata
# [vector/factor input]
# Values are assumed to be in the same order as the existing metadata info.
# Convert vector or factor into a single-column data.table
# Colname is the variable name of the vector or factor.
# [all other inputs]
# Coerce to data.table
if (is.vector(new_metadata) || is.factor(new_metadata)) {
original_name <- deparse(substitute(new_metadata))
new_metadata <- data.table::as.data.table(
new_metadata,
keep.rownames = TRUE
)
if ("rn" %in% colnames(new_metadata) && ncol(new_metadata) > 1L) {
# should only be TRUE when an "rn" col for rownames was added based
# on the vector or factor's names
data.table::setnames(new_metadata, old = "rn", new = "feat_ID")
}
# add column name for new meta info.
# if a cell_ID col was added via rownames, it should be in the first
# position.
# ncol(new_metadata) should be the col index of the new information.
if (!is.null(vector_name) && is.character(vector_name)) {
colnames(new_metadata)[ncol(new_metadata)] <- vector_name
} else {
colnames(new_metadata)[ncol(new_metadata)] <- original_name
}
} else {
# [DF or DT-like input]
new_metadata <- data.table::as.data.table(new_metadata)
}
# If no specific column_feat_ID is provided, assume "feat_ID"
if (is.null(column_feat_ID)) {
column_feat_ID <- "feat_ID"
}
# 4. combine with existing metadata
# get old and new meta colnames that are not the ID col
new_col_names <- colnames(new_metadata)
new_col_names <- new_col_names[new_col_names != column_feat_ID]
old_col_names <- colnames(feat_metadata[])
old_col_names <- old_col_names[old_col_names != "feat_ID"]
# overwrite columns with same name
same_col_names <- new_col_names[new_col_names %in% old_col_names]
if (length(same_col_names) >= 1) {
wrap_msg(
"\nThese column names were already used: ", same_col_names, "\n",
"and will be overwritten \n"
)
feat_metadata[][, (same_col_names) := NULL]
}
if (!isTRUE(by_column)) {
feat_metadata[] <- cbind(feat_metadata[], new_metadata)
} else {
if (!column_feat_ID %in% colnames(new_metadata)) {
stop("'by_column' is TRUE and 'column_feat_ID' not found in
new_metadata")
}
feat_metadata[] <- data.table::merge.data.table(
x = feat_metadata[],
by.x = "feat_ID",
y = new_metadata,
by.y = column_feat_ID,
all.x = TRUE
)
}
# 5. ensure data is in same order and set data
feat_metadata[] <- feat_metadata[][match(ordered_feat_IDs, feat_ID)]
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject <- setFeatureMetadata(gobject,
x = feat_metadata,
verbose = FALSE,
initialize = FALSE
)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
return(gobject)
}
# expression ####
#' @title create_average_DT
#' @description calculates average gene expression for a cell metadata
#' factor (e.g. cluster)
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param meta_data_name name of metadata column to use
#' @param expression_values which expression values to use
#' @returns data.table with average gene expression values for each factor
#' @keywords internal
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' create_average_DT(g, meta_data_name = "leiden_clus")
#' @export
create_average_DT <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
meta_data_name,
expression_values = c("normalized", "scaled", "custom")) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
# expression values to be used
values <- match.arg(
expression_values,
unique(c("normalized", "scaled", "custom", expression_values))
)
expr_data <- getExpression(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
values = values,
output = "matrix"
)
# metadata
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "data.table",
copy_obj = TRUE
)
myrownames <- rownames(expr_data)
savelist <- list()
for (group in unique(cell_metadata[[meta_data_name]])) {
name <- paste0("cluster_", group)
temp <- expr_data[, cell_metadata[[meta_data_name]] == group]
temp_DT <- rowMeans_flex(temp)
savelist[[name]] <- temp_DT
}
finalDF <- do.call("cbind", savelist)
rownames(finalDF) <- myrownames
return(as.data.frame(finalDF))
}
#' @title create_average_detection_DT
#' @description calculates average gene detection for a cell metadata
#' factor (e.g. cluster)
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param meta_data_name name of metadata column to use
#' @param expression_values which expression values to use
#' @param detection_threshold detection threshold to consider a gene detected
#' @returns data.table with average gene epression values for each factor
#' @keywords internal
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' create_average_detection_DT(g, meta_data_name = "leiden_clus")
#' @export
create_average_detection_DT <- function(gobject,
feat_type = NULL,
spat_unit = NULL,
meta_data_name,
expression_values = c("normalized", "scaled", "custom"),
detection_threshold = 0) {
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
# expression values to be used
values <- match.arg(
expression_values,
unique(c("normalized", "scaled", "custom", expression_values))
)
expr_data <- getExpression(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
values = values,
output = "matrix"
)
# metadata
cell_metadata <- getCellMetadata(gobject,
spat_unit = spat_unit,
feat_type = feat_type,
output = "data.table",
copy_obj = TRUE
)
myrownames <- rownames(expr_data)
savelist <- list()
for (group in unique(cell_metadata[[meta_data_name]])) {
name <- paste0("cluster_", group)
temp <- expr_data[, cell_metadata[[meta_data_name]] == group]
temp <- as.matrix(temp)
if (is.matrix(temp)) {
temp_DT <- rowSums_flex(temp > detection_threshold) / ncol(temp)
} else {
temp_DT <- as.numeric(temp > detection_threshold)
}
savelist[[name]] <- temp_DT
}
finalDF <- do.call("cbind", savelist)
rownames(finalDF) <- myrownames
return(as.data.frame(finalDF))
}
#' @title create_cluster_matrix
#' @name create_cluster_matrix
#' @description creates aggregated matrix for a given clustering column
#' @inheritParams data_access_params
#' @param expression_values name of expression values to use
#' @param cluster_column name of cluster column to use,
#' @param feat_subset subset of features to use
#' @param gene_subset deprecated do not use.
#' @returns matrix
#' @keywords internal
#' @examples
#' g <- GiottoData::loadGiottoMini("visium")
#'
#' create_cluster_matrix(g, cluster_column = "leiden_clus")
#' @export
create_cluster_matrix <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
expression_values = c("normalized", "scaled", "custom"),
cluster_column,
feat_subset = NULL,
gene_subset = NULL) {
# data.table variables
feats <- NULL
## deprecated arguments
if (!is.null(gene_subset)) {
feat_subset <- gene_subset
}
# Set feat_type and spat_unit
spat_unit <- set_default_spat_unit(
gobject = gobject,
spat_unit = spat_unit
)
feat_type <- set_default_feat_type(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type
)
values <- match.arg(
expression_values,
unique(c("normalized", "scaled", "custom", expression_values))
)
# average expression per cluster
aggr_sc_clusters <- create_average_DT(
gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
meta_data_name = cluster_column,
expression_values = values
)
aggr_sc_clusters_DT <- data.table::as.data.table(aggr_sc_clusters)
aggr_sc_clusters_DT[, feats := rownames(aggr_sc_clusters)]
aggr_sc_clusters_DT_melt <- data.table::melt.data.table(aggr_sc_clusters_DT,
variable.name = "cluster",
id.vars = "feats",
value.name = "expression"
)
# create matrix
testmat <- data.table::dcast.data.table(aggr_sc_clusters_DT_melt,
formula = feats ~ cluster,
value.var = "expression"
)
testmatrix <- dt_to_matrix(testmat)
# create subset if required
if (!is.null(feat_subset)) {
feat_subset_detected <- feat_subset[
feat_subset %in% rownames(testmatrix)
]
testmatrix <- testmatrix[
rownames(testmatrix) %in% feat_subset_detected,
]
}
return(testmatrix)
}