【问题标题】:Function that returns integer with specific distribution返回具有特定分布的整数的函数
【发布时间】:2014-11-05 03:33:06
【问题描述】:

我正在寻找一个分布,或者更确切地说是一个函数,它返回特定范围内的整数,数字越高概率越小。

假设范围是从 1 到 5。

85% of the time the function should return 1
8% of the time the function should return 2
4% of the time the function should return 3
2% of the time the function should return 4
1% of the time the function should return 5

此外,如果概率符合一个集合分布,比如正态分布或指数分布,那就太好了。

这样的函数会是什么样子?

【问题讨论】:

    标签: r statistics distribution


    【解决方案1】:

    使用

    sample.int(n, size = 1, prob = p) 
    

    你可以在哪里使用类似的东西

    p <- exp(-(1:n))
    

    或使用标准正态分布

    p <- dnorm(1:n)
    

    编辑 对于您的具体示例,请使用

    n <- 5
    p <- c(0.85, 0.08, 0.04, 0.02, 0.01)
    

    【讨论】:

    • 我觉得我最喜欢这个。谢谢!
    • 但这不是你首先想要的,只是“额外地”
    • 这是他首先想要的,只是不完全是他的例子,这只是一个例子......
    【解决方案2】:

    效率不是很高,并假设您可以确保 cumsum 加起来为 1。

    reqProb = c(0.85,0.08,0.04,0.02,0.01)
    nRandom = 100
    # unlist(lapply(runif(nRandom,0,1),function(x) min(which(x<cumsum(reqProb)))))
    unlist(lapply(runif(nRandom,0,1),function(x) which(x<cumsum(reqProb))[1]))
    

    【讨论】:

      【解决方案3】:

      试试:

      nums = 1:5
      prob = c(85,8,4,2,1)
      xx = list()
      for(i in 1:5) xx[[length(xx)+1]] = rep(nums[i], prob[i])
      xx = unlist(xx)
      xx
      
      sample(xx,1)
      [1] 1
      

      sample(xx,1) 将返回给定分布的值。一次获取更多样本:

      sample(xx, 25)
       [1] 1 1 1 1 1 1 1 1 1 1 1 3 1 2 1 1 1 5 1 1 1 1 1 3 1
      

      您可以通过以下方式检查分布:

      table(sample(xx, 100))
      
       1  2  3  4  5 
      85  8  4  2  1 
      > 
      > 
      table(sample(xx, 100, replace=T))
      
       1  2  3  4  5 
      82  8  6  2  2 
      

      【讨论】:

      • 有没有办法避免这种循环?谢谢
      • 为什么循环困扰着您?如果它有效,它是有用的。您的数据是非常大还是花费了太多时间?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2012-11-21
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多