[R] calculating mean excluding zeros
gunter.berton at gene.com
Tue Jul 19 23:36:50 CEST 2011
Sarah et. al:
On Tue, Jul 19, 2011 at 1:56 PM, Sarah Goslee <sarah.goslee 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:
Perhaps ?zapsmall .
However, I would agree with your sentiments that it may depend on
context. Finite precision can be a tricky thing.
>> testvec <- sample(0:10, 100, replace=TRUE)
>  4.31
>> mean(testvec[testvec != 0])
>  4.842697
>> mean(testvec[!sapply(testvec, function(x)isTRUE(all.equal(x, 0)))])
>  4.842697
> (Is there an elementwise equivalent to all.equal() that I'm missing?)
> On Tue, Jul 19, 2011 at 4:48 PM, Weidong Gu <anopheles123 at gmail.com> wrote:
>> You can do it by subsetting or indexing
>>  8.052215
>>  10.46788
>> Weidong Gu
>> On Tue, Jul 19, 2011 at 4:36 PM, Dimitri Liakhovitski
>> <dimitri.liakhovitski at gmail.com> wrote:
>>> 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!
>>> Dimitri Liakhovitski
> Sarah Goslee
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
"Men by nature long to get on to the ultimate truths, and will often
be impatient with elementary studies or fight shy of them. If it were
possible to reach the ultimate truths without the elementary studies
usually prefixed to them, these would not be preparatory studies but
-- Maimonides (1135-1204)
Genentech Nonclinical Biostatistics
More information about the R-help