Search code examples
rnormal-distribution

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)

Solution

  • 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)