Skip to content

rdunif unexpected output #211

Closed
Closed

Description

@1danjordan

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?

Activity

  1. hadley commented on Aug 15, 2016

    @hadley
    Member

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

  2. 1danjordan commented on Sep 25, 2016

    @1danjordan
    ContributorAuthor

    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.

  3. added
    bugan unexpected problem or unintended behavior
    on Mar 3, 2017
  4. added a commit that references this issue on Jan 10, 2025
    8f435c3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions