我正在尝试使用大文件/矩阵(Windows Vista 64 位,4G RAM)在 R (2.15.0) 中运行 for 循环。如果我对这个循环进行一次迭代,它工作正常。但是,如果我在多个文件上运行循环(并且我想执行数百个文件),则会耗尽内存。我试图在循环结束时删除文件,但它没有将内存返回给 Windows(正如我在 Windows 任务管理器中看到的那样)。似乎 R 试图从我的操作系统中获取越来越多的内存,而不是在删除文件后使用内部可用的内存。有什么解决方法吗?如果您需要有关研究问题的更多详细信息,我很乐意分享其余部分以找到合适的解决方案。
已经谢谢了!干杯,罗伯特
> library(VariantAnnotation)
> fi<-list.files("E:/1000genomes/chr22",full.names=T)
> for(i in 1:length(fi)) {
+ input=paste("smaller.00", i, ".gz", sep = "")
+ output=paste("geno.", i, ".RData", sep = "")
+ vcf = readVcf(input, "hg19")
+ genotypes=geno(vcf)$GT[,]
+ save(genotypes, file=output)
+ gc()
+ }
Error: scanVcf: Realloc could not re-allocate memory (873600000 bytes)
path: E:\1000genomes\chr22\smaller.002.gz
In addition: Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
Reached total allocation of 3963Mb: see help(memory.size)
2: In doTryCatch(return(expr), name, parentenv, handler) :
Reached total allocation of 3963Mb: see help(memory.size)
> gc()
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 4543758 242.7 12363911 660.4 18010556 961.9
Vcells 19536404 149.1 61090604 466.1 119317584 910.4
如果我删除脚本末尾的内容:
+ save(genotypes, file=output)
+ rm(vcf)
+ rm(genotypes)
+ rm(input)
+ rm(output)
+ rm(getal)
+ rm(i)
+ }
Error: scanVcf: Calloc could not allocate memory (18 of 1 bytes)
path: E:\1000genomes\chr22\smaller.001.gz
In addition: Warning message:
In doTryCatch(return(expr), name, parentenv, handler) :
Reached total allocation of 3963Mb: see help(memory.size)
> gc()
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 2355472 125.8 10798339 576.7 16872405 901.1
Vcells 1992717 15.3 62280756 475.2 105556441 805.4
我在互联网上发现从命令提示符运行可能有效,所以我将脚本放在 R-root 目录的“runthis.R”文件中并运行:Rscript.exe runthis.R --no-save --no -恢复
它运行了一个额外的文件,然后报告了同样的错误。
最佳答案
不知何故,我在分析中犯了一个错误。现在我发现(当然经过很多麻烦之后)确实 rm() 后跟 gc() 命令在我的情况下确实有效!感谢 mneI 指出这一点:)
关于r - 如何使用大文件防止 R 循环中的内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551342/