Split multi-fasta file into separate single fasta files in R

Viewed 284

I had a single fasta file which was in the format

>header
ACGATGCA.....

My aim was to break the fasta file in a specific manner for some biological analysis, the R code for which was:

loadfasta <- readNonStandardFastaFile("File_name.txt/File_name.fasta")
loadfasta_2 <- "Nucelotide sequence(fasta file)"                   #e.g. "ACGATGCA...."
                                                                   #Loaded the file using readNonStandardFastaFile
                                                                   #loadfasta_2 <- loadfasta$content

break_fasta <- rollapply(strsplit(loadfasta_2, "")[[1]], 15, paste, collapse = "", partial = TRUE, align = "left")
new_data_frame <- read.table(text =  break_fasta, col.names = "Segment")
new_data_frame$MeanPosition<- paste(1:nrow(new_data_frame),sep="")
dataframe_new <- new_data_frame[c("MeanPosition","Segment")]
dataframe_new

Now I have to perform the same function for a multi-fasta file containing 1333 different sequences in the format:

>header1
AACGATCGA.....
>header2
CAAGTCGAT.....
>header3
CCGTAGACT.....

Is there any way to modify the previous mentioned code with the help of loops or maybe separating the multi-fasta into individual fasta files and loading those separated fasta files in any other way which would solve my issue? Any help will be greatly appreciated!

1 Answers

You can read it in data.frame then save it in folder named fastafolder using a for loop :

fasta <- read.table("~/fasta", quote="\"", comment.char="")

dir.create("~/fastafolder")

for (line in 1:nrow(fasta)) {
  rows <- 2 * line - 1
  if (rows < nrow(fasta)) {
    write(fasta[rows:(rows + 1), 1] , paste0("~/fastafolder/fasta" , line))
  }
}

Created on 2022-05-28 by the reprex package (v2.0.1)

Related