Search code examples
rbioinformaticssequencesfasta

write a table in "for loop" (R)


I have many sequences in a text file. I import these sequences using "read.fasta" function. I use "for loop" to create table of nucleotides frequency for each sequence and use "write.table" to have an output. But it create a file per each sequence(many output file and each file have table of a sequence). I search for a commands to create a file that have all tables.
note: "mydata.txt" is a file contain many sequence with fasta format

file=read.fasta(file="mydata") 
for (i in seq_along(file))
{
NucleotidesFrequency=table(file[[i]])
print(NucleotidesFrequency)
write.table(NucleotidesFrequency, paste(i, (".txt"), sep=""),sep="\t") 
}

Solution

  • You could try rbind (see ?rbind for details):

    ## create example data
    set.seed(1)
    s <- list(sample(LETTERS[1:4], size=20, replace=T), sample(LETTERS[1:4], size=20, replace=T))
    
    ## call table for each item in the list
    l <- lapply(s, table)
    l
    #[[1]]
    #A B C D 
    #4 5 5 6 
    #[[2]]
    #A B C D 
    #5 7 4 4
    
    ## using rbind to create a matrix
    d <- do.call(rbind, l)
    d
    #    A B C D
    #[1,] 4 5 5 6
    #[2,] 5 7 4 4
    
    ## write it into a file
    write.table(d, "file.txt")