gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:41:02 26 4
gpt4 key购买 nike

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

trialStep1_done <- Reduce(rbind, out1)

但是,运行时间太长。我想知道是否可以在并行计算包的帮助下运行此代码。

我知道有 mclapply , mcMap ,但我没有看到像 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 中的函数调用很昂贵,尤其是当您不断创建新对象时。在这种情况下,您调用 rbind 65999 次,每次你创建一个新的 R 对象并添加一行。相反,您可以调用 rbind一次有 66000 个参数,这将更快,因为内部 rbind将在 C 中进行绑定(bind),而不必调用 R 函数 66000 次并且只分配一次内存。在这里我们比较您的Reduce与哲元的矩阵/unlist 一起使用,最后与 rbind 一起使用用 do.call 调用过一次( do.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

哲元是最快的,但出于所有意图和目的, do.call(rbind())方法非常相似。

关于r - 如何在 R 并行计算中使用 Reduce() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37636463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com