New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rdunif unexpected output #211

Closed
dandermotj opened this Issue Jul 1, 2016 · 2 comments

Comments

Projects
None yet
2 participants
@dandermotj
Contributor

dandermotj commented Jul 1, 2016

When rdunif has an upper bound b less than the lower bound a, it outputs b n times.

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

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.

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?

@dandermotj dandermotj referenced this issue Jul 1, 2016

Closed

Rdunif #212

@hadley

This comment has been minimized.

Member

hadley commented Aug 15, 2016

Passing a vector doesn't work in general because sample(10:10) probably doesn't do what you expect.

@dandermotj

This comment has been minimized.

Contributor

dandermotj commented Sep 25, 2016

Ah I missed that! You don't need my suggestion, but I then I suppose this would work

rdunif2 <- function(n, b, a = 1) {
  if(a == b) return(rep(a, n))
  vec <- a:b
  sample(vec, n, replace = TRUE)
}

Can make a pull req if you want. Apologies if I'm distracting you from the important stuff.

@hadley hadley added the bug label Mar 3, 2017

@hadley hadley closed this in 8f435c3 Mar 4, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment