【发布时间】:2026-01-15 10:55:02
【问题描述】:
我正在尝试使用 doSMP / foreach 来并行化 R 中的一些代码。
我有一个巨大的遗传数据二维矩阵 - 10,000 个观察值(行)和 300 万个变量(列)。由于内存问题,我不得不将这些数据分成 1000 个变量的块。
我想读入每个文件,做一些统计,然后将这些结果写到一个文件中。使用 for 循环很容易,但我想使用 foreach 来加速它。这就是我正在做的事情:
# load doSMP, foreach, iterators, codetools
require(doSMP)
# files i'm processing
print(filelist <- system("ls matrix1k.*.txt", T))
#initialize processes
w <- startWorkers(2)
registerDoSMP(w)
# for each file, read into memory, do some stuff, write out results.
foreach (i = 1:length(filelist)) %dopar% {
print(i)
file <- filelist[i]
print(file)
thisfile <- read.table(file,header=T)
# here i'll do stuff using that file
# here i'll write out results of the stuff I do above
}
#stop processes
stopWorkers(w)
但这会导致错误:Error in { : task 2 failed - "cannot open the connection"。当我将%dopar% 更改为%do% 时,完全没有问题。
【问题讨论】:
-
不回答您的问题,但将数据放入 NetCDF 文件(带有 ncdf 包)可以方便快捷地输入数据块;使用
scan()而不是read.table会快得多。我猜想在循环之外打开文件 (?file) 可能会起作用 -
现在仍在回答您的问题,但@Martin 建议的中途做法是在
read.table中使用colClasses参数。这真的可以加快速度。 -
您能提供更多细节吗? 1)它打开了一些文件,还是立即失败? 2) 你是在写不同的文件还是写一个相同的文件?
标签: r foreach parallel-processing