Last updated: 2021-11-12

Checks: 7 0

Knit directory: Multispectral HCC/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20210728) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 1a7cca3. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/.DS_Store
    Ignored:    analysis/figure/
    Ignored:    code/
    Ignored:    data/
    Ignored:    old/
    Ignored:    output/.DS_Store
    Ignored:    output/cores_3/.DS_Store
    Ignored:    output/silhouette.nmf.rds
    Ignored:    output/tumor.hc.nmf.all.3.rds
    Ignored:    output/tumor.hc.nmf.rank.1.rds
    Ignored:    output/tumor.hc.nmf.rank.10.rds
    Ignored:    output/tumor.hc.umap.rds

Untracked files:
    Untracked:  core_cluster_fractions.pdf
    Untracked:  output/cores_3/09_12058_T_HCC1_Core[1,5,O]_[64353,10620].tif.pdf
    Untracked:  output/cores_3/09_12058_T_HCC1_Core[1,5,O]_[64353,10620]_composite_image.tif.pdf
    Untracked:  output/cores_3/10_19418_T_HCC1_Core[1,7,F]_[52018,13307].tif.pdf
    Untracked:  output/cores_3/10_19418_T_HCC1_Core[1,7,F]_[52018,13307]_composite_image.tif.pdf
    Untracked:  output/cores_3/11_19586_T_HCC1_Core[1,1,L]_[60801,3853].tif.pdf
    Untracked:  output/cores_3/11_19586_T_HCC1_Core[1,1,L]_[60801,3853]_composite_image.tif.pdf
    Untracked:  output/cores_3/11_22196_T_HCC1_Core[1,7,L]_[60177,13499].tif.pdf
    Untracked:  output/cores_3/11_22196_T_HCC1_Core[1,7,L]_[60177,13499]_composite_image.tif.pdf
    Untracked:  output/cores_3/12_291_T_HCC1_Core[1,5,K]_[58929,10236].tif.pdf
    Untracked:  output/cores_3/12_291_T_HCC1_Core[1,5,K]_[58929,10236]_composite_image.tif.pdf
    Untracked:  output/cores_3/14_55372_T_HCC2_Core[1,4,I]_[52796,8447].tif.pdf
    Untracked:  output/cores_3/14_55372_T_HCC2_Core[1,4,I]_[52796,8447]_composite_image.tif.pdf
    Untracked:  output/cores_3/15_04414_T_HCC2_Core[1,6,D]_[44733,11134].tif.pdf
    Untracked:  output/cores_3/15_04414_T_HCC2_Core[1,6,D]_[44733,11134]_composite_image.tif.pdf
    Untracked:  output/cores_3/tif_clusters.zip

Unstaged changes:
    Modified:   output/cores_3/07_4662.png
    Modified:   output/cores_3/08_27704.png
    Modified:   output/cores_3/09_12058.png
    Modified:   output/cores_3/09_19505.png
    Modified:   output/cores_3/10_1150.png
    Modified:   output/cores_3/10_16169.png
    Modified:   output/cores_3/10_19418.png
    Modified:   output/cores_3/10_26818.png
    Modified:   output/cores_3/10_26871.png
    Modified:   output/cores_3/10_28011.png
    Modified:   output/cores_3/10_6446.png
    Modified:   output/cores_3/10_7994.png
    Modified:   output/cores_3/10_8486.png
    Modified:   output/cores_3/11_17328.png
    Modified:   output/cores_3/11_18529.png
    Modified:   output/cores_3/11_19586.png
    Modified:   output/cores_3/11_19933.png
    Modified:   output/cores_3/11_20683.png
    Modified:   output/cores_3/11_22196.png
    Modified:   output/cores_3/11_25684.png
    Modified:   output/cores_3/11_25993.png
    Modified:   output/cores_3/11_26686.png
    Modified:   output/cores_3/11_3580.png
    Modified:   output/cores_3/11_8671.png
    Modified:   output/cores_3/11_9225.png
    Modified:   output/cores_3/12_10971.png
    Modified:   output/cores_3/12_20368.png
    Modified:   output/cores_3/12_21031.png
    Modified:   output/cores_3/12_28533.png
    Modified:   output/cores_3/12_291.png
    Modified:   output/cores_3/12_29804.png
    Modified:   output/cores_3/12_32083.png
    Modified:   output/cores_3/12_8132.png
    Modified:   output/cores_3/13_20857.png
    Modified:   output/cores_3/13_30248.png
    Modified:   output/cores_3/13_372.png
    Modified:   output/cores_3/13_9790.png
    Modified:   output/cores_3/14_10898.png
    Modified:   output/cores_3/14_11220.png
    Modified:   output/cores_3/14_50885.png
    Modified:   output/cores_3/14_55372.png
    Modified:   output/cores_3/14_5837.png
    Modified:   output/cores_3/14_5897.png
    Modified:   output/cores_3/14_62694.png
    Modified:   output/cores_3/14_62836.png
    Modified:   output/cores_3/14_64469.png
    Modified:   output/cores_3/14_65050.png
    Modified:   output/cores_3/14_65563.png
    Modified:   output/cores_3/14_65641.png
    Modified:   output/cores_3/14_65723.png
    Modified:   output/cores_3/14_66422.png
    Modified:   output/cores_3/14_8155.png
    Modified:   output/cores_3/15_04414.png
    Modified:   output/cores_3/15_10312.png
    Modified:   output/cores_3/15_24019.png
    Modified:   output/cores_3/15_28478.png
    Modified:   output/cores_3/16_02092.png
    Modified:   output/cores_3/16_20351.png
    Deleted:    output/cores_4/07_4662.png
    Deleted:    output/cores_4/08_27704.png
    Deleted:    output/cores_4/09_12058.png
    Deleted:    output/cores_4/09_19505.png
    Deleted:    output/cores_4/10_1150.png
    Deleted:    output/cores_4/10_16169.png
    Deleted:    output/cores_4/10_19418.png
    Deleted:    output/cores_4/10_26818.png
    Deleted:    output/cores_4/10_26871.png
    Deleted:    output/cores_4/10_28011.png
    Deleted:    output/cores_4/10_6446.png
    Deleted:    output/cores_4/10_7994.png
    Deleted:    output/cores_4/10_8486.png
    Deleted:    output/cores_4/11_17328.png
    Deleted:    output/cores_4/11_18529.png
    Deleted:    output/cores_4/11_19586.png
    Deleted:    output/cores_4/11_19933.png
    Deleted:    output/cores_4/11_20683.png
    Deleted:    output/cores_4/11_22196.png
    Deleted:    output/cores_4/11_25684.png
    Deleted:    output/cores_4/11_25993.png
    Deleted:    output/cores_4/11_26686.png
    Deleted:    output/cores_4/11_3580.png
    Deleted:    output/cores_4/11_8671.png
    Deleted:    output/cores_4/11_9225.png
    Deleted:    output/cores_4/12_10971.png
    Deleted:    output/cores_4/12_20368.png
    Deleted:    output/cores_4/12_21031.png
    Deleted:    output/cores_4/12_28533.png
    Deleted:    output/cores_4/12_291.png
    Deleted:    output/cores_4/12_29804.png
    Deleted:    output/cores_4/12_32083.png
    Deleted:    output/cores_4/12_8132.png
    Deleted:    output/cores_4/13_20857.png
    Deleted:    output/cores_4/13_30248.png
    Deleted:    output/cores_4/13_372.png
    Deleted:    output/cores_4/13_9790.png
    Deleted:    output/cores_4/14_10898.png
    Deleted:    output/cores_4/14_11220.png
    Deleted:    output/cores_4/14_50885.png
    Deleted:    output/cores_4/14_55372.png
    Deleted:    output/cores_4/14_5837.png
    Deleted:    output/cores_4/14_5897.png
    Deleted:    output/cores_4/14_62694.png
    Deleted:    output/cores_4/14_62836.png
    Deleted:    output/cores_4/14_64469.png
    Deleted:    output/cores_4/14_65050.png
    Deleted:    output/cores_4/14_65563.png
    Deleted:    output/cores_4/14_65641.png
    Deleted:    output/cores_4/14_65723.png
    Deleted:    output/cores_4/14_66422.png
    Deleted:    output/cores_4/14_8155.png
    Deleted:    output/cores_4/15_04414.png
    Deleted:    output/cores_4/15_10312.png
    Deleted:    output/cores_4/15_24019.png
    Deleted:    output/cores_4/15_28478.png
    Deleted:    output/cores_4/16_02092.png
    Deleted:    output/cores_4/16_20351.png

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/cores_3.Rmd) and HTML (docs/cores_3.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 1a7cca3 Jovan Tanevski 2021-11-12 wflow_publish("analysis/cores_3.Rmd")
Rmd a52096d Jovan Tanevski 2021-11-12 overlay tifs with cluster info, manual silhouette calculation
Rmd baf95ea Jovan Tanevski 2021-11-12 keep all residuals, fix object access
Rmd 6ff2531 Jovan Tanevski 2021-11-11 small fix
Rmd e98088d Jovan Tanevski 2021-11-11 core analysis of all hepatocytes for one core per patient
html 515f7e6 Jovan Tanevski 2021-10-28 Build site.
html 434cb0d Jovan Tanevski 2021-10-27 Build site.
html a915f46 Jovan Tanevski 2021-10-27 Build site.
Rmd a56dc0c Jovan Tanevski 2021-10-27 remove beta-cat, add cores 3 and 4 clusters

Setup

library(skimr)
library(uwot)
library(limma)
library(NMF)
library(cowplot)
library(pheatmap)
library(RColorBrewer)
library(distances)
library(furrr)
library(raster)
library(RStoolbox)
library(tidyverse)
data <- read_csv("data/tumor_hepatocytes.csv", col_types = cols())
Warning: One or more parsing issues, see `problems()` for details
tumor.hc <- data %>%
  select(
    `Cytoplasm AGS (Opal 690) Mean (Normalized Counts, Total Weighting)`,
    `Cytoplasm BerEP4 (Opal 650) Mean (Normalized Counts, Total Weighting)`,
    `Cytoplasm CRP (Opal 540) Mean (Normalized Counts, Total Weighting)`,
    `Nucleus p-S6 (Opal 570) Mean (Normalized Counts, Total Weighting)`,
#    `Nucleus beta-cat. (Opal 520) Mean (Normalized Counts, Total Weighting)`
  ) %>%
  `colnames<-`(str_split(colnames(.), " ") %>% map_chr(~ .x[2]) %>% make.names())

skim(tumor.hc)
Data summary
Name tumor.hc
Number of rows 223846
Number of columns 4
_______________________
Column type frequency:
numeric 4
________________________
Group variables None

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
AGS 0 1 0.27 0.41 0 0.07 0.12 0.25 5.23 ▇▁▁▁▁
BerEP4 0 1 1.09 2.19 0 0.21 0.32 0.58 24.08 ▇▁▁▁▁
CRP 0 1 2.51 3.08 0 0.55 1.00 3.50 35.80 ▇▁▁▁▁
p.S6 0 1 1.31 1.25 0 0.58 0.94 1.61 35.24 ▇▁▁▁▁

Detect outliers based on Tukey’s interquartile approach and winsorize. Follow by quantile normalization and ranking to get rid of the effect of abundance

quartiles <- apply(tumor.hc, 2, \(x) quantile(x, c(.25, .75)))
lower <- quartiles[1, ] - 1.5 * (quartiles[2, ] - quartiles[1, ])
upper <- quartiles[2, ] + 1.5 * (quartiles[2, ] - quartiles[1, ])


tumor.hc.winsorized <- tumor.hc %>% imap_dfc(\(x, y){
  x[x < lower[y]] <- x[which.min(abs(x - lower[y]))]
  x[x > upper[y]] <- x[which.min(abs(x - upper[y]))]
  x
})

skim(tumor.hc.winsorized)
Data summary
Name tumor.hc.winsorized
Number of rows 223846
Number of columns 4
_______________________
Column type frequency:
numeric 4
________________________
Group variables None

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
AGS 0 1 0.19 0.16 0 0.07 0.12 0.25 0.52 ▇▅▂▁▃
BerEP4 0 1 0.46 0.35 0 0.21 0.32 0.58 1.15 ▆▇▂▁▃
CRP 0 1 2.31 2.50 0 0.55 1.00 3.50 7.93 ▇▂▁▁▂
p.S6 0 1 1.21 0.83 0 0.58 0.94 1.61 3.16 ▆▇▃▂▂
tumor.hc.norm <- normalizeQuantiles(data.frame(tumor.hc.winsorized))

skim(tumor.hc.norm)
Data summary
Name tumor.hc.norm
Number of rows 223846
Number of columns 4
_______________________
Column type frequency:
numeric 4
________________________
Group variables None

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
AGS 0 1 1.06 0.99 0 0.35 0.6 1.49 3.19 ▇▃▁▁▂
BerEP4 0 1 1.07 1.00 0 0.35 0.6 1.49 3.15 ▇▃▂▁▂
CRP 0 1 1.04 0.96 0 0.35 0.6 1.49 3.19 ▇▃▁▁▂
p.S6 0 1 1.04 0.96 0 0.35 0.6 1.49 3.19 ▇▃▁▁▂
tumor.hc.rank <- mutate_all(tumor.hc.winsorized, ~ rank(., ties.method = "min"))

Pilot run. Subsample one core per patient from the original data.

set.seed(42)
selected.cores <- data %>% select(`Sample Name`) %>% 
  mutate(sample = str_extract(`Sample Name`, "[0-9]{2}_[0-9]+")) %>% 
  group_by(`Sample Name`) %>% distinct() %>% ungroup() %>% 
  group_by(sample) %>% slice_sample() %>% pull(`Sample Name`)

subsamp <- which(data %>% pull(`Sample Name`) %in% selected.cores)

Dimensionality reduction

cache <- "output/tumor.hc.umap.rds"
if (file.exists(cache)) {
  tumor.hc.umap <- read_rds(cache)
} else {
  tumor.hc.umap <- umap(tumor.hc.norm, n_neighbors = 100, 
                        min_dist = 0.2, n_threads = 7)
  write_rds(tumor.hc.umap, cache, "gz")
}

tumor.hc.umap.sample <-
  tumor.hc.umap %>%
  `colnames<-`(c("U1", "U2")) %>%
  as_tibble()

Check if sample is representative in UMAP space

all <- ggplot(tumor.hc.umap.sample, aes(x = U1, y = U2)) +
  geom_point(size = 0.5) +
  theme_classic()

sampled <- ggplot(tumor.hc.umap.sample %>% slice(subsamp), aes(x = U1, y = U2)) +
  geom_point(color = "darkgreen", size = 0.5) +
  theme_classic()

unsampled <- ggplot(tumor.hc.umap.sample %>% slice(-subsamp), aes(x = U1, y = U2)) +
  geom_point(color = "darkred", size = 0.5) +
  theme_classic()

plot_grid(all, sampled, unsampled)

Version Author Date
a915f46 Jovan Tanevski 2021-10-27

Consensus NMF

We use an efficient implementation of alternating non negative least-squares with regularized to favor sparse coefficient matrices snmf/r. In this way we aim for cleaner clustering.

cache <- "output/tumor.hc.nmf.all.3.rds"

if (file.exists(cache)) {
  tumor.hc.nmf <- read_rds(cache)
} else {
  tumor.hc.nmf <- nmf(as.matrix(t(tumor.hc.rank[subsamp, ])),
    rank = 3, method = "snmf/r",
    nrun = 10, seed = 42, verbose = TRUE,
    .options = "vkp10-m"
  )
  write_rds(tumor.hc.nmf, cache, "gz")
}

Extract basis of NMF (signature of cluster)

basismap(tumor.hc.nmf)

Version Author Date
a915f46 Jovan Tanevski 2021-10-27

Assign clusters

nmf.clusters <- apply(fit(tumor.hc.nmf)@H, 2, which.max)

Plot in 2D

tumor.hc.umap.clus <-
  tumor.hc.umap.sample %>%
  slice(subsamp) %>%
  mutate(Cluster = as.factor(nmf.clusters))

ggplot(tumor.hc.umap.clus, aes(x = U1, y = U2, color = Cluster)) +
  geom_point(size = 0.5) +
  theme_classic()

Expression profiles per cluster

tumor.hc.clustered.nmf <- tumor.hc.norm[subsamp, ] %>%
  mutate(Cluster = as.factor(nmf.clusters)) %>%
  pivot_longer(names_to = "Marker", values_to = "Norm.value", -Cluster)

profiles <- seq_len(max(nmf.clusters)) %>% map(~
ggplot(
  tumor.hc.clustered.nmf %>% filter(Cluster == .x),
  aes(x = Marker, y = Norm.value, color = Marker)
) +
  stat_summary(fun.data = mean_sdl, show.legend = FALSE) +
  scale_color_brewer(palette = "Set2") +
  ylim(-1, 3) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)))

plot_grid(plotlist = profiles, labels = paste("Cluster", seq_len(max(nmf.clusters))))
Warning: Removed 14390 rows containing non-finite values (stat_summary).
Warning: Removed 16165 rows containing non-finite values (stat_summary).
Warning: Removed 24968 rows containing non-finite values (stat_summary).
Warning: Removed 1 rows containing missing values (geom_segment).

Version Author Date
a915f46 Jovan Tanevski 2021-10-27

Marker abundance plots

tumor.hc.umap.markers <- tumor.hc.norm %>%
  bind_cols(tumor.hc.umap.sample) %>%
  slice(subsamp)

low <- RColorBrewer::brewer.pal(8, "Set2")[8]
highs <- RColorBrewer::brewer.pal(8, "Set2")[seq_len(ncol(tumor.hc.norm))]

tumor.hc.umap.markers.plots <- colnames(tumor.hc.norm) %>%
  map2(highs, \(marker, color){
    ggplot(tumor.hc.umap.markers, aes_string(x = "U1", y = "U2", color = marker)) +
      geom_point(size = 0.5) +
      scale_color_gradient(low = low, high = color) +
      theme_classic()
  })

plot_grid(plotlist = tumor.hc.umap.markers.plots)

Version Author Date
a915f46 Jovan Tanevski 2021-10-27

Core plots

tumor.hc.umap.cores <- data %>%
  select(`Sample Name`) %>%
  bind_cols(tumor.hc.umap.sample) %>%
  slice(subsamp) %>%
  mutate(
    c = nmf.clusters,
    sample = str_extract(`Sample Name`, "[0-9]+_[0-9]+")
  )

tumor.hc.umap.cores %>%
  group_by(sample) %>%
  summarize(
    Fraction = table(c) / n(),
    Cluster = names(Fraction),
    .groups = "drop"
  ) %>%
  mutate(Fraction = as.numeric(Fraction)) %>%
  pivot_wider(names_from = "Cluster", values_from = "Fraction") %>%
  column_to_rownames("sample") %>%
  mutate(across(everything(), ~ replace_na(., 0))) %>%
  as.matrix() %>%
  pheatmap(
    scale = "none",
    color = colorRampPalette(brewer.pal(n = 7, name = "YlOrBr"))(100),
    fontsize = 6
  )

Version Author Date
a915f46 Jovan Tanevski 2021-10-27
tumor.hc.umap.cores %>%
  pull(sample) %>%
  unique() %>%
  walk(\(s){
    output.fig <- paste0("output/cores_3/", s, ".png")
    if (!file.exists(output.fig)) {
      png(output.fig, width  = 800, height = 800)
      (ggplot(
        tumor.hc.umap.cores %>%
          mutate(c = ifelse(sample == s, c, NA), Cluster = as.factor(c)) %>%
          arrange(!is.na(Cluster), Cluster),
        aes(x = U1, y = U2, color = Cluster)
      ) +
        geom_point(size = 0.5) +
        scale_color_discrete(na.value = "gray80") +
        theme_classic()) %>%
        print()
      dev.off()
    }
  })

Figures with UMAPs for each core can be found in output.

Overlay cluster information on available tiffs

available.images <- list.files("data/core images/", full.names = TRUE)

spatial <- data %>% 
  select(`Sample Name`, `Cell X Position`, `Cell Y Position`) %>% 
  `colnames<-`(c("sample", "X", "Y")) %>%
  slice(subsamp) %>% 
  mutate(Cluster = as.factor(nmf.clusters))

available.images %>% walk(\(img){
  id <- str_extract(img, "[0-9]{2}_[0-9]+(_[^_\\.]*){4}")
  name <- str_extract(img, "[0-9]{2}_[0-9]+(_[^_\\.]*)*.tif")
  s <- paste0(id,".im3")
  if(s %in% spatial$sample){
    rb <- brick(img)
    
    
    names(rb) <- c("r", "g", "b")
    
    pdf(paste0("output/cores_3/", name, ".pdf"))
    #the t should be flipped along the y direction to match coordinates in spatial
    (ggRGB(flip(rb, "y")) + 
      geom_point(data = spatial %>% filter(sample == s), aes(x = X, y = Y, color = Cluster)) +
      theme_map()) %>%
      print()
    dev.off()
  }
  
})

Differential expression analysis (silhouette)

Calculate the similarity of samples using the expression and the silhouette scores based on the assigned clusters.

cache <- "output/silhouette.nmf.rds"

if (file.exists(cache)) {
  silhouette.nmf <- read_rds(cache)
} else {
  # manual calculation of silhouette scores with lazily evaluated distance matrix
  subsamp.dists <- distances(tumor.hc.norm[subsamp, ])
  
  plan(multisession, workers = 5)
  
  silhouette.nmf <- nmf.clusters %>% future_imap_dbl(\(c, i){
    dists <- tibble(d = subsamp.dists[i,][-i], cluster = nmf.clusters[-i]) %>% 
      group_by(cluster) %>% 
      summarize(m = mean(d)) 
    
    a <- dists %>% filter(cluster == c) %>% pluck("m", 1)
    b <- dists %>% filter(cluster != c) %>% pull(m) %>% min()
    
    (b - a)/max(a, b)
  }, .options = furrr::furrr_options(packages = "distances"), .progress = TRUE)
  
  write_rds(silhouette.nmf, cache, "gz")
}

tibble(c = nmf.clusters, s = silhouette.nmf) %>% 
  group_by(c) %>% 
  summarize(m = mean(s))
c m
1 0.3791663
2 0.3017454
3 0.1130977
print(paste0("Average silhouette score: ", mean(silhouette.nmf)))
[1] "Average silhouette score: 0.250828061783453"

Select only the samples with positive silhouette scores as “core samples”

core.samples <- which(silhouette.nmf > 0)
tumor.hc.core.samples <- tumor.hc.norm[subsamp, ] %>%
  add_column(Cluster = nmf.clusters) %>%
  slice(core.samples)

Calculate difference in means (mean(cluster) - mean(other)), one-vs-all t-test per marker and correct for FDR. Filter q <= 0.05. Plot the differences.

de.table <- unique(tumor.hc.core.samples$Cluster) %>%
  map_dfr(\(c){
    tumor.hc.core.samples %>%
      summarize(across(-Cluster, ~ t.test(.x ~ (Cluster == c))$p.value)) %>%
      pivot_longer(names_to = "Marker", values_to = "p", everything()) %>%
      mutate(Cluster = c, Difference = tumor.hc.core.samples %>%
        group_by(Cluster == c) %>%
        select(-Cluster) %>%
        group_split(.keep = FALSE) %>% map(colMeans) %>% reduce(`-`))
  }) %>%
  mutate(q = p.adjust(p, method = "fdr"), Difference = -Difference)

de.table %>%
  filter(q <= 0.05) %>%
  arrange(q)
Marker p Cluster Difference q
AGS 0 1 -1.1509970 0
BerEP4 0 1 1.3643187 0
CRP 0 1 -0.8705340 0
p.S6 0 1 -0.6053700 0
AGS 0 3 -0.4408815 0
BerEP4 0 3 -0.7472194 0
CRP 0 3 1.6290324 0
p.S6 0 3 1.4251024 0
AGS 0 2 1.6605926 0
BerEP4 0 2 -0.7006696 0
CRP 0 2 -0.7032498 0
p.S6 0 2 -0.7808243 0
de.table %>%
  pivot_wider(names_from = "Cluster", values_from = "Difference", -c(p, q)) %>%
  column_to_rownames("Marker") %>%
  as.matrix() %>%
  pheatmap(scale = "none")

Version Author Date
a915f46 Jovan Tanevski 2021-10-27

sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 10.16

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] forcats_0.5.1       stringr_1.4.0       dplyr_1.0.7        
 [4] purrr_0.3.4         readr_2.1.0         tidyr_1.1.4        
 [7] tibble_3.1.6        ggplot2_3.3.5       tidyverse_1.3.1    
[10] RStoolbox_0.2.6     raster_3.5-2        sp_1.4-5           
[13] furrr_0.2.3         future_1.23.0       distances_0.1.8    
[16] RColorBrewer_1.1-2  pheatmap_1.0.12     cowplot_1.1.1      
[19] NMF_0.23.0          synchronicity_1.3.5 bigmemory_4.5.36   
[22] Biobase_2.54.0      BiocGenerics_0.40.0 cluster_2.1.2      
[25] rngtools_1.5.2      pkgmaker_0.32.2     registry_0.5-1     
[28] limma_3.50.0        uwot_0.1.10         Matrix_1.3-4       
[31] skimr_2.1.3         workflowr_1.6.2    

loaded via a namespace (and not attached):
  [1] readxl_1.3.1         uuid_1.0-3           backports_1.3.0     
  [4] Hmisc_4.6-0          plyr_1.8.6           repr_1.1.3          
  [7] splines_4.1.1        listenv_0.8.0        gridBase_0.4-7      
 [10] digest_0.6.28        foreach_1.5.1        htmltools_0.5.2     
 [13] fansi_0.5.0          checkmate_2.0.0      magrittr_2.0.1      
 [16] doParallel_1.0.16    tzdb_0.2.0           recipes_0.1.17      
 [19] globals_0.14.0       modelr_0.1.8         gower_0.2.2         
 [22] vroom_1.5.6          jpeg_0.1-9           colorspace_2.0-2    
 [25] rvest_1.0.2          haven_2.4.3          xfun_0.28           
 [28] rgdal_1.5-27         crayon_1.4.2         jsonlite_1.7.2      
 [31] bigmemory.sri_0.1.3  survival_3.2-13      iterators_1.0.13    
 [34] glue_1.5.0           gtable_0.3.0         ipred_0.9-12        
 [37] future.apply_1.8.1   scales_1.1.1         DBI_1.1.1           
 [40] Rcpp_1.0.7           htmlTable_2.3.0      xtable_1.8-4        
 [43] foreign_0.8-81       bit_4.0.4            Formula_1.2-4       
 [46] stats4_4.1.1         lava_1.6.10          prodlim_2019.11.13  
 [49] htmlwidgets_1.5.4    httr_1.4.2           geosphere_1.5-14    
 [52] ellipsis_0.3.2       farver_2.1.0         pkgconfig_2.0.3     
 [55] XML_3.99-0.8         nnet_7.3-16          sass_0.4.0          
 [58] dbplyr_2.1.1         utf8_1.2.2           caret_6.0-90        
 [61] labeling_0.4.2       tidyselect_1.1.1     rlang_0.4.12        
 [64] reshape2_1.4.4       later_1.3.0          munsell_0.5.0       
 [67] cellranger_1.1.0     tools_4.1.1          cli_3.1.0           
 [70] generics_0.1.1       broom_0.7.10         evaluate_0.14       
 [73] fastmap_1.1.0        yaml_2.2.1           bit64_4.0.5         
 [76] ModelMetrics_1.2.2.2 knitr_1.36           fs_1.5.0            
 [79] nlme_3.1-153         whisker_0.4          xml2_1.3.2          
 [82] compiler_4.1.1       rstudioapi_0.13      png_0.1-7           
 [85] reprex_2.0.1         bslib_0.3.1          stringi_1.7.5       
 [88] highr_0.9            rgeos_0.5-8          lattice_0.20-45     
 [91] vctrs_0.3.8          pillar_1.6.4         lifecycle_1.0.1     
 [94] jquerylib_0.1.4      data.table_1.14.2    httpuv_1.6.3        
 [97] latticeExtra_0.6-29  R6_2.5.1             promises_1.2.0.1    
[100] gridExtra_2.3        parallelly_1.28.1    codetools_0.2-18    
[103] MASS_7.3-54          assertthat_0.2.1     rprojroot_2.0.2     
[106] withr_2.4.2          parallel_4.1.1       hms_1.1.1           
[109] terra_1.4-11         grid_4.1.1           rpart_4.1-15        
[112] timeDate_3043.102    class_7.3-19         rmarkdown_2.11      
[115] git2r_0.28.0         pROC_1.18.0          lubridate_1.8.0     
[118] base64enc_0.1-3