【问题标题】:"sample" and "rbinom" functions in RR中的“样本”和“rbinom”函数
【发布时间】:2015-06-22 00:58:05
【问题描述】:

我猜之前有人问过,但是我对R中的“sample”和“rbinom”函数还是有点生疏,想问以下两个简单的问题:

a) 假设我们有:

        rbinom(n = 5, size = 1, prob = c(0.9,0.2,0.3))

所以 "n" = 5 但 "prob" 只表示其中三个。 R 为这两个 n 分配了什么值?

b) 假设我们有:

        sample(x = 1:3, size = 1, prob = c(.5,0.2,0.9))

根据 R-help (?sample):

     The optional prob argument can be used to give a vector of weights    
     for obtaining the elements of the vector being sampled.  
     They need not sum to one, but they should be non-negative and not all zero.

问题是:为什么“概率”不需要总和为一?

任何答案将不胜感激:谢谢!

【问题讨论】:

  • 为什么它们的总和必须为 1? c(3,1) 的权重与 c(0.75,0.25) 一样有效。而且我收集 R 只会根据rbinom(n = 5, size = 1, prob = c(1,0)) 将权重回收到n 的长度,其中权重将为1,0,1,0,1
  • R 内部会在必要时回收并在使用前执行prob=prob/sum(prob)

标签: r sample simulate


【解决方案1】:

来自documentation for rbinom

n 以外的数值参数被回收到结果的长度。

这意味着在您的示例中,您传入的 prob 向量将被回收,直到达到所需的长度(大概为 5)。所以将使用的向量是:

c(0.9, 0.2, 0.3, 0.9, 0.2)

至于sample 函数,正如@thelatemail 指出的那样,概率的总和不必为1。看来prob 向量在内部被归一化为1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 2021-05-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2018-11-10
    • 2020-04-02
    • 2012-10-24
    相关资源
    最近更新 更多