Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting upper and lower limits in rnorm

Tags:

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 = 25.09)

Upper limit needs to be 340, and the lower limit 0

I am asking this question because I am rewriting an SAS-code into an R-code. I have never used SAS. I am trying to rewrite the following piece of code:

sim_sample(simtot=100000,seed=10004,lbound=0,ubound=340,round_y=0.01,round_m=0.01,round_sd=0.01,n=15,m=39.74,sd=25.11,mk=4)
like image 870
Jolanda Kossakowski Avatar asked Oct 13 '13 08:10

Jolanda Kossakowski


People also ask

What does Rnorm mean in R?

rnorm is the R function that simulates random variates having a specified normal distribution. As with pnorm , qnorm , and dnorm , optional arguments specify the mean and standard deviation of the distribution.

How do you generate a normal random variable in R?

If we want to generate standard normal random numbers then rnorm function of R can be used but need to pass the mean = 0 and standard deviation = 1 inside this function.

Why do we use Rnorm?

If you want to generate a vector of normally distributed random numbers, rnorm is the function you should use. The first argument n is the number of numbers you want to generate, followed by the standard mean and sd arguments.

What does Rnorm do in R studio?

The rnorm() function in R generates a random number using a normal(bell curve) distribution. Thus, the rnorm() function simulates random variates having a specified normal distribution.


2 Answers

The rtruncnorm() function will return the results you need.

  library(truncnorm)
  rtruncnorm(n=10, a=0, b=340, mean=39.4, sd=25.09)
like image 86
charlie Avatar answered Oct 07 '22 20:10

charlie


You can make your own truncated normal sampler that doesn't require you to throw out observations quite simply

rtnorm <- function(n, mean, sd, a = -Inf, b = Inf){
    qnorm(runif(n, pnorm(a, mean, sd), pnorm(b, mean, sd)), mean, sd)
}
like image 26
Dason Avatar answered Oct 07 '22 20:10

Dason