PaulH PaulH - 2 months ago 16
R Question

loop over all files in folder in R

I would like to import all files from a folder, convert the files and then export them with the same name, but with a different extension. In my specific case I want to convert 150 nexus files (.nex) to fasta files (.fasta)

This is how the code looks if I do it one by one:

library(ape)
gen1 <- read.nexus.data("gen1.nex") #import nexus file
write.dna(gen1, file = "./fastas/gen1.fasta", format = "fasta") #export fastafile


But now I fail to make a working for-loop to do all 150 files in one run. This is what I tried:

library(ape)
filenames = dir(pattern="*.nex")
for (i in filenames){
i <- read.nexus.data(i)
write.dna(i, file = "./fastas/i.fasta", format = "fasta")
}


When I run this code, I get only one file named "i.fasta" and not 150 files named gen1.fasta, gen2.fasta, DNAsequence1.fasta, DNAsequence2.fasta, etc. How should I change the for-loop to make it work correct?

Answer

You need to 1) include the value of i inside the character string giving the fasta filename, 2) not rewrite i when you're loading your nexus file.

library(ape)
filenames = dir(pattern="*.nex")
for (i in filenames){
    dat <- read.nexus.data(i)
    write.dna(dat, file = sprintf("./fastas/%s.fasta", i), format = "fasta")
}
Comments