如何在R并行计算中使用Reduce()函数?

丹尼尔

我想对66000个列表元素的列表运行Reduce代码out1

trialStep1_done <- Reduce(rbind, out1)

但是,运行时间太长。我想知道是否可以借助并行计算程序包来运行此代码。

我知道有mclapplymcMap但我没有看到任何类似的功能mcReduce在并行计算软件包。

是否有类似的功能mcReduce可用于Reduce在R中并行完成我想做的任务?

非常感谢@BrodieG和@zheYuan Li,您的回答非常有帮助。我认为以下代码示例可以更精确地表示我的问题:

df1 <- data.frame(a=letters, b=LETTERS, c=1:26 %>% as.character())
set.seed(123)
df2 <- data.frame(a=letters %>% sample(), b=LETTERS %>% sample(), c=1:26 %>% sample() %>% as.character())
set.seed(1234)
df3 <- data.frame(a=letters %>% sample(), b=LETTERS %>% sample(), c=1:26 %>% sample() %>% as.character())
out1 <- list(df1, df2, df3)

# I don't know how to rbind() the list elements only using matrix()
# I have to use lapply() and Reduce() or do.call()
out2 <- lapply(out1, function(x) matrix(unlist(x), ncol = length(x), byrow = F))

Reduce(rbind, out2)
do.call(rbind, out2)
# One thing is sure is that `do.call()` is super faster than `Reduce()`, @BordieG's answer helps me understood why. 

因此,在这一点上,对于我的200000行数据集,do.call()很好地解决了这个问题。

最后,我想知道这是否是更快的方法?还是@ZheYuanLi演示的方式matrix()可能在这里?

布罗迪

问题不在于rbind,问题在于Reduce不幸的是,R中的函数调用非常昂贵,尤其是当您继续创建新对象时。在这种情况下,您调用rbind65999次,并且每次创建一个添加了一行的新R对象。相反,您只能rbind使用66000个参数调用一次,这将更快,因为内部rbind将在C中进行绑定,而不必调用R函数66000次并仅分配一次内存。在这里,我们将您的Reduce使用与Zheyuan的矩阵/未列表进行比较,最后将其与rbind调用一次with do.calldo.call允许您使用指定为列表的所有参数来调用函数)进行比较:

out1 <- replicate(1000, 1:20, simplify=FALSE)  # use 1000 elements for illustrative purposes

library(microbenchmark)    
microbenchmark(times=10,
  a <- do.call(rbind, out1),
  b <- matrix(unlist(out1), ncol=20, byrow=TRUE),
  c <- Reduce(rbind, out1)
)
# Unit: microseconds
#                                                expr        min         lq
#                           a <- do.call(rbind, out1)    469.873    479.815
#  b <- matrix(unlist(out1), ncol = 20, byrow = TRUE)    257.263    260.479
#                            c <- Reduce(rbind, out1) 110764.898 113976.376
all.equal(a, b, check.attributes=FALSE)
# [1] TRUE
all.equal(b, c, check.attributes=FALSE)
# [1] TRUE

Zheyuan是最快的,但是就所有意图和目的而言,该do.call(rbind())方法都非常相似。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章