setting upper and lower limits in rnorm

前端 未结 5 1336
自闭症患者
自闭症患者 2020-12-03 14:04

I am simulating data using rnorm, but I need to set an upper and lower limit, does anyone know how to do this?

code:

rnorm(n = 10, mean = 39.74, sd =         


        
5条回答
  •  [愿得一人]
    2020-12-03 14:54

    This is the function that I wrote to achieve the same purpose. It normalizes the result from the rnorm function and then adjusts it to fit the range.

    NOTE: The standard deviation and mean (if specified) get altered during the normalization process.

    #' Creates a random normal distribution within the specified bounds.
    #' 
    #' WARNING: This function does not preserve the standard deviation or mean.
    #' @param n The number of values to be generated
    #' @param mean The mean of the distribution
    #' @param sd The standard deviation of the distribution
    #' @param lower The lower limit of the distribution
    #' @param upper The upper limit of the distribution
    rtnorm <- function(n, mean=NA, sd=1, lower=-1, upper=1){
      mean = ifelse(is.na(mean)|| mean < lower || mean > upper,
                    mean(c(lower, upper)), mean)
      data <- rnorm(n, mean=m, sd=sd) # data
    
      if (!is.na(lower) && !is.na(upper)){ # adjust data to specified range
        drange <- range(data)           # data range
        irange <- range(lower, upper)   # input range
        data <- (data - drange[1])/(drange[2] - drange[1]) # normalize data (make it 0 to 1)
        data <- (data * (irange[2] - irange[1]))+irange[1] # adjust to specified range
      }
      return(data)
    }
    

提交回复
热议问题