简体   繁体   English

如何使概率分布成为R中函数的参数?

[英]How to make probability distribution an argument of a function in R?

I have a function f in R which involves drawing many samples of the form我在 R 中有一个函数 f,它涉及绘制许多形式的样本

sample <- rnorm(k,0,1) 

where k is some integer.其中 k 是某个整数。 I would like to make as an argument of this function f the type of distribution, so I can quickly generate samples of the form我想将分布类型作为此函数的参数,以便我可以快速生成以下形式的样本

sample <- runif(k,0,1)

or other probability distributions for instance.或其他概率分布,例如。 In other words, I want to be able to write f(k,uniform) and generate the second type of sampling, and f(k,normal) for the first.换句话说,我希望能够编写 f(k,uniform) 并生成第二种采样,而 f(k,normal) 用于第一种。

Is this possible?这可能吗? I'd like to avoid having to repeatedly modify the code within my functions each time I change distributions.我想避免每次更改分布时都必须重复修改函数中的代码。

Don't know how useful this is, but:不知道这有多大用处,但是:

f <- function(k,g){g(k)}

Used like f(100,runif) or f(100,rnorm)f(100,runif)f(100,rnorm)

As a variation:作为变体:

f <- function(k,g,...){g(k,...)}

which would also allow things like f(100,rnorm,10,2)这也将允许像f(100,rnorm,10,2)

Here's a promising, in-development implementation of what you're looking for.这是您正在寻找的有前途的开发中的实现。 The distributions package is available on Github and on CRAN. distributions包在 Github和 CRAN 上可用

Here's an example usage:这是一个示例用法:

library(distributions)

X <- Bernoulli(0.1)

random(X, 10)
#>  [1] 0 0 0 0 0 0 0 0 1 0
pdf(X, 1)
#> [1] 0.1

cdf(X, 0)
#> [1] 0.9
quantile(X, 0.5)
#> [1] 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM