ana_gg
ana_gg

Reputation: 370

Reading files in R inside a bash loop

I want to run a R script for 23 chromosomes. The files I need to read are "chr_1.txt, chr_2.txt,...,chr_23.txt"

So I have a bash file

#!/bin/bash
for chr in {1..23}; do \

sbatch torunR.sh "chr_$"
done

and another bash file (torunR.sh)

R CMD BATCH script.R

The problem is that I don't know how to read a different "chr_X.txt" files in R (script.R). I have tried chr_$ or chr_*', for example:

geno = read.table(file="chr_*.txt") but it didn't work.

Any ideas?? Thanks!!

Upvotes: 0

Views: 635

Answers (1)

Marcus
Marcus

Reputation: 3646

I'm not an expert in bash scripting so I don't know the necessity of batching, but I would modify your R script to use a command line argument created within the loop.

Your R script would look like this:

## script.R
targetFile <- commandArgs(trailingOnly = TRUE)

# optional status message
cat(sprintf("Processing file %s\n", targetFile))

geno <- read.table(file = targetFile)

Then modify your bash script to be something along the lines of

#!/bin/bash
for chr in {1..23}; do \

Rscript script.R "chr_$chr.txt"
done

Result when running bash script (with optional status message):

$ ./bashScript.sh
Processing file chr_1.txt
Processing file chr_2.txt
Processing file chr_3.txt
Processing file chr_4.txt
Processing file chr_5.txt
Processing file chr_6.txt
Processing file chr_7.txt
Processing file chr_8.txt
Processing file chr_9.txt
Processing file chr_10.txt
Processing file chr_11.txt
Processing file chr_12.txt
Processing file chr_13.txt
Processing file chr_14.txt
Processing file chr_15.txt
Processing file chr_16.txt
Processing file chr_17.txt
Processing file chr_18.txt
Processing file chr_19.txt
Processing file chr_20.txt
Processing file chr_21.txt
Processing file chr_22.txt
Processing file chr_23.txt

Upvotes: 2

Related Questions