gpt4 book ai didi

r - 以概率选择特定数字

转载 作者:行者123 更新时间:2023-12-02 17:29:12 26 4
gpt4 key购买 nike

如何以特定概率p选择一个数字?

假设我们必须在 {0, 1} 之间进行选择,而 p 代表选择 1 的概率。

因此,当 p=0.8 时,我们选择 1 为 80%,0 为 20%。

R 中有一个简单的解决方案吗?

最佳答案

看看sample功能。

> set.seed(1)
> sample(c(0,1), size=10, replace=TRUE, prob=c(0.2,0.8))
[1] 1 1 1 0 1 0 0 1 1 1

从帮助文件中您可以阅读:

sample takes a sample of the specified size from the elements of x using either with or without replacement.

并且 sample 中的参数 prob 充当...

A vector of probability weights for obtaining the elements of the vector being sampled.

关于r - 以概率选择特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22639816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com