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

纵饮孤独 提交于 2019-12-02 18:33:07

As is stands you probably have an array with three dimensions. If you wanted to have a list you would have added simplify=FALSE. Try this:

do.call( rbind, replicate(5, my.fun(), simplify=FALSE ) )

Or you can use aperm in the case where "final" is still an array:

fun <- function() matrix(1:10, 2,5)
final <- replicate( 2, fun() )
> final
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

> t( matrix(aperm(final, c(2,1,3)), 5,4) )
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
[3,]    1    3    5    7    9
[4,]    2    4    6    8   10

There may be more economical matrix operations. I just haven't discovered one yet.

If you replace replicate with rlply from the plyr package, you can use do.call with rbind:

library(plyr)
do.call(rbind, rlply(5, my.fun()))

If you'd rather not rely on the plyr package, you can always do:

do.call(rbind, lapply(1:5, function(i) my.fun()))

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()
SHARMISTHA CHAKRABORTTY

Try this:

final <- replicate(5, my.fun(), simplify = "matrix")

You will get the result of 'final' in the form of matrix.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!