Repeating a user-defined function using replicate() or sapply()

前端 未结 4 1772
太阳男子
太阳男子 2021-02-01 09:52

I have defined a custom function, like this:

my.fun = function() {

      for (i in 1:1000) {
      ...
        for (j in 1:20) {
          ...
        }
      }         


        
4条回答
  •  庸人自扰
    2021-02-01 10:29

    Depends on which package you use for parallel computing, but here's how I would do it (hide it in a loop using sapply, just like replicate).

    library(snowfall)
    sfInit(parallel = TRUE, cpus = 4, type = "SOCK")
    # sfExport() #export appropriate objects that will be needed inside a function, if applicable
    # sfLibrary() #call to any special library
    out <- sfSapply(1:5, fun = my.fun, simplify = FALSE)
    sfStop()
    

提交回复
热议问题