Skip to content

Instantly share code, notes, and snippets.

@GabrielHoffman
Last active March 21, 2024 14:55
Show Gist options
  • Save GabrielHoffman/d4345ba3bb9db111f4f4e80e4c4306a4 to your computer and use it in GitHub Desktop.
Save GabrielHoffman/d4345ba3bb9db111f4f4e80e4c4306a4 to your computer and use it in GitHub Desktop.
Plot within and between correlations for a continuous property
# Plot within and between correlations for a continuous property
plot_within_btw = function( data, info){
library(tidyverse)
library(corrr)
if( ! all(c("ID", "Property") %in% colnames(info)) ){
stop("info must have column names ID and Property")
}
if( ! identical(info$ID, colnames(data)) ){
stop("info$ID and colnames(data) must be identical")
}
# compute correlations
df_cor = correlate( data, quiet=TRUE ) %>%
stretch() %>%
filter(!is.na(r))
# merge with info
df = df_cor %>%
inner_join(info %>%
rename(x = ID, Property.x = Property),
by='x') %>%
inner_join(info %>%
rename(y = ID, Property.y = Property),
by='y')
# Plot
fig = df %>%
mutate(Status = Property.x & Property.y) %>%
ggplot(aes(Status, r, fill=Status)) +
geom_violin() +
geom_boxplot(width = 0.07, fill = "grey", outlier.color = "black") +
theme_bw(15) +
scale_fill_manual(values = c("grey90", "steelblue1")) +
theme(legend.position = "none") +
xlab("Property") +
ylab("Correlation")
list(fig = fig, df = df)
}
library(dreamlet)
library(tidyverse)
file = "/sc/arion/projects/psychAD/NPS-AD/freeze2_rc/processAssays/final/AGING_2024-02-01_22_23_processAssays_SubID_class.RDS"
res.proc2 = readRDS(file)
# form = ~ Source + Sex + scale(PMI) + log(n_genes) + percent_mito + mito_genes + mito_ribo + ribo_genes
form = ~ Sex
fit = dreamlet(res.proc2, form, assays="EN")
data = residuals(fit)[['EN']]
info = colData(res.proc2)
info$SubID = rownames(info)
info = info %>%
as_tibble %>%
select(SubID, Age) %>%
mutate(Property = Age < 5) %>% # define within/btw
rename(ID = SubID) %>%
filter(ID %in% colnames(data))
res = plot_within_btw( data, info)
res$fig
> res$df
# A tibble: 79,242 × 7
x y r Age.x Property.x Age.y Property.y
<chr> <chr> <dbl> <dbl> <lgl> <dbl> <lgl>
1 H822 H823 0.0844 26 FALSE 50 FALSE
2 H822 H831 0.223 26 FALSE 85 FALSE
3 H822 H836 0.0989 26 FALSE 20 FALSE
4 H822 H845 -0.151 26 FALSE 24 FALSE
5 H822 H846 -0.193 26 FALSE 58 FALSE
6 H822 H847 -0.0703 26 FALSE 0.4 TRUE
7 H822 H848 -0.0925 26 FALSE 22 FALSE
8 H822 H863 -0.00587 26 FALSE 43 FALSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment