2

I want to generate some Weibull random numbers in a given interval. For example 20 random numbers from the Weibull distribution with shape 2 and scale 30 in the interval (0, 10).

rweibull function in R produce random numbers from a Weibull distribution with given shape and scale values. Can someone please suggest a method? Thank you in advance.

Nayomi
  • 85
  • 5
  • Check this out: http://stats.stackexchange.com/questions/88773/getting-rweibull-to-output-n-observations-in-1-52-given-specific-shape-scale – chinsoon12 Apr 21 '16 at 05:42

2 Answers2

3

Use the distr package. It allows to do this kind of stuff very easily.

require(distr)
#we create the distribution
d<-Truncate(Weibull(shape=2,scale=30),lower=0,upper=10)
#The d object has four slots: d,r,p,q that correspond to the [drpq] prefix of standard R distributions
#This extracts 10 random numbers
d@r(10)
#get an histogram
hist(d@r(10000))
nicola
  • 24,005
  • 3
  • 35
  • 56
1

Using base R you can generate random numbers, filter which drop into target interval and generate some more if their quantity appears to be less than you need.

rweibull_interval <- function(n, shape, scale = 1, min = 0, max = 10) {
  weib_rnd <- rweibull(10*n, shape, scale)
  weib_rnd <- weib_rnd[weib_rnd > min & weib_rnd < max]
  if (length(weib_rnd) < n) 
    return(c(weib_rnd, rweibull_interval(n - length(weib_rnd), shape, scale, min, max))) else 
      return(weib_rnd[1:n])
}

set.seed(1)
rweibull_interval(20, 2, 30, 0, 10)

 [1] 9.308806 9.820195 7.156999 2.704469 7.795618 9.057581 6.013369 2.570710 8.430086 4.658973
[11] 2.715765 8.164236 3.676312 9.987181 9.969484 9.578524 7.220014 8.241863 5.951382 6.934886
inscaven
  • 2,514
  • 19
  • 29