# How to transform a DNAStringSet from the Bioconductor package Biostrings to a data frame?

I am working on Mac OS X. I am using R version 3.5.1.

I have important a FASTA file into R using Biostrings::readDNAStringSet. This creates a DNAStringSet object in R.

I would like to transform it into a data frame so that I can then plot the widths with ggplot2.

as.data.frame on my DNAStringSet object returns a data frame with only one column. Is there a function that returns a data frame with columns width, seq and names present in the DNAStringSet object?

According to the documentation (?Biostrings::DNAStringSet):

width(x): A vector of non-negative integers containing the number of letters for each element in x. Note that width(x) is also defined for a character vector with no NAs and is equivalent to nchar(x, type="bytes").

names(x): NULL or a character vector of the same length as x containing a short user-provided description or comment for each element in x. These are the only data in an XStringSet object that can safely be changed by the user. All the other data are immutable! As a general recommendation, the user should never try to modify an object by accessing its slots directly.

as.character(x, use.names=TRUE): Converts x to a character vector of the same length as x. The use.names argument controls whether or not names(x) should be propagated to the names of the returned vector.

This should be enough for you to create a data.frame:

dss2df <- function(dss) data.frame(width=width(dss), seq=as.character(dss), names=names(dss)) 

Also, if you have a huge DNAStringSet, perhaps you do not want to convert all the sequences to characters; storing sequences as characters supposedly is less efficient. For plotting it might be sufficient to have just widths.

qplot(width(dss), geom='histogram'))