Created
July 18, 2018 15:24
-
-
Save jrjhealey/97974abcccc359931697fe60b2f215c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env Rscript | |
# Perform cell-wise averaging of matrices (ignoring headers and row names) | |
# Standard install if missing | |
list.of.packages <- c("argparse", "abind") | |
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])] | |
if(length(new.packages)) install.packages(new.packages) | |
for(i in list.of.packages){suppressMessages(library(i, character.only = TRUE))} | |
# Parse commandline arguments | |
parser <- ArgumentParser() | |
parser$add_argument('-i', | |
'--infiles', | |
nargs='+', | |
required=TRUE, | |
help="All the matrices to average.") | |
parser$add_argument('-s', | |
'--separator', | |
action='store', | |
default='\t', | |
help='The field separator for the input matrices (they should all match). [Def = \t].') | |
parser$add_argument('-o', | |
'--outfile', | |
action='store', | |
required=TRUE, | |
help='Output file to store the averaged matrix in.') | |
args <-parser$parse_args() | |
cat("Averaging the following matrices:", "\n") | |
cat("=================================", "\n") | |
args$infiles | |
cat("Outputting to:", "\n") | |
cat("==============", "\n") | |
args$outfile | |
# Read tables in from argument list | |
cat("Made tables...", "\n") | |
tables <- lapply(args$infiles, read.table, header=TRUE, row.names=1, check.names=FALSE, sep=args$sep) | |
# Convert to matrices | |
cat("Made matrices...", "\n") | |
matrices <- lapply(tables, as.matrix) | |
# 'Vertically' bind the matrices. Think of it as a z-stack of matrices. | |
cat("Vertically binding arrays...", "\n") | |
stack <- abind(matrices, along=3) | |
# Average them | |
stack_avg <- apply(stack, c(1,2), mean) | |
# Write file | |
write.table(stack_avg, args$outfile, sep=args$sep, col.names = NA, quote = FALSE) | |
cat("File written to: ", "\n", args$outfile, "\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment