When `rdunif` has an upper bound `b` less than the lower bound `a`, it outputs `b` `n` times. ``` r rdunif(10, -5, 5) # [1] -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 ``` A solution is to pass a vector of integers into `sample` ``` r rdunif2 <- function(n, b, a = 1) { vec <- a:b sample(vec, n, replace = TRUE) } rdunif2(10, -5, 5) # [1] -2 3 2 -4 -4 3 3 2 4 -5 ``` I've benchmarked them and `rdunif2` is slightly slower. ``` r microbenchmark( rdunif(1000, 50), rdunif2(1000, 50) ) # Unit: microseconds # expr min lq mean median uq max neval cld # rdunif(1000, 50) 23.179 29.8285 35.06438 31.919 34.5780 125.010 100 a # rdunif2(1000, 50) 30.019 36.0980 42.52322 37.997 39.8975 139.069 100 b ``` But maybe acceptably so?
Activity
hadley commentedon Aug 15, 2016
Passing a vector doesn't work in general because
sample(10:10)probably doesn't do what you expect.1danjordan commentedon Sep 25, 2016
Ah I missed that! You don't need my suggestion, but I then I suppose this would work
Can make a pull req if you want. Apologies if I'm distracting you from the important stuff.
rdunif checks its inputs for validity