mashr
to adjust the TWAS results
Last updated: 2021-10-01
Checks: 7 0
Knit directory: fitnessGWAS/
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(20180914)
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 01226ab. 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: .Rapp.history
Ignored: .Rhistory
Ignored: .Rproj.user/
Ignored: .httr-oauth
Ignored: .pversion
Ignored: analysis/.DS_Store
Ignored: analysis/correlations_SNP_effects_cache/
Ignored: code/.DS_Store
Ignored: code/Drosophila_GWAS.Rmd
Ignored: data/.DS_Store
Ignored: data/derived/
Ignored: data/input/.DS_Store
Ignored: data/input/.pversion
Ignored: data/input/dgrp.fb557.annot.txt
Ignored: data/input/dgrp2.bed
Ignored: data/input/dgrp2.bim
Ignored: data/input/dgrp2.fam
Ignored: data/input/huang_transcriptome/
Ignored: figures/.DS_Store
Ignored: figures/fig1_inkscape.svg
Ignored: figures/figure1a.pdf
Ignored: figures/figure1b.pdf
Untracked files:
Untracked: big_model.rds
Untracked: code/quant_gen_1.R
Untracked: data/input/genomic_relatedness_matrix.rds
Untracked: old_analyses/
Unstaged changes:
Modified: .gitignore
Modified: figures/GWAS_stats_figure.pdf
Modified: figures/SNP_effect_ED.pdf
Modified: figures/TWAS_stats_figure.pdf
Modified: figures/antagonism_ratios.pdf
Modified: figures/boyle_plot.pdf
Modified: figures/composite_mixture_figure.pdf
Modified: figures/eff_size_histos.pdf
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/TWAS.Rmd
) and HTML (docs/TWAS.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 | 01226ab | lukeholman | 2021-10-01 | wflow_publish("analysis/*") |
html | 8d14298 | lukeholman | 2021-09-26 | Build site. |
Rmd | af15dd6 | lukeholman | 2021-09-26 | Commit Sept 2021 |
html | 3124aad | lukeholman | 2021-03-05 | Build site. |
Rmd | 6704dc8 | lukeholman | 2021-03-05 | wflow_publish(“analysis/TWAS.Rmd”) |
html | c18c925 | lukeholman | 2021-03-05 | Build site. |
Rmd | 382f3a3 | lukeholman | 2021-03-05 | wflow_publish(“analysis/TWAS.Rmd”) |
Rmd | 3855d33 | lukeholman | 2021-03-04 | big fist commit 2021 |
html | 3855d33 | lukeholman | 2021-03-04 | big fist commit 2021 |
Rmd | 8d54ea5 | Luke Holman | 2018-12-23 | Initial commit |
library(edgeR)
library(tidyverse)
library(glue)
library(future)
library(future.apply)
library(parallel)
library(kableExtra)
library(DT)
library(ashr)
library(mashr)
options(stringsAsFactors = FALSE)
# Connect to the database of annotations
db <- DBI::dbConnect(RSQLite::SQLite(), "data/derived/annotations.sqlite3")
# Helper to run shell commands
run_command <- function(shell_command, wd = getwd(), path = ""){
cat(system(glue("cd ", wd, path, "\n",shell_command), intern = TRUE), sep = '\n')
}
kable_table <- function(df) { # cool tables
kable(df, "html") %>%
kable_styling() %>%
scroll_box(height = "300px")
}
my_data_table <- function(df){ # Make html tables:
datatable(
df, rownames=FALSE,
autoHideNavigation = TRUE,
extensions = c("Scroller", "Buttons"),
options = list(
dom = 'Bfrtip',
deferRender=TRUE,
scrollX=TRUE, scrollY=400,
scrollCollapse=TRUE,
buttons =
list('pageLength', 'colvis', 'csv', list(
extend = 'pdf',
pageSize = 'A4',
orientation = 'landscape',
filename = 'TWAS_enrichment')),
columnDefs = list(list(targets = c(8,10), visible = FALSE)),
pageLength = 50
)
)
}
# Helper to load Huang et al.'s data
load_expression_data <- function(sex, both_sex_chromosomes = TRUE){
# Note: Huang et al's data contains weird stuff like supposedly Y-linked genes that have
# higher/equal expression in *females* in all lines, presumably microarray issues/errors.
# To be conservative, we restrict our analyses to genes that are known to be on a
# chromosomes that is present in both sexes
if(both_sex_chromosomes){
genes_allowed <- tbl(db, "genes") %>%
filter(chromosome %in% c("2L", "2R", "3L", "3R", "4", "X")) %>%
pull(FBID)
} else {
genes_allowed <- tbl(db, "genes") %>%
pull(FBID)
}
if(sex != "both"){
expression <- glue("data/input/huang_transcriptome/dgrp.array.exp.{sex}.txt") %>%
read_delim(delim = " ") %>%
filter(gene %in% genes_allowed)
sample_names <- names(expression)[names(expression) != "gene"] %>% str_remove(":[12]")
gene_names <- expression$gene
expression <- expression %>% select(-gene) %>% as.matrix() %>% t()
rownames(expression) <- sample_names # rows are samples, columns are genes
colnames(expression) <- gene_names
return(expression %>% as.data.frame() %>%
tibble::rownames_to_column("line") %>%
as_tibble() %>%
mutate(line = str_remove_all(line, "[.]1")))
}
females <- read_delim("data/input/huang_transcriptome/dgrp.array.exp.female.txt", delim = " ") %>%
filter(gene %in% genes_allowed)
names(females)[-1] <- paste("F_", names(females)[-1],sep="") #%>% str_remove(":[12]")
females <- females %>%
left_join(read_delim("data/input/huang_transcriptome/dgrp.array.exp.male.txt", delim = " "), by = "gene")
sample_names <- names(females)[names(females) != "gene"] %>% str_remove(":[12]")
gene_names <- females$gene
sex <- ifelse(str_detect(sample_names, "F_"), "female", "male")
line <- str_remove_all(sample_names, "F_")
females <- females %>% select(-gene) %>% t()
colnames(females) <- gene_names
list(
sampleIDs = tibble(sex, line),
expression = females
)
}
# Table S5: heritability of the expression level of each transcript (as measured in males, or females)
huang_heritability <- read_csv("data/input/huang_2015_tableS5_transcript_heritability.csv")
# Load the predicted line means from present study, as calculated in get_predicted_line_means.Rmd
predicted_line_means <- read_csv("data/derived/predicted_line_means.csv")
The following takes the 368 female samples and the 369 male samples, and finds the log fold difference in expression between sexes, and the average expression across both sexes, using the edgeR package.
expression_data_both_sexes <- load_expression_data("both") %>% unname()
voom_gene_data <- calcNormFactors(DGEList(t(expression_data_both_sexes[[2]])))
mm <- model.matrix(~ sex, data = expression_data_both_sexes[[1]])
colnames(mm) <- gsub("sex", "", colnames(mm))
sex_bias_in_expression <- voom_gene_data %>%
voom(mm, plot = FALSE) %>%
lmFit(mm) %>%
eBayes() %>%
topTable(n = Inf) %>%
rownames_to_column("FBID") %>%
select(FBID, logFC, AveExpr) %>%
rename(male_bias_in_expression = logFC) %>%
as_tibble() %>% arrange(male_bias_in_expression)
write_csv(sex_bias_in_expression, "data/derived/gene_expression_by_sex.csv")
rm(expression_data_both_sexes)
Huang et al.’s microarray data was downloaded from the DGRP website.
Rows: 18140 Columns: 370
── Column specification ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Delimiter: " "
chr (1): gene
dbl (369): line_21:1, line_21:2, line_26:1, line_26:2, line_28:1, line_28:2,...
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Here, we perform a large number of simple linear regressions, and obtain the slope (beta or β) and its standard error from a regression of transcript i on fitness trait j. The number of regression run was 5.714810^{4}, i.e. 4 fitness traits × 14287 transcripts. This approach is often called ‘TWAS’.
transcript_selection_analysis <- function(expression_data, phenotypes){
if("block" %in% names(phenotypes)) phenotypes <- phenotypes %>% select(-block)
expression_data <- expression_data %>%
filter(line %in% phenotypes$line)
# Find line mean expression for each gene (average across the c. 2 replicate samples per line)
chunk_cols <- split(2:ncol(expression_data), ceiling(seq_along(2:ncol(expression_data)) / 500))
mean_expression_data <- mclapply(1:2, function(i){
expression_data[, c(1, chunk_cols[[i]])] %>%
group_by(line) %>%
summarise_all(mean) %>%
ungroup()
}) %>% bind_rows()
# Scale each transcript's expression level so that mean is 0, and the variance is 1, across all the lines measured by Huang et al.
for(i in 2:ncol(mean_expression_data)) mean_expression_data[,i] <- as.numeric(scale(mean_expression_data[,i]))
# Join the microarray data with the phenotypes (i.e. our fitness data), and keep only the lines where we have both sets of measurements
expression_data <- phenotypes %>% left_join(expression_data, by = "line")
expression_data <- expression_data[complete.cases(expression_data), ] %>% select(-line)
print("Data ready for analysis. Starting TWAS...")
# Create chunks of transcript names, which will be used to facilitate parallel processing
transcripts <- names(expression_data)[-c(1:4)]
transcripts <- split(transcripts, ceiling(seq_along(transcripts) / 100))
# Define a function to run 4 linear models, and get the beta and SE for regressions of expression level on the 4 fitness traits
do_one_transcript <- function(transcript){
expression_level <- expression_data %>% pull(!!transcript)
FE <- summary(lm(female.fitness.early ~ expression_level, data = expression_data))$coefficients
FL <- summary(lm(female.fitness.late ~ expression_level, data = expression_data))$coefficients
ME <- summary(lm(male.fitness.early ~ expression_level, data = expression_data))$coefficients
ML <- summary(lm(male.fitness.late ~ expression_level, data = expression_data))$coefficients
c(FE[2,1], FL[2,1], ME[2,1], ML[2,1], # effect size
FE[2,2], FL[2,2], ME[2,2], ML[2,2], # SE
FE[2,4], FL[2,4], ME[2,4], ML[2,4]) # p-value
}
# Runs do_one_transcript() on all the transcripts listed in the vector 'transcripts'
do_chunk_of_transcripts <- function(transcripts){
output <- data.frame(transcripts, lapply(transcripts, do_one_transcript) %>% do.call("rbind", .))
names(output) <- c("gene", "beta_FE", "beta_FL", "beta_ME", "beta_ML",
"SE_FE", "SE_FL", "SE_ME", "SE_ML",
"pval_FE", "pval_FL", "pval_ME", "pval_ML")
output
}
# Run it all, in parallel
transcripts %>%
mclapply(do_chunk_of_transcripts) %>%
do.call("rbind", .) %>% as_tibble() %>% mutate(gene = as.character(gene))
}
if(!file.exists("data/derived/TWAS/TWAS_result_males.csv")){
TWAS_result_females <- load_expression_data("female") %>% transcript_selection_analysis(predicted_line_means)
TWAS_result_females %>% write_csv("data/derived/TWAS/TWAS_result_females.csv")
TWAS_result_males <- load_expression_data("male") %>% transcript_selection_analysis(predicted_line_means)
TWAS_result_males %>% write_csv("data/derived/TWAS/TWAS_result_males.csv")
} else {
TWAS_result_females <- read_csv("data/derived/TWAS/TWAS_result_females.csv")
TWAS_result_males <- read_csv("data/derived/TWAS/TWAS_result_males.csv")
}
mashr
to adjust the TWAS resultsThis section re-uses the custom function run_mashr()
. See the earlier script (where mashr
was applied to the GWAS data) for the function definition. Essentially, run_mashr()
helps us to run mashr
twice, once using canonical and once using data-driven covariance matrices.
Similar to for the GWAS data, we use the canonical analysis to estimate the frequency of different types of transcripts (rather than loci), which we do for the entire transcriptome, as well as separately for each of the individual chromosome arms. We use the data-driven (“ED”) approach to derive the most accurate adjusted beta terms (i.e. the slope of the regression of transcript abundance on the phenotype of interest).
if(!file.exists("data/derived/TWAS/TWAS_ED.rds")){
input_data <- data.frame(TWAS_result_females[,1:3],
TWAS_result_males[,4:5],
TWAS_result_females[,6:7],
TWAS_result_males[,8:9])
with_chrs <- input_data %>%
left_join(tbl(db, "genes") %>%
select(FBID, chromosome) %>%
collect(), by = c("gene" = "FBID"))
TWAS_canonical <- input_data %>%
run_mashr(mashr_mode = "canonical")
TWAS_canonical_2L <- with_chrs %>%
filter(chromosome == "2L") %>% select(-chromosome) %>%
run_mashr(mashr_mode = "canonical")
TWAS_canonical_2R <- with_chrs %>%
filter(chromosome == "2R") %>% select(-chromosome) %>%
run_mashr(mashr_mode = "canonical")
TWAS_canonical_3L <- with_chrs %>%
filter(chromosome == "3L") %>% select(-chromosome) %>%
run_mashr(mashr_mode = "canonical")
TWAS_canonical_3R <- with_chrs %>%
filter(chromosome == "3R") %>% select(-chromosome) %>%
run_mashr(mashr_mode = "canonical")
TWAS_canonical_X <- with_chrs %>%
filter(chromosome == "X") %>% select(-chromosome) %>%
run_mashr(mashr_mode = "canonical")
saveRDS(TWAS_canonical, "data/derived/TWAS/TWAS_canonical.rds")
saveRDS(TWAS_canonical_2L, "data/derived/TWAS/TWAS_canonical_2L.rds")
saveRDS(TWAS_canonical_2R, "data/derived/TWAS/TWAS_canonical_2R.rds")
saveRDS(TWAS_canonical_3L, "data/derived/TWAS/TWAS_canonical_3L.rds")
saveRDS(TWAS_canonical_3R, "data/derived/TWAS/TWAS_canonical_3R.rds")
saveRDS(TWAS_canonical_X, "data/derived/TWAS/TWAS_canonical_X.rds")
TWAS_ED <- input_data %>%
run_mashr(mashr_mode = "ED",
ED_p_cutoff = 0.4)
saveRDS(TWAS_ED, "data/derived/TWAS/TWAS_ED.rds")
} else {
TWAS_canonical <- readRDS("data/derived/TWAS/TWAS_canonical.rds")
TWAS_ED <- readRDS("data/derived/TWAS/TWAS_ED.rds")
}
TWAS_mashr_results <-
data.frame(
FBID = colnames(load_expression_data("female"))[-1],
as.data.frame(get_pm(TWAS_canonical)) %>% rename_all(~str_c("canonical_", .)),
as.data.frame(get_lfsr(TWAS_canonical)) %>%
rename_all(~str_replace_all(., "beta", "LFSR")) %>% rename_all(~str_c("canonical_", .))) %>%
as_tibble() %>%
bind_cols(
data.frame(
as.data.frame(get_pm(TWAS_ED)) %>% rename_all(~str_c("ED_", .)),
as.data.frame(get_lfsr(TWAS_ED)) %>%
rename_all(~str_replace_all(., "beta", "LFSR")) %>% rename_all(~str_c("ED_", .))) %>%
as_tibble())
This uses the canonical analysis’ classifications. Each transcript gets a posterior probability that it belongs to the i’th mixture component – only the mixture components that are not very rare are included. These are: equal_effects
(i.e. the transcript is predicted to affect all 4 phenotypes equally), female-specific and male-specific (i.e. an effect on females/males only, which is concordant across age categories), sexually antagonistic (again, regardless of age), and null (note: the prior for mashr
was that null transcripts are 10× more common than any other type).
# Get the mixture weights, as advised by mashr authors here: https://github.com/stephenslab/mashr/issues/68
posterior_weights_cov <- TWAS_canonical$posterior_weights
colnames(posterior_weights_cov) <- sapply(
str_split(colnames(posterior_weights_cov), '\\.'),
function(x) {
if(length(x) == 1) return(x)
else if(length(x) == 2) return(x[1])
else if(length(x) == 3) return(paste(x[1], x[2], sep = "."))
})
posterior_weights_cov <- t(rowsum(t(posterior_weights_cov),
colnames(posterior_weights_cov)))
# Make a neat dataframe
TWAS_mixture_assignment_probabilities <- data.frame(
FBID = TWAS_mashr_results$FBID,
posterior_weights_cov,
stringsAsFactors = FALSE
) %>% as_tibble() %>%
rename(P_equal_effects = equal_effects,
P_female_specific = Female_specific_1,
P_male_specific = Male_specific_1,
P_null = null,
P_sex_antag = Sex_antag_0.25)
TWAS_mixture_assignment_probabilities <- TWAS_mixture_assignment_probabilities %>%
left_join(huang_heritability, by = "FBID")
saveRDS(TWAS_mixture_assignment_probabilities,
"data/derived/TWAS/TWAS_mixture_assignment_probabilities.rds")
Here, we define significantly antagonistic transcripts as those where the relationship with fitness is significantly positive for one sex or age class and significantly negative for the other. Similarly, we define significantly concordant transcripts as those where the relationship with fitness is significantly positive for one sex or age class and also significantly positive for the other. This is quite conservative, because a transcript has to have a LFSR < 0.05 for two tests, giving two chances for a ‘false negative’ error.
TWAS_results <- data.frame(
FBID = TWAS_result_females$gene,
as.data.frame(get_pm(TWAS_ED)),
as.data.frame(get_lfsr(TWAS_ED))) %>%
as_tibble()
names(TWAS_results)[6:9] <- paste("LFSR", c("FE", "FL", "ME", "ML"), sep = "_")
p_cutoff <- 0.01
TWAS_results <- TWAS_results %>%
mutate(sig_SA_early = ifelse(sign(beta_FE) != sign(beta_ME) & LFSR_FE < p_cutoff & LFSR_ME < p_cutoff, "*", ""),
sig_SA_late = ifelse(sign(beta_FL) != sign(beta_ML) & beta_FL < p_cutoff & beta_ML < p_cutoff, "*", ""),
sig_AA_females = ifelse(sign(beta_FE) != sign(beta_FL) & LFSR_FE < p_cutoff & beta_FL < p_cutoff, "*", ""),
sig_AA_males = ifelse(sign(beta_ME) != sign(beta_ML) & LFSR_ME < p_cutoff & beta_ML < p_cutoff, "*", ""),
sig_SC_early = ifelse(sign(beta_FE) == sign(beta_ME) & LFSR_FE < p_cutoff & LFSR_ME < p_cutoff, "*", ""),
sig_SC_late = ifelse(sign(beta_FL) == sign(beta_ML) & beta_FL < p_cutoff & beta_ML < p_cutoff, "*", ""),
sig_AC_females = ifelse(sign(beta_FE) == sign(beta_FL) & LFSR_FE < p_cutoff & beta_FL < p_cutoff, "*", ""),
sig_AC_males = ifelse(sign(beta_ME) == sign(beta_ML) & LFSR_ME < p_cutoff & beta_ML < p_cutoff, "*", "")
) %>%
left_join(tbl(db, "genes") %>% select(FBID, gene_name, chromosome) %>% collect(), by = "FBID") %>% # gene info for each
left_join(sex_bias_in_expression, by = "FBID") %>%
left_join(TWAS_mixture_assignment_probabilities, by = "FBID") %>%
mutate(across(where(is.numeric), ~ round(.x, 2))) %>%
as_tibble() %>%
distinct()
TWAS_results %>%
write_csv("data/derived/TWAS/TWAS_results.csv")
sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.7
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] parallel stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] mashr_0.2.38 ashr_2.2-47 DT_0.13 kableExtra_1.3.4
[5] future.apply_1.5.0 future_1.17.0 glue_1.4.2 forcats_0.5.0
[9] stringr_1.4.0 dplyr_1.0.0 purrr_0.3.4 readr_2.0.0
[13] tidyr_1.1.0 tibble_3.0.1 ggplot2_3.3.2 tidyverse_1.3.0
[17] edgeR_3.30.1 limma_3.44.1 workflowr_1.6.2
loaded via a namespace (and not attached):
[1] nlme_3.1-149 fs_1.4.1 bit64_0.9-7 lubridate_1.7.10
[5] webshot_0.5.2 httr_1.4.1 rprojroot_1.3-2 tools_4.0.3
[9] backports_1.1.7 irlba_2.3.3 R6_2.4.1 rmeta_3.0
[13] DBI_1.1.0 colorspace_1.4-1 withr_2.2.0 tidyselect_1.1.0
[17] bit_1.1-15.2 compiler_4.0.3 git2r_0.27.1 cli_2.0.2
[21] rvest_0.3.5 xml2_1.3.2 scales_1.1.1 mvtnorm_1.1-0
[25] SQUAREM_2020.2 mixsqp_0.3-43 systemfonts_0.2.2 digest_0.6.25
[29] rmarkdown_2.5 svglite_1.2.3 pkgconfig_2.0.3 htmltools_0.5.0
[33] dbplyr_1.4.4 invgamma_1.1 htmlwidgets_1.5.1 rlang_0.4.6
[37] readxl_1.3.1 RSQLite_2.2.0 rstudioapi_0.11 generics_0.0.2
[41] jsonlite_1.7.0 vroom_1.5.3 magrittr_2.0.1 Matrix_1.2-18
[45] Rcpp_1.0.4.6 munsell_0.5.0 fansi_0.4.1 abind_1.4-5
[49] gdtools_0.2.2 lifecycle_0.2.0 stringi_1.5.3 whisker_0.4
[53] yaml_2.2.1 plyr_1.8.6 grid_4.0.3 blob_1.2.1
[57] listenv_0.8.0 promises_1.1.0 crayon_1.3.4 lattice_0.20-41
[61] haven_2.3.1 hms_0.5.3 locfit_1.5-9.4 knitr_1.32
[65] pillar_1.4.4 codetools_0.2-16 reprex_0.3.0 evaluate_0.14
[69] modelr_0.1.8 vctrs_0.3.0 tzdb_0.1.2 httpuv_1.5.3.1
[73] cellranger_1.1.0 gtable_0.3.0 assertthat_0.2.1 xfun_0.22
[77] broom_0.5.6 later_1.0.0 viridisLite_0.3.0 truncnorm_1.0-8
[81] memoise_1.1.0 globals_0.12.5 ellipsis_0.3.1