【问题标题】:R: draw from a vector using custom probability functionR:使用自定义概率函数从向量中绘制
【发布时间】:2016-02-12 22:58:31
【问题描述】:

如果以前有人问过这个问题,请原谅我(我觉得它必须有,但找不到我正在寻找的确切内容)。

我是否可以使用指定元素不同机会的概率函数来绘制整数向量(从 1 到例如 10)中的一个元素。如果我想要相等的概率,我使用runif() 来获得 1 到 10 之间的数字:

ceiling(runif(1,1,10))

我如何类似地从例如得到 1 到 10 之间的数字的指数分布(使得 1 比 10 更可能),或逻辑概率函数(如果我想要一个从 1 到 10 的 sigmoid 增加概率)。

我能想到的唯一“解决方案”是首先从 say sigmoid 分布中提取 e6 数字,然后将 min 和 max 缩放为 1 和 10 - 但这看起来很笨拙。

更新:

这个尴尬的解决方案(我觉得它不是很“正确”)会这样

#Draw enough from a distribution, here exponential
x <- rexp(1e3)

#Scale probs to e.g. 1-10
scaler <- function(vector, min, max){
 (((vector - min(vector)) * (max - min))/(max(vector) - min(vector))) + min  
} 

x_scale <- scaler(x,1,10)

#And sample once (and round it)
round(sample(x_scale,1))

周围没有更好的解决方案吗?

【问题讨论】:

  • 我觉得你需要看看sample()。你的代码相当于sample(1:10, 1),可以用prob=参数指定概率
  • 是的,但是你怎么能在那里指定逻辑概率呢?

标签: r distribution sample


【解决方案1】:

我相信 sample() 是您正在寻找的,正如 @HubertL 在 cmets 中提到的那样。您可以指定一个递增函数(例如logit())并将您要从v 采样的向量作为输入传递。然后,您可以将该函数的输出用作概率向量p。请参阅下面的代码。

logit <- function(x) {
  return(exp(x)/(exp(x)+1))
}

v <- c(seq(1,10,1))
p <- logit(seq(1,10,1))

sample(v, 1, prob = p, replace = TRUE)

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2012-12-21
    • 2019-07-19
    相关资源
    最近更新 更多