R中的foreach():返回两个项目,分别绑定所有第一项和所有第二项

时间:2015-08-22 23:26:37

标签: r list foreach lapply rbind

使用R和foreach包进行并行处理时遇到此问题。

我每小时有一个数据集,为期一年。仅考虑一个数据集,并行运行我使用:

    day = foreach (h = 1:24, .combine=rbind)   %dopar%     {
    ...
    singlematrix         # return a single matrix
    }
    24matrices <- day
    # thanks to rbind, all single matrices are piled together

每个循环返回一个矩阵,.combine=rbind使得我得到一个更大的矩阵,即24个单个矩阵。

如果不是每h返回一个矩阵,我想实现类似的东西:

    day = foreach (h = 1:24, .combine=rbind)   %dopar%     {
    ...
    list("row"=singlerow, "matrix"=singlematrix)     # return both
    }
    24rows <- day[[1]]             # singlerows piled up
    24matrices <- day[[2]]         # singlematrices piled up

如何将所有24个单人组合在一起,将所有24个单一矩阵组合在一起,而不混合行和矩阵?

我尝试插入.multicombine=TRUE,返回list( "row"=item1, "matrix"=item2),但行和矩阵混合在一起。不幸的是我对lapply并不满意,这可能就是去这里的方式。 非常感谢!

1 个答案:

答案 0 :(得分:1)

我会推测,因为我没有你日常矩阵的实际结构,但也许这会让你朝着一个好的方向前进:

set.seed(42)
library(foreach)
day <- foreach(h = 1:24) %dopar% {
    ## ...
    mtx1 <- matrix(sample(6), nr=2)
    mtx2 <- matrix(sample(8), nr=2)
    list(mtx1, mtx2)
}

length(day)
## [1] 24
str(day[[1]])
## List of 2
##  $ : int [1:2, 1:3] 6 5 2 3 4 1
##  $ : int [1:2, 1:4] 6 1 4 8 2 3 5 7

ret1 <- do.call('rbind', lapply(day, `[[` , 1))
ret2 <- do.call('rbind', lapply(day, `[[` , 2))

str(ret1)
##  int [1:48, 1:3] 6 5 3 5 3 5 1 5 5 1 ...
str(ret2)
##  int [1:48, 1:4] 6 1 8 1 1 6 8 5 7 4 ...