[R] How to pick out several infinite values when calculating means?

Joshua Wiley jwiley.psych at gmail.com
Tue Nov 16 22:33:39 CET 2010


Hi Lei,

Here is one option relying on is.finite()


## Messy data for means
dat <- data.frame(values = c(rnorm(7), 1:7, c(1, 2, 3, NA, 4, 5, 6),
  c(1, 2, Inf, 4, 100, -Inf, NaN)), group = rep(letters[1:4], 7))

## use is.finite() to select for only finite numbers
tapply(dat$values, dat$group, function(x) {mean(x[is.finite(x)])})

if you wanted to just exclude infinite values, but keep NAs (I don't
know why you would but...), you could use !is.infinite() to get values
that are not infinite.

Cheers,

Josh

On Tue, Nov 16, 2010 at 1:24 PM, Lei  Zhou <Lei.Zhou at agrsci.dk> wrote:
> Dear r-help,
>
> I want to use tapply to calculate means for a variable. But there were several infinite values in the observations.
>
> How can I calculate means not considering  these infinite values?
>
> Thanks in advance.
>
>
> Regards,
> Lei
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list