The kable function from the knitr package allows to display nicely formatted tables using R Markdown, as explained here. I recently encountered unexpected behaviour of kable when calling it from lapply or a function, which led to this post on StackOverflow. The answers were very detailed and enlightening, and I invite you to read them. They could be summarized in two points: be aware of side-effects, and prefer cat (with new lines) to print.
Batch tsv to csv conversion
I recently had to convert tables from tsv to csv format and found several ways to do it in this thread from StackOverflow, including the tsv2csv.py Python script below:
import sys
import csv
tabin = csv.reader(sys.stdin, dialect=csv.excel_tab)
commaout = csv.writer(sys.stdout, dialect=csv.excel)
for row in tabin:
commaout.writerow(row)
Here is a simple wrapper Bash script to run the conversion in batch:
for file in *.tsv
do
python tsv2csv.py < $file > ${file%.*}.csv
done
Running ApE on Ubuntu 14.4
ApE is a free plasmid editor, convenient to plan a cloning experiment. The Linux version is not maintained anymore, but still runs on Ubuntu 14.4 (Mac and Windows versions are both maintained).
To run on Ubuntu, download the latest Linux version, unzip and run, using:
wget http://biologylabs.utah.edu/jorgensen/wayned/ape/Download/Linux/ApE_linux_current.zip unzip ApE_linux_current.zip cd ApE Linux tclsh8.5 AppMain.tcl
If this does not work, you may have to install tk8.5 and tcl8.5:
sudo apt-get install tk8.5 tcl8.5
Add summary label in stacked bar chart using ggplot
The script below illustrates how to add one label per stack in a stacked bar chart using ggplot in R. In this case, labels indicate the sum of values represented in each bar stack. The idea is to create as many labels as bars, but assign text to only one label per stack, then plot labels according to stack height.
| # This script illustrates how to add one label per stack in a stacked bar chart using ggplot in R. | |
| # In this case, labels indicate the sum of values represented in each bar stack. | |
| # The idea is to create as many labels as bars, but assign text to only one label per stack, then plot labels according to stack height. | |
| # Data | |
| df <- data.frame(stack=factor(rep(c("A", "B", "C"), each=3)), cat=factor(rep(c("X", "Y", "Z"), times=3)), val=1:9) | |
| # Compute sum | |
| totals <- as.vector(by(df$val, df$stack, sum)) | |
| # Calculate label position | |
| pos <- rep(totals + 1, each=3) | |
| # Create labels | |
| labels <- unlist(lapply(as.character(totals), function(x) c(rep("", 2), x))) | |
| # Add labels and their position to data | |
| df <- data.frame(df, pos=pos, labels=labels) | |
| # Plot | |
| plot <- ggplot(df, aes(x=stack, y=val, fill=cat)) + | |
| geom_bar(stat="identity", position="stack") + | |
| geom_text(aes(y=pos, label=labels), vjust=0) | |
| plot |
Automate GeneTrail with iMacros
GeneTrail is a comprehensive web-based application to perform Gene Ontology and pathway analysis, with a user-friendly graphical interface. It is not possible, however, to access it programmatically, which can be cumbersome when processing more than a few datasets. It is nevertheless possible to automate interactions with the graphical interface using iMacros, which works as an add-on to web browsers such as Firefox.
iMacros is very simple to use:
- Once installed, open iMacros in Firefox.
- Click on “Record” and perform all the tasks you normally do on GeneTrail, including upload and download. Stop recording when done.
- The macro is now saved and you should see it in the iMacros panel. Right click on it and edit as follows:
- Locate the name of the file to be uploaded and replace it by a new file name.
- Add “WAIT SECONDS=120″ before the line starting with “ONDOWNLOAD”. If necessary, replace 120 with a number of seconds greater than the time GeneTrail takes to process results, so iMacros waits long enough before to try downloading.
- Edit the line starting with “ONDOWNLOAD” to indicate the folder and file names (e.g. “ONDOWNLOAD FOLDER=/home/sebastien/imacrosresults FILE=result1.zip WAIT=YES”). Delete other lines starting with “ONDOWNLOAD”, if any.
- Click on play. To replay with different upload and download file names, edit the script as indicated above.
iMacros can also be called from the command line, and it is possible to automate further, both on Linux and Windows.
Running David from R
David is an online resource to perform Gene Ontology analysis. Analysis can be done graphically on the website or programmatically, using David Web Service. The following snippet illustrates how to query David from R, using the Bioconductor “RDAVIDWebService” package.
| # This snippet illustrates how to query David from R, using the RDAVIDWebService package. | |
| # Load RDAVIDWebService. | |
| library("RDAVIDWebService") | |
| # Create a DAVIDWebService object connected to David, using your registration email. | |
| # To register, go to: http://david.abcc.ncifcrf.gov/content.jsp?file=WS.html. | |
| david <- DAVIDWebService$new(email='yourEmail@yourEmail.org') | |
| # Define foreground and background gene lists. | |
| # The foreground list should be contained within the background list. | |
| FG <- addList(david, myForegroundGenes, idType="REFSEQ_MRNA", listName="isClass", listType="Gene") | |
| BG <- addList(david, myBackgroundGenes, idType="REFSEQ_MRNA", listName="all", listType="Background") | |
| # Inspect FG and BG to see the proportion of genes recognized by David, and those that are unmapped. | |
| FG | |
| BG | |
| # Inspect "david" object to see the gene lists selected as foreground and background. | |
| david | |
| # Specifiy annotation categories. | |
| setAnnotationCategories(david, c("GOTERM_BP_ALL", "GOTERM_MF_ALL", "GOTERM_CC_ALL")) | |
| # Get functional annotation chart as R object. | |
| FuncAnnotChart <- getFunctionalAnnotationChart(david) | |
| # Print functional annotation chart to file. | |
| getFunctionalAnnotationChartFile(david, "FuncAnnotChart.tsv") | |
| # Get functional annotation clustering (limited to 3000 genes). | |
| FuncAnnotClust <- getClusterReport(david) | |
| # Print functional annotation clustering to file (limited to 3000 genes). | |
| getClusterReportFile(david, "FuncAnnotClust.tsv") |
Gene format conversion with Biomart in R
Ensembl BioMart is a tool to query Ensembl database, thus allowing, for instance, to convert gene format. It can be used from a web interface or with the Bioconductor “biomaRt” package, as explained in Getting Genetics Done. The snippet below shows specifically how to find mRNA Refseq Ids associated with mouse gene symbols.
| # This snippet queries BioMart to find mRNA Refseq Ids associated with mouse gene symbols. | |
| # Load biomaRt. | |
| library(biomaRt) | |
| # Get vector of gene symbols from a table loaded in R. | |
| genes <- mytable$Gene | |
| # Choose BioMart database and dataset. | |
| mart <- useMart("ensembl", dataset="mmusculus_gene_ensembl") | |
| # Specify filter used to read input values. | |
| # A list of possible filters can be retrieved using listFilters. | |
| filters=c("mgi_symbol") | |
| # Specify attributes to be returned. | |
| # A list of possible attributes can be retrieved using listAttributes. | |
| attributes <- c("chromosome_name", "start_position", "end_position", "mgi_symbol", "refseq_mrna") | |
| # Retrieve attributes for submitted genes. | |
| mynewtable <- getBM(attributes=attributes, filters=filters, values=genes, mart=mart, uniqueRows=T) |
Get directory of running script
In shell scripts, it is often useful to know which directory the script is running from. Here is a way to get this information:
curdir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
“$0” is the script name. “dirname” returns the corresponding directory. “cd” changes to that directory, which becomes the working directory. “pwd” returns it, so it can be assigned to the variable “curdir”. The option “-P” tells to only use the physical directory structure and to not follow symbolic links. Note that “cd” is encapsulated using the “$(…)” syntax, so it does not change the working directory for the rest of the script.
Wrapper shell script for pipelines
This shell script (also on Github) is a wrapper to run a command on all files from a set of directories, and output to directories with matching names. I often use it in pipelines, to batch process files in a project directory structure similar to the one used by ProjectTemplate.
| #!/bin/bash | |
| # Wrapper to run a command on all files from a set of directories, and output to directories with matching names. | |
| # Parameters need to be edited according to your data structure. | |
| # The parameters here assume a project directory containing: | |
| # - a "src" directory, from which are run this script and the executable used in the command. | |
| # - a "data" directory, containing input directories that can be called using regular expressions. The input directories are named with an underscore-separated suffix indicating file format. | |
| # - a "munge" directory, where output directories will be created with names matching those of the input directories, using a different underscore-separated suffix to indicate the output file format. | |
| src_path=../src # Directory of the executable used in command -- edit with yours. | |
| in_path=../data # Data directory, where the input directories lie -- edit with yours. | |
| in_dir=*_bedgraph # Input directories; use regular expressions to select multiple directories at once -- edit with yours. | |
| out_path=../munge # Munge directoy, where the output directories lie -- edit with yours. | |
| out_dir_suffix=fixedstepwig # Suffix of output directories; the root name is the same as for matching input directories -- edit with yours. | |
| for dir in $in_path/$in_dir # Cycle through input directories. | |
| do | |
| dir_name=${dir##*/} # Extract directory name without path. | |
| dir_base=${dir_name%_*} # Extract directory name root witout suffix. | |
| out_dir=${dir_base}_${out_dir_suffix} # Compose output directory name by adding the output directory suffix to the input directory name root. | |
| [ -d $out_path/$out_dir ] || mkdir -p $out_path/$out_dir # Create output directory if it does not already exist. | |
| for file in $dir/* # Cycle through files in each input directory. | |
| do | |
| file_name=${file##*/} # Extract file name without path. | |
| file_base=${file_name%.*} # Extract file name root without the extension, defined as anything after the first "." character. | |
| out_file=${out_path}/${out_dir}/${file_base}.wig # Compose the output file name by adding a new extension to the input file name root. | |
| cmd="perl ${src_path}/bedgraph_to_wig.pl --bedgraph $file --wig $out_file --step 100 --compact" # Define command. | |
| [ -e $out_file ] || $cmd # Execute command if the output file does not already exist. | |
| done | |
| done |
Bam to wig conversion
Conversion from bam to wiggle format can be done using the rsem-bam2wig utility, which takes a sorted bam file as input. The syntax is rather simple:
rsem-bam2wig sorted-bam-input-filename wig-output-filename wiggle-plot-name [--no-fractional-weight]
The option “–no-fractional-weight” should be set if the bam file has not been generated by rsem.
To sort a bam file, use samtools:
samtools sort bam-input-filename sorted-bam-output-filename