[Rd] sample() fails with double or integer NA input of length one

Martin Maechler maechler at stat.math.ethz.ch
Mon Jul 18 10:41:50 CEST 2016


>>>>> Travis McArthur <travis.d.mcarthur at gmail.com>
>>>>>     on Sat, 16 Jul 2016 14:40:28 -0500 writes:

    > Hi,
    > I have discovered that sample() fails with an uninformative error
    > message when the x argument is a single NA of type double or integer.

    > I can reproduce the problem with the following code:

    > base::sample(NA)
    > # NA is of logical type above
    > base::sample(NA_character_)
    > base::sample(NA_complex_)
    > base::sample(NA_real_)
    > base::sample(NA_integer_)


    > The last two lines throw the following error:
    > Error in if (length(x) == 1L && is.numeric(x) && x >= 1) { :
    > missing value where TRUE/FALSE needed

Good catch,  thank you, Travis!

The error message --- not quite uninformative I would argue ---
actually even suggests a fix -- which I have already committed
to the R sources:

Replace  is.numeric() by  is.finite().

However, that is not good enough: With that change,

   sample(1i)

fails.   So, in a better patch, the line in case 
    
     if (length(x) == 1L && is.numeric(x) && x >= 1) {

could be replaced by

     if (length(x) == 1L && is.numeric(x) && is.finite(x) && x >= 1) {
or   if (length(x) == 1L && is.numeric(x) && !is.na(x)    && x >= 1) {

or does anyone see a nicer / more performant efficient solution?
Martin 

       [............]

    > Best,
    > Travis McArthur



More information about the R-devel mailing list