|
#!/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") |
if you want to pass the arguments (similar to Unix - bash style), you need to use Rscript, instead of interactive R. Check this
https://www.r-bloggers.com/passing-arguments-to-an-r-script-from-command-lines/
Have a look at this package: https://cran.r-project.org/web/packages/docopt/index.html
may be snakemake can do this. It supports passing config files to R.