【问题标题】:Can R recognize the type of distribution used as a function argument?R 可以识别用作函数参数的分布类型吗?
【发布时间】:2017-10-26 13:16:29
【问题描述】:

背景

我有一个名为TBT 的简单函数。该函数有一个名为x 的参数。用户可以为参数x提供R中存在的任何类型rdistribution_name()(例如rnorm()rf()rt()rbinom()等),除了一个:rcauchy()"。

问题

我想知道 R 是如何识别用户提供了 rcauchy() 作为 x 的输入的,在这种情况下,R 会发出警告消息?

这是我没有成功的 R 代码:

TBT = function(x) {

if( x == rcauchy(...) ) { warning("\n\tThis type of distribution is not supported.") }

}

TBT( x = rcauchy(1e4) )

Error in TBT(rcauchy(10000)) : '...' used in an incorrect context

【问题讨论】:

标签: r function random


【解决方案1】:

如果您希望他们在调用您的函数时确实调用随机函数,您可以这样做

TBT <- function(x) {
    xcall <- match.call()$x
    if (class(xcall)=="call" && xcall[[1]]=="rcauchy") { 
        warning("\n\tThis type of distribution is not supported.") 
    }
}
TBT( x = rcauchy(1e4) )

但这不会捕捉到类似的情况

x <- rcauchy(1e4)
TBT( x )

R 无法跟踪 x 变量中的数据来自何处

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2014-07-09
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    相关资源
    最近更新 更多