开始使用免费开始使用

使用 parSapply()

我们之前玩过如下游戏:

  • 初始化:total = 0
  • 掷一个骰子并将点数加到 total
  • 如果 total 为偶数,则将 total 重置为 0。
  • 如果 total 大于 10,游戏结束。

可以使用 play() 函数来模拟这个游戏:

play <- function() {
  total <- no_of_rolls <- 0
  while(total < 10) {
    total <- total + sample(1:6, 1)

    # If even. Reset to 0
    if(total %% 2 == 0) total <- 0 
    no_of_rolls <- no_of_rolls + 1
  }
  no_of_rolls
}

要将游戏模拟 100 次,可以使用 for 循环或 sapply()

res <- sapply(1:100, function(i) play())

这非常适合并行运行!

若要在集群上使用函数,请使用 clusterExport() 函数。它接收一个集群对象和一个函数名字符串。

clusterExport(cl, "some_function")

本练习是课程的一部分

高效 R 代码写作

查看课程

练习说明

play() 函数已在您的工作区中定义。

  • 使用 makeCluster() 创建一个集群;将使用的内核数设为 2。将结果保存为 cl
  • play() 函数导出到该集群。
  • 将上面的 sapply() 调用改写为 parSapply()
  • 使用 stopCluster() 停止该集群。

交互式实操练习

通过完成这段示例代码来试试这个练习。

library("parallel")
# Create a cluster via makeCluster (2 cores)
cl <- ___

# Export the play() function to the cluster
___

# Re-write sapply as parSapply
res <- sapply(1:100, function(i) play())

# Stop the cluster
___
编辑并运行代码