Please do not use setwd
in a script, it changes working folder without explicit specifications from the user, so the results could be unpredictable for people that are not familiar with the content of the script.
Create a tab-separated file with input filename and output filename, or at least a file with all input files, unless you can pick them using a list.files(pattern = "<pattern_here>")
. Read this file as a data.frame
and use it with an apply
, so a function processes the df row-by-row. Let's say the file (named metadata.txt
) is:
in_file out_file
tgf.txt tgf.output.txt
abc.txt abc.filtered.txt
xyz.txt xyz.randomname.txt
Define a function called process_row()
in the Rscript:
process_row <- function(r) {
d <- read.table(r[[1]], header = FALSE);
x <- aggregate(d[, 2], list(d$V3), median);
write.table(x, r[[2]], quote=FALSE, row.names=TRUE);
}
And do the actual work:
meta_data <- read.table('./metadata.txt', sep = ' ', header = TRUE, stringsAsFactors = FALSE);
apply(meta_data, 1, process_row(r))
# You don't need a q() in an Rscript because it exits after the last line of code anyway.