Re: [Rd] NAs and weighted.mean

From: Martin Maechler <>
Date: Thu, 24 Jun 2010 10:18:32 +0200

>>>>> "RobMcG" == McGehee, Robert <>
>>>>> on Wed, 23 Jun 2010 19:38:44 -0400 writes:

    RobMcG> R-developers,
    RobMcG> In version R 2.11.0, weighted.mean was changed such that:     >> weighted.mean(NA, na.rm=TRUE)
    RobMcG> [1] 0

    RobMcG> rather than NaN as in previous versions of R.

which versions?
Even in 2.10.0 it gave 0.

    RobMcG> rather than NaN as in previous versions of R. I see a note in the NEWS
    RobMcG> file indicates that weighted.mean was changed "so an infinite value with
    RobMcG> zero weight does not force an NaN result." 

    RobMcG> In case the side effect of returning 0 rather than NaN in this case was
    RobMcG> unintentional, I'd like to propose that this case be reverted such that
    RobMcG> weighted.mean(NA, na.rm=TRUE) returns a NaN to be consistent with the     RobMcG> mean function.

I tend to agree with you.
Note that also, for such functions FUN

        FUN(NA, na.rm=TRUE)
identical to
        FUN( numeric(0) )

and for "mean-like" functions I agree it should return NaN (or NA, perhaps).

    RobMcG>  Otherwise perhaps a note should be added in the
    RobMcG>  documentation explaining this inconsistent
    RobMcG>  behavior.

    RobMcG> I believe this patch should fix the problem while preserving the
    RobMcG> behavior in the NEWS file:
    RobMcG> -    w <- w/sum(w)

    RobMcG> - sum((x*w)[w != 0])
    RobMcG> + sum((x*w)[w != 0])/sum(w)d

Yes, it seems so, and I will probably commit it, for R-devel at first, and R-patched later after a while.

Martin Maechler, ETH Zurich

    RobMcG> Here's the full note from the NEWS file.
    RobMcG> o	The default method of weighted.mean(x, w) coerces 'w' to be
    RobMcG> numeric (aka double); previously only integer weights were
    RobMcG> coerced.  Zero weights are handled specially so an infinite
    RobMcG> value with zero weight does not force an NaN result.

    RobMcG> Thanks, Robert

     ............ mailing list Received on Thu 24 Jun 2010 - 08:25:27 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 24 Jun 2010 - 17:01:17 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive