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

前端 未结 4 1817
太阳男子
太阳男子 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:27

    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.

提交回复
热议问题