From maechler at stat.math.ethz.ch  Thu Jun 24 10:18:32 2010
From: maechler at stat.math.ethz.ch (Martin Maechler)
Date: Thu, 24 Jun 2010 10:18:32 +0200
Subject: [Rd] NAs and weighted.mean
In-Reply-To: <EEBC169715EB8C438D3C9283AF0F201C086C9061@MSGBOSCLM2WIN.DMN1.FMR.COM>
References: <EEBC169715EB8C438D3C9283AF0F201C086C9061@MSGBOSCLM2WIN.DMN1.FMR.COM>
Message-ID: <19491.5336.6203.306663@stat.math.ethz.ch>

>>>>> "RobMcG" == McGehee, Robert <Robert.McGehee at geodecapital.com>
>>>>>     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

     ............



[Rd] NAs and weighted.mean
Martin Maechler