简体   繁体   中英

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]. What should I do?

scores <- rnorm(1000, 120, 20)

Instead of a while loop, you can use a recursion approach:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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