简体   繁体   English

在 R 中的特定范围内生成正态分布

[英]Generate a normal distribution within certain limits in R

I would like to generate a normal distribution with a mean of 120 and a standard deviation of 20. But I need to limit the values to [0, 150].我想生成均值为 120、标准差为 20 的正态分布。但我需要将值限制为 [0, 150]。 What should I do?我该怎么办?

scores <- rnorm(1000, 120, 20)

Instead of a while loop, you can use a recursion approach:您可以使用递归方法代替 while 循环:

foo = function(n, m, v, up, down)
{
    if(n==0) return(numeric(n))
    vec = Filter(function(x) x>=down & x<=up, rnorm(n, m, v))
    c(vec, foo(n-length(vec), m, v, up, down))
}

result = foo(1000, 120, 20, 150, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM