R:使用自定义概率函数从向量中绘制
R: draw from a vector using custom probability function
如果以前有人问过,请见谅(我觉得一定有,但找不到我要找的东西)。
我可以使用指定元素不同概率的概率函数绘制整数向量(从 1 到 10)的一个元素吗?如果我想要相等的概率,我使用 runif()
来获得 1 到 10 之间的数字:
ceiling(runif(1,1,10))
我如何类似地从例如指数分布以获得 1 到 10 之间的数字(这样 1 比 10 更有可能),或逻辑概率函数(如果我想要一个 sigmoid 增加概率从 1 到 10)。
我唯一能想出的 "solution" 是首先从 say sigmoid 分布中提取 e6 数字,然后将最小值和最大值缩放到 1 和 10 - 但这看起来很笨拙。
更新:
这个尴尬的解决方案(我觉得不是很"correct")会像这样
#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()
就是您要找的,正如@HubertL 在评论中提到的那样。您可以指定递增函数(例如 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)
如果以前有人问过,请见谅(我觉得一定有,但找不到我要找的东西)。
我可以使用指定元素不同概率的概率函数绘制整数向量(从 1 到 10)的一个元素吗?如果我想要相等的概率,我使用 runif()
来获得 1 到 10 之间的数字:
ceiling(runif(1,1,10))
我如何类似地从例如指数分布以获得 1 到 10 之间的数字(这样 1 比 10 更有可能),或逻辑概率函数(如果我想要一个 sigmoid 增加概率从 1 到 10)。
我唯一能想出的 "solution" 是首先从 say sigmoid 分布中提取 e6 数字,然后将最小值和最大值缩放到 1 和 10 - 但这看起来很笨拙。
更新:
这个尴尬的解决方案(我觉得不是很"correct")会像这样
#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()
就是您要找的,正如@HubertL 在评论中提到的那样。您可以指定递增函数(例如 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)