有效读取fasta文件并计算R中的核苷酸频率

efficiently read in fasta file and calculate nucleotide frequencies in R

我如何读取 fasta 文件 (~4 Gb) 并计算 window 长度为 4 bps 的核苷酸频率?

使用

读取fasta文件耗时过长
library(ShortRead)
readFasta('myfile.fa')

我尝试使用(并且有很多)

对其进行索引
library(Rsamtools)
indexFa('myfile.fa')
fa = FaFile('myfile.fa')

但是我不知道如何访问这种格式的文件

加载Biostrings包然后使用readDNAStringSet()方法

来自example("readDNAStringSet"),稍作修改:

library(Biostrings)
# example("readDNAStringSet") #optional
filepath1 <- system.file("extdata", "someORF.fa", package="Biostrings")
head(fasta.seqlengths(filepath1, seqtype="DNA")) # 
x1 <- readDNAStringSet(filepath1)
head(x1)

我猜想 'slow' 读取一个大小的文件需要一分钟;比这更长的时间和软件以外的东西是问题所在。也许在处理之前询问您的文件来自哪里、您的操作系统以及您是否对文件进行了操作(例如,试图在文本编辑器中打开它们)是合适的。

如果 'too slow' 是因为您 运行 内存不足,那么分块阅读可能会有帮助。使用 Rsamtools

fa = "my.fasta"
## indexFa(fa) if the index does not already exist
idx = scanFaIndex(fa)

创建索引块,例如,分成 n=10 个块

chunks = snow::splitIndices(length(idx), 10)

然后处理文件

res = lapply(chunks, function(chunk, fa, idx) {
    dna = scanFa(fa, idx[chunk])
    ## ...
}, fa, idx)

使用 do.call(c, res) 或类似方法连接最终结果,或者如果您正在累积单个值,则可能使用 for 循环。索引 fasta 文件是通过调用 samtools 库;在 non-Windows.

上,在命令行上使用 samtools 也是一种选择

另一种方法是使用 Biostrings::fasta.index() 为文件编制索引,然后使用

分块
idx = fasta.index(fa, seqtype="DNA")
chunks = snow::splitIndices(nrow(fai), 10)
res = lapply(chunks, function(chunk) {
    dna = readDNAStringSet(idx[chunk, ])
    ## ...
}, idx)

如果每条记录由单行 DNA 序列组成,则通过 readLines() 以 (even-numbered) 个块将记录读入 R 并从那里进行处理相对容易

con = file(fa)
open(fa)
chunkSize = 10000000
while (TRUE) {
    lines = readLines(fa, chunkSize)
    if (length(lines) == 0)
        break
    dna = DNAStringSet(lines[c(FALSE, TRUE)])
    ## ...
}
close(fa)