【问题标题】:Creating vector of results of repeated function calls in R在 R 中创建重复函数调用的结果向量
【发布时间】:2012-11-09 17:57:48
【问题描述】:

我有一个函数使用runif 来计算一些值,所以每次调用它时,结果都会略有不同。我想计算多次调用该函数的结果的平均值。

为此,最好用重复函数调用的结果创建一个向量

有没有一种简单的惯用方法来创建重复函数调用的向量?我试试

rep(my_function_call(), 10)

但它只是调用函数一次并重复结果 10 次。我希望函数评估 10 次,并得到一个结果向量。

【问题讨论】:

    标签: r


    【解决方案1】:

    replicate 是你的朋友。见?replicate

    replicate(10, my_function_call()) # this would be what you're looking for
    

    【讨论】:

    • 手册引用:replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation)
    猜你喜欢
    • 2019-03-31
    • 2018-09-13
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2012-11-03
    相关资源
    最近更新 更多