在 R 中生成总和为 M 的 N 个随机整数 [英] Generate N random integers that sum to M in R

查看:38
本文介绍了在 R 中生成总和为 M 的 N 个随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成 N 个随机正整数,总和为 M.我希望围绕均值为 M/N 且标准偏差较小的相当正态分布选择随机正整数(是否可以将其设置为约束?).

I would like to generate N random positive integers that sum to M. I would like the random positive integers to be selected around a fairly normal distribution whose mean is M/N, with a small standard deviation (is it possible to set this as a constraint?).

最后,您将如何概括生成 N 个随机正数(不仅仅是整数)的答案?

Finally, how would you generalize the answer to generate N random positive numbers (not just integers)?

我发现了其他相关问题,但无法确定如何将他们的答案应用于此上下文:https://stats.stackexchange.com/问题/59096/generate-three-random-numbers-that-sum-to-1-in-r

I found other relevant questions, but couldn't determine how to apply their answers to this context: https://stats.stackexchange.com/questions/59096/generate-three-random-numbers-that-sum-to-1-in-r

生成 3 个总和为 1 的随机数R

R - 整数的随机近似正态分布预定义总数

推荐答案

标准化.

rand_vect <- function(N, M, sd = 1, pos.only = TRUE) {
  vec <- rnorm(N, M/N, sd)
  if (abs(sum(vec)) < 0.01) vec <- vec + 1
  vec <- round(vec / sum(vec) * M)
  deviation <- M - sum(vec)
  for (. in seq_len(abs(deviation))) {
    vec[i] <- vec[i <- sample(N, 1)] + sign(deviation)
  }
  if (pos.only) while (any(vec < 0)) {
    negs <- vec < 0
    pos  <- vec > 0
    vec[negs][i] <- vec[negs][i <- sample(sum(negs), 1)] + 1
    vec[pos][i]  <- vec[pos ][i <- sample(sum(pos ), 1)] - 1
  }
  vec
}

对于连续版本,只需使用:

For a continuous version, simply use:

rand_vect_cont <- function(N, M, sd = 1) {
  vec <- rnorm(N, M/N, sd)
  vec / sum(vec) * M
}

示例

rand_vect(3, 50)
# [1] 17 16 17

rand_vect(10, 10, pos.only = FALSE)
# [1]  0  2  3  2  0  0 -1  2  1  1

rand_vect(10, 5, pos.only = TRUE)
# [1] 0 0 0 0 2 0 0 1 2 0

rand_vect_cont(3, 10)
# [1] 2.832636 3.722558 3.444806

rand_vect(10, -1, pos.only = FALSE)
# [1] -1 -1  1 -2  2  1  1  0 -1 -1

这篇关于在 R 中生成总和为 M 的 N 个随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆