1

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?

PaulH
  • 27
  • 1
  • 4

3 Answers3

1

solution is quite simple when using paste function:

library(ape)
filenames = dir(pattern="*.nex")
for (f in filenames){
  i <- read.nexus.data(f)
  write.dna(i, file = paste0("./fastas/",f,".fasta"), format = "fasta")
}
Wietze314
  • 5,942
  • 2
  • 21
  • 40
1

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")
}
plannapus
  • 18,529
  • 4
  • 72
  • 94
0

something not stylish, but it works well

library(ape)
tmp <- list.files(pattern = "*.nex")
genes <- lapply(tmp, read.nexus.data)
for (i in 1:length(tmp))
  write.dna(genes[[i]], file = paste(tmp[i], ".fasta"), format = "fasta")