使用copy()或sapply()重复用户定义的函数 [英] Repeating a user-defined function using replicate() or sapply()

查看:128
本文介绍了使用copy()或sapply()重复用户定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个自定义函数,如下所示:

I have defined a custom function, like this:

my.fun = function() {

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

 return(output)

}

返回由1000行和20列组成的输出矩阵output.

which returns an output matrix, output, composed by 1000 rows and 20 columns.

我需要做的是重复执行该函数5次,并将五个output结果存储到一个全新的矩阵中,例如final,但不使用另一个for循环 (这是为了使代码更清晰,也因为稍后我想尝试并行化这5个重复).

What I need to do is to repeat the function say 5 times and to store the five output results into a brand new matrix, say final, but without using another for-loop (this for making the code clearer, and also because in a second moment I would like to try to parallelize these additional 5 repetitions).

因此,final应该是具有5000行和20列的矩阵(这5次重复的原理是,在我使用的两个for循环中,除其他功能外,sample).

Hence final should be a matrix with 5000 rows and 20 columns (the rationale behind these 5 repetitions is that within the two for-loops I use, among other functions, sample).

我尝试使用final <- replicate(5, my.fun()),它可以正确地计算五个重复项,但是随后我必须手动"将元素放入全新的5000 x 20矩阵中. (也许使用sapply()?).非常感谢

I tried to use final <- replicate(5, my.fun()), which correctly computes the five replications, but then I have to "manually" put the elements into a brand new 5000 x 20 matrix.. is there a more elgant way to do so? (maybe using sapply()?). Many thanks

推荐答案

按原样,您可能有一个具有三个维度的数组.如果您想要一个列表,则可以添加simple = FALSE.试试这个:

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 ) )

或者在最终"仍然是数组的情况下可以使用aperm:

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.

这篇关于使用copy()或sapply()重复用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆