使.combine函数可缩放 [英] make .combine function scaleable

查看:157
本文介绍了使.combine函数可缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用foreach,并且遇到了使.combine函数可扩展的问题。例如,下面是一个简单的组合函数:

pre $ MyComb < - function(part1,part2){
xs< (part1 $ x,part2 $ x)
ys <-c(part1 $ y,part2 $ y)
return(list(xs,ys))
}

当我使用这个函数将一个foreach语句与一个不是2的迭代器结合起来时,它会错误地返回它。例如这个工程:

pre $ x $ foreach(i = 1:2,.combine = MyComb)%dopar%list( x= i * 2,y= i * 3)

p>

  x = foreach(i = 1:3,.combine = MyComb)%dopar%list(x= i * 2, y= i * 3)

是否有一种方法可以扩展组合函数以使其可扩展到n次迭代? 看起来像一块(可以作为一个部分传回去),或者采取许多论据,并把它们同时放在一起(具有相同的限制)。因此,至少你的 MyComb 必须返回一个包含组件 x y (这就是你的每一块%dopar%所做的。



有几种方法可以做这:

  MyComb1<  -  function(part1,part2){
list(x = c(part1 $ x ,part2 $ x),y = c(part1 $ y,part2 $ y))
}

x = foreach(i = 1:3,.combine = MyComb1)%dopar%list (x= i * 2,y= i * 3)



  MyComb2<  -  function(...){
dots = list(。 ...)
ret < - lapply(names(dots [[1]]),function(e){
unlist(sapply(dots,'[[',e))
})
name(ret)< - names(dots [[1]])
ret
}

s = foreach(i = 1:3 ,. combine = MyComb2)%dopar%list(x= i * 2,y= i * 3)
x = foreach(i = 1:3,.combine = MyComb2,.multicombine = TRUE)%dopar %list(x= i * 2,y= i * 3)

可以采取多个piec es一次结合起来。这是更一般(但更复杂)。

I am trying to use foreach and am having problems making the .combine function scalable. For example, here is a simple combine function

MyComb <- function(part1,part2){
          xs <- c(part1$x,part2$x)
          ys <- c(part1$y,part2$y)
          return(list(xs,ys))
          }

When I use this function to combine a foreach statement with an iterator other than 2 it returns it incorrectly. For example this works:

   x = foreach(i=1:2,.combine=MyComb) %dopar% list("x"=i*2,"y"=i*3)

But not this:

 x = foreach(i=1:3,.combine=MyComb) %dopar% list("x"=i*2,"y"=i*3)

Is there a way to generalize the combine function to make it scalable to n iterations?

解决方案

Your .combine function must take either two pieces and return something that "looks" like a piece (could be passed back in as a part) or take many arguments and put all of them together at once (with the same restrictions). Thus at least your MyComb must return a list with components x and y (which is what each piece of your %dopar% do.

A couple of ways to do this:

MyComb1 <- function(part1, part2) {
    list(x=c(part1$x, part2$x), y=c(part1$y, part2$y))
}

x = foreach(i=1:3,.combine=MyComb1) %dopar% list("x"=i*2,"y"=i*3)

This version takes only two pieces at a time.

MyComb2 <- function(...) {
    dots = list(...)
    ret <- lapply(names(dots[[1]]), function(e) {
        unlist(sapply(dots, '[[', e))
    })
    names(ret) <- names(dots[[1]])
    ret
}

s = foreach(i=1:3,.combine=MyComb2) %dopar% list("x"=i*2,"y"=i*3)
x = foreach(i=1:3,.combine=MyComb2, .multicombine=TRUE) %dopar% list("x"=i*2,"y"=i*3)

This one can take multiple pieces at a time and combine them. It is more general (but more complex).

这篇关于使.combine函数可缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆