2
我想使用doParallel
包对R中的大数据帧执行一些并行处理。让我们调用数据框mydata
。我想遍历按行数据帧,所以像R:使用doParallel将若干行并行处理在一起
foreach(x=iter(mydata, by='row')) %dopar%{
... do stuff ...
}
但是,那不是很正确,因为在每一个循环,我需要有机会获得几行。假设变量idx
包含哪些行需要一起处理的信息。比方说idx
是一个矩阵,看起来像
1 2 3
10 12 14
4 7 9
...
每一行表示mydata
需要一起处理的行。我怎样才能使用doParallel
包来做到这一点?
编辑:我看到我可以发送“块”data.frame使用iblkcol
有没有办法发送我选择的非连续块?
编辑:我结束了使用自定义iteraor:基于
apply(idx,1,function(idx) list(mydata[idx,]))
然后
> data <- data.frame(A=sample(letters,10),B=rnorm(10))
> data
A B
1 z 0.5105797
2 h 1.2559502
3 a 0.9697254
4 n -1.4189076
5 e -0.5800640
6 b 0.2907486
7 q -2.4414012
8 d 1.8146928
9 v 0.2510003
10 x -0.2011185
> idx <- list(c(1,2),c(4,5),c(3,6,7),c(8,9,10))
>
> library(iterators)
>
> ialn <- function(x, idx){
+ it <- iter(idx)
+ nextEl <- function(){
+ n <- nextElem(it)
+ x[n,]
+ }
+ obj <- list(nextElem=nextEl)
+ class(obj)<- c('ialn','abstractiter','iter')
+ obj
+ }
>
>
> it <- ialn(data,idx)
> nextElem(it)
A B
1 z 0.5105797
2 h 1.2559502
> nextElem(it)
A B
4 n -1.418908
5 e -0.580064
谢谢!使用自定义迭代器,我能够得到我想要的。 – bdeonovic 2014-11-23 23:49:35