In the more general case, that approach is prone to machine precision error (FAQ 7.31).
Here's a clunky but safer alternative: > set.seed(1234) > testvec <- sample(0:10, 100, replace=TRUE) > mean(testvec) [1] 4.31 > mean(testvec[testvec != 0]) [1] 4.842697 > mean(testvec[!sapply(testvec, function(x)isTRUE(all.equal(x, 0)))]) [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 <anopheles...@gmail.com> wrote: > You can do it by subsetting or indexing > > r<-c(0,0,0,rnorm(10,10,5)) >> mean(r) > [1] 8.052215 >> mean(r[r!=0]) > [1] 10.46788 > > Weidong Gu > > On Tue, Jul 19, 2011 at 4:36 PM, Dimitri Liakhovitski > <dimitri.liakhovit...@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 >> marketfusionanalytics.com >> -- Sarah Goslee http://www.functionaldiversity.org ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.