Ira
Ira

Reputation: 99

Select files with same base names using R

Would it be possible to select files with same base names (uniq) from all the files in the directory. I have been able to get the list of all the files from the directory.

fastq.files <- list.files(path = rawdatapath, pattern = c("(.fastq.gz|.fq.gz|.fastq|.fq)$"), full.names = TRUE)
fastq.files

And the files would be something like this in the directory:

t1_R1.fq
t1_R2.fq
t2_R1.fq
t2_R1.fq

Here the uniq base name is t1 and t2

The given below is the bash equivalent.

#Shell Script:

#!bin/bash

for i in $(ls *.fastq | rev | cut -c 14- | rev | uniq)

do 

bowtie2 --very-sensitive -p16 --rg-id ${i} -x cprefseqs -1 ${i}_R1_001.fastq -2 ${i}_R2_001.fastq  -S $i.sam

done

Upvotes: 0

Views: 727

Answers (1)

Esther
Esther

Reputation: 1115

If your files all have that same format you can use lapply and strsplit to get all the unique base names

x <- file.names()
 [1] "t1_R1.fq" "t1_R2.fq" "t2_R1.fq" "t2_R1.fq"

#splits each string into a list using "_" as a delimiter and returns the first element
f <- lapply(strsplit(x, "_"), "[", 1)

f <- unique(unlist(f))
 [1] "t1" "t2"

res <- lapply(f, function(x) list.files(pattern=x))

Upvotes: 1

Related Questions