[R] Interval for rnorm command?

peter dalgaard pdalgd at gmail.com
Mon Jun 9 11:39:39 CEST 2014


It's usually easier to use the inversion method on a truncated uniform:

fun3 <- function(n, low, high, mean, sd) 
	qnorm(runif(n, 
	  pnorm(low, mean, sd), 
	  pnorm(high, mean, sd)), mean, sd)
res3 <- fun3(100,-3.7, 3.7, 1,2)
hist(res3)


On 08 Jun 2014, at 08:34 , arun <smartpink111 at yahoo.com> wrote:

> Hi,
> 
> You may try:
> fun1 <- function(len, low, high, mean, sd) {
>     x <- rnorm(len * 2, mean, sd)
>     x <- x[x < high & x > low]
>     x[1:len]
> }
> 
> ##slow
> fun2 <- function(len, low, high, mean, sd) {
>     i <- 1
>     while (i < len) {
>         x <- rnorm(1, mean, sd)
>         if (x < high & x > low) {
>             i <- i + 1
>         }
>     }
>     x
> }
> 
> 
> set.seed(42)
>  res1 <- fun1(100,-3.7, 3.7, 1,2)
>  set.seed(42)
>  res2 <- fun1(100,-3.7, 3.7, 1,2)
> 
> 
> identical(res1,res2)
> #[1] TRUE
> range(res1)
> #[1] -2.562617  3.640227
> A.K.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> On Saturday, June 7, 2014 10:28 PM, zagreus <a0906257 at unet.univie.ac.at> wrote:
> Hello everyone!
> 
> I want to create a data vector using the "rnorm" command. Let's say /x <-
> rnorm(100, 1, 2)/. This gives me 100 values from the specific normal
> distribution. However, I want to generate a variable that has a certain
> range of values, e.g. values can't exceed the interval /[-3.7; 3.7]/. How
> can I implement such an interval? 
> 
> Thanks for your help and sorry if this is totally trivial, I am new to R. 
> 
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Interval-for-rnorm-command-tp4691856.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list