From ripley at stats.ox.ac.uk  Sat Apr  1 07:14:37 2017
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Sat, 1 Apr 2017 06:14:37 +0100
Subject: [Rd] mean(x) != mean(rev(x)) different with x <- c(NA,
 NaN) for some builds
In-Reply-To: <CAFDcVCST6wRDGeMyzruL4Bq5JsTy2XH5HxwKMba-k=NqWAdewQ@mail.gmail.com>
References: <CAFDcVCST6wRDGeMyzruL4Bq5JsTy2XH5HxwKMba-k=NqWAdewQ@mail.gmail.com>
Message-ID: <8b7a61f1-536f-4646-90b7-fde714ad6116@stats.ox.ac.uk>

 From ?NA

      Numerical computations using ?NA? will normally result in ?NA?: a
      possible exception is where ?NaN? is also involved, in which case
      either might result.

and ?NaN

      Computations involving ?NaN? will return ?NaN? or perhaps ?NA?:
      which of those two is not guaranteed and may depend on the R
      platform (since compilers may re-order computations).

fortunes::fortune(14) applies (yet again).

On 01/04/2017 04:50, Henrik Bengtsson wrote:
> In R 3.3.3, I observe the following on Ubuntu 16.04 (when building
> from source as well as for the sudo apt r-base build):
>
>> x <- c(NA, NaN)
>> mean(x)
> [1] NA
>> mean(rev(x))
> [1] NaN
>
>> rowMeans(matrix(x, nrow = 1, ncol = 2))
> [1] NA
>> rowMeans(matrix(rev(x), nrow = 1, ncol = 2))
> [1] NaN
>
>> .rowMeans(x, m = 1, n = 2)
> [1] NA
>> .rowMeans(rev(x), m = 1, n = 2)
> [1] NaN
>
>> .rowSums(x, m = 1, n = 2)
> [1] NA
>> .rowSums(rev(x), m = 1, n = 2)
> [1] NaN
>
>> rowSums(matrix(x, nrow = 1, ncol = 2))
> [1] NA
>> rowSums(matrix(rev(x), nrow = 1, ncol = 2))
> [1] NaN
>
> I'd expect NA to trump NaN in all cases (with na.rm = FALSE).  sum()
> does not have this problem and returns NA in both cases (*).
>
> For the same R version build from source on RHEL 6.6 system
> (completely different architecture), I get the expected result (= NA)
> for all of the above cases, e.g.
>
>> x <- c(NA, NaN)
>> mean(x)
> [1] NA
>> mean(rev(x))
> [1] NA
> [...]
>
> Before going insane trying to troubleshoot this, I have a vague memory
> that this, or something related to this, has been discussed
> previously, but I cannot locate it.
>
> Is the above a bug in R, a FAQ, a build error, overzealous compiler
> optimization, and / or ...?
>
> Thanks,
>
> Henrik


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Emeritus Professor of Applied Statistics, University of Oxford



[Rd] mean(x) != mean(rev(x)) different with x <- c(NA, NaN) for some builds
Prof Brian Ripley