Skip to content

calculating mean excluding zeros

6 messages · Dimitri Liakhovitski, Weidong Gu, Bert Gunter +1 more

#
Sorry if it's been discussed before - don't seem to find it.
I'd like to calculate a mean while ignoring zeros.
"mean" doesn't seem to have an option for that.
Any other function/package that could do it?

Thanks for a pointer!
#
You can do it by subsetting or indexing

 r<-c(0,0,0,rnorm(10,10,5))
[1] 8.052215
[1] 10.46788

Weidong Gu

On Tue, Jul 19, 2011 at 4:36 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
#
In the more general case, that approach is prone to machine precision
error (FAQ 7.31).

Here's a clunky but safer alternative:
[1] 4.31
[1] 4.842697
[1] 4.842697
(Is there an elementwise equivalent to all.equal() that I'm missing?)

Sarah
On Tue, Jul 19, 2011 at 4:48 PM, Weidong Gu <anopheles123 at gmail.com> wrote:

  
    
#
Thanks a lot, Sarah.
I assume, if the values against which I am comparing are REALLY zero
("0") - then even the first one (mean(testvec[testvec != 0])) should
work, right?
Dimitri
On Tue, Jul 19, 2011 at 4:56 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:

  
    
#
Sarah et. al:
On Tue, Jul 19, 2011 at 1:56 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
Perhaps ?zapsmall  .

However, I would agree with your sentiments that it may depend on
context. Finite precision can be a tricky thing.

-- Bert

  
    
#
On Tue, Jul 19, 2011 at 5:20 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
Well, yes. But what's "really" zero?
[1] FALSE
[1] TRUE

"0" is a string, and string comparison is a different issue, not
subject to machine precision.

Sarah