Last updated: 2020-06-25

Checks: 5 2

Knit directory: psychencode/

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.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

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(20200622) 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.

Using absolute paths to the files within your workflowr project makes it difficult for you and others to run your code on a different machine. Change the absolute path(s) below to the suggested relative path(s) to make your code more reproducible.

absolute relative
/Users/sabrinami/Github/psychencode .
/Users/sabrinami/Github/psychencode/data/PEC_TWAS_weights data/PEC_TWAS_weights

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 b51eff6. 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:    code/.DS_Store
    Ignored:    data/.DS_Store
    Ignored:    output/.DS_Store

Untracked files:
    Untracked:  .gitignore
    Untracked:  code/annotate_snp_by_position.py
    Untracked:  data/PEC_TWAS_weights.tar.gz
    Untracked:  output/weights_out.txt.gz

Unstaged changes:
    Modified:   analysis/psychencode.Rmd
    Modified:   output/psychencode.db

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/psychencode.Rmd) and HTML (docs/psychencode.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 b51eff6 sabrina-mi 2020-06-24 new
html b51eff6 sabrina-mi 2020-06-24 new

Introduction

Gandal et al analyzed autism spectrum disorder, schizophrenia, and bipolar disorder across multiple levels of transcriptomic organization—gene expression, local splicing, transcript isoform expression, and coexpression networks for both protein-coding and noncoding genes to produce a quantitative, genome-wide resource. They performed TWAS based on postmortem frontal and temporal cerebral cortex samples from 1695 adults. RNA-sequencing reads were aligned to the GRCh37.p13 (hg19) reference genome. We generated a model using elastic-net weights released by Gandal et al. LD was calculated using 1000 Genomes European reference panel. More info on the study: https://science.sciencemag.org/content/362/6420/eaat8127. The TWAS is available at http://resource.psychencode.org

Definitions

Define variables in the terminal:

export PRE="/Users/sabrinami/Github/psychencode"
export CODE=$PRE/code
export DATA=$PRE/data
export OUTPUT=$PRE/output

Now in R:

PRE="/Users/sabrinami/Github/psychencode"
DATA=glue::glue("{PRE}/data")
OUTPUT=glue::glue("{PRE}/output")

Download Data

TWAS data can be downloaded at http://resource.psychencode.org Or download from terminal by running

cd $DATA
wget "http://resource.psychencode.org/Datasets/Derived/PEC_TWAS_weights.tar.gz"

And unzip

tar -xvf PEC_TWAS_weights.tar.gz

Load File

When you open the PEC_TWAS_weights directory, there will be ~15,000 binary files. Each file contain information for a single gene. When loaded, an .RDat file contains snps (snp info), wgt.matrix (weights), and cv.performance (cross validation) tables. In the snps table, the first column is chromosome, the fourth is position, the fifth is effect allele, and the sixth is reference allele. In the wgt.matrix table, the rownames are the snp ids, and the columns are the weights derived from each method for each snp. In R, set the directory to PEC_TWAS_weights, then load the file:

setwd("/Users/sabrinami/Github/psychencode/data/PEC_TWAS_weights")
load("ENSG00000000457.wgt.RDat")

Now, the snps, wgt.matrix, and cv.performance are defined as variables.

Load Libraries

Run in R:

library(RSQLite)
library(tidyverse)
library(data.table)

Convert File to Dataframe

make_df will load a file and store its data as a dataframe. This is only for a single gene, so later will be repeated for all genes. The input is the name of the .RDat file, and it returns returns dataframe with gene, position, chromosome, ref allele, eff allele, and non-zero enet weights.

make_df <- function(file) {
  load(file)  
  weights <- data.frame(wgt.matrix) 
  snps <- data.frame(snps) 
  rownames(weights) <- c() 
  weights$gene <- substr(file, 1, nchar(file) - 9)
  weights$chromosome <- snps$V1 
  weights$position <- snps$V4
  weights$ref_allele <- snps$V6
  weights$eff_allele <- snps$V5
  weights %>% filter(enet != 0) %>% select(gene, chromosome, position, ref_allele, eff_allele, enet)
}

Make Weights Table

First, combine .RDat file names in a vector

files <- list.files(pattern = "\\.RDat")

The goal is to write tab delimited file with gene, chr, pos, ref, eff, and enet data for all genes in directory. Convert the first file in the vector to dataframe, then write it to a text file. And repeat for the remaining files, then append to the same text file.

pre_weights = glue::glue("{OUTPUT}/pre_weights.txt")
write.table(make_df(files[1]), pre_weights, sep = "\t", quote = FALSE, row.names = FALSE)
for(i in 2:length(files)) {
  write.table(make_df(files[i]), pre_weights, append = TRUE, sep = "\t", quote = FALSE, col.names = FALSE, row.names = FALSE)
}

Add rsids

Following Yanyu’s recommendation, rsids were added to pre_weights.txt using her python script and a hg19 lookup table. Her script is here: https://github.com/liangyy/misc-tools/tree/master/annotate_snp_by_position The lookup table, dbSNP150_list.txt, contains chromosome, position, ref, alt, rsid, and dbSNPBuildID. So the rsid for each snp is generated by matching the chromosome and position from psychencode models to lookup table. The output, weights_out.txt, will have gene, chr, pos, ref, eff, and rsid as new_id. In the terminal, run:

python3 $CODE/annotate_snp_by_position.py \
--input $OUTPUT/pre_weights.txt --chr_col 2 --pos_col 3 \
--lookup_table $DATA/dbSNP150_list.txt.gz --lookup_chr_col 1 --lookup_start_col 2 --lookup_end_col 2 --lookup_newid_col 5 --if_input_has_header 1 \
--out_txtgz $OUTPUT/weights_out.txt.gz

This will take several hours. Unzip weights_out.txt before reading into R.

gunzip $OUTPUT/weights_out.txt.gz

Add varIDs

Read weights_out.txt in R, and define varID from chromosome, position, reference and effect alleles. (The RNA-seq was in hg19, so varID is defined in b37)

weights <- fread("weights_out.txt")
weights$varID <- paste("chr", weights$chromosome, weights$position, weights$ref_allele, weights$eff_allele, "b37", sep = "_")
weights <- weights %>% select(gene, rsid, varID, ref_allele, alt_allele, enet) %>% rename(weight = enet, rsid = new_id)

Make Extra Table

Generate number of snps for each gene from the weights table. For now, include blank columns to match PrediXcan format (gene, genename, n.snps.in.model, pred.perf.R2, pred.perf.pval, pred.perf.qval)

extra <- weights %>% group_by(gene) %>% summarise(n.snps.in.model = n())
extra$genename <- NA
extra$pred.perf.R2 <- NA
extra$pred.perf.pval <- NA
extra$pred.perf.qval <- NA
extra <- extra[c(1, 3, 2, 4, 5, 6)]

Write to SQLite Database

Create database connection, and write the weights and extra tables to database.

model_db = glue::glue("{OUTPUT}/psychencode.db")
conn <- dbConnect(RSQLite::SQLite(), model_db)
dbWriteTable(conn, "weights", weights)
dbWriteTable(conn, "extra", extra)

To double check, confirm there is a weights and extra table, and show their contents.

dbListTables(conn)
dbGetQuery(conn, 'SELECT * FROM weights') %>% head
dbGetQuery(conn, 'SELECT * FROM extra') %>% head

Lastly, disconnect from database connection

dbDisconnect(conn)

sessionInfo()
R version 3.6.2 (2019-12-12)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/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     

loaded via a namespace (and not attached):
 [1] workflowr_1.6.2 Rcpp_1.0.3      rprojroot_1.3-2 digest_0.6.23  
 [5] later_1.0.0     R6_2.4.1        backports_1.1.5 git2r_0.27.1   
 [9] magrittr_1.5    evaluate_0.14   highr_0.8       stringi_1.4.5  
[13] rlang_0.4.2     fs_1.3.1        promises_1.1.0  whisker_0.4    
[17] rmarkdown_2.1   tools_3.6.2     stringr_1.4.0   glue_1.3.1     
[21] httpuv_1.5.3.1  xfun_0.12       yaml_2.2.0      compiler_3.6.2 
[25] htmltools_0.4.0 knitr_1.27