2

I have code that generates a random value from an exponential distribution defined as the following, i.e. with a rate of 4874, and assigns it to a variable tau.

tau <- rexp(n=1,rate=4874) 

Sometimes it produces a NaN value. rexp() doesn't have an na.rm option, so I used this while loop to re-assign a random deviate if the value produced is NaN.

while (is.na(tau)) {
   tau <- rexp(n=1,rate=4874)
}

If I run it and a NaN value is produced and assigned initially to tau, and the while loop is entered, it seems unable to stop generating more NaN values, i.e. I have an infinite loop (the re-assignment line in the while loop just re-assigns a NaN value each time).

Any ideas? Unfortunately the rexp() function doesn't allow you to include an na.rm = TRUE argument. I've been unable to find anything about dealing with NaN values in R when they are produced by random sampling of a distribution.

ytsejam
  • 3,291
  • 7
  • 39
  • 69
  • 2
    Can you provide us with reproducible example of your error with seed? `rexp` shouldn't produce `NaN` with rate >0 . – Andrey Kolyadin Nov 07 '17 at 14:01
  • I just ran `sum(is.na(rexp(n=1e9,rate=4874)))`, selecting one billion values from `rexp`, and received 0 NA values. By the way, it is much more efficient to generate the set of random values in one go and store them, rather than select one value at a time. The values extracted will be identical as long as there is no random selection or resetting of the seed in between. – lmo Nov 07 '17 at 14:02
  • Regarding the efficiency of selecting multiple values at once, see my answer [here](https://stackoverflow.com/questions/21991130/simulating-a-random-walk/45900693) as an example. Compare the timing of the first function to all subsequent functions. – lmo Nov 07 '17 at 14:08

0 Answers0