【问题标题】:foreach() in R: return two items, rbind all first items and all second items separatelyR中的foreach():返回两个项目,分别rbind所有第一个项目和所有第二个项目
【发布时间】:2015-11-16 15:54:21
【问题描述】:

我在使用 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,这可能是这里的路。 非常感谢!

【问题讨论】:

    标签: r list foreach lapply rbind


    【解决方案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 ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      相关资源
      最近更新 更多