[R] Cannot calculate mean() for double vector

William Dunlap wdunlap at tibco.com
Fri Oct 16 20:15:06 CEST 2009

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Reuben Bellika
> Sent: Friday, October 16, 2009 11:02 AM
> To: r-help at r-project.org
> Subject: Re: [R] Cannot calculate mean() for double vector
> OK. It looks like I just have several NA values at the start 
> of my array:
> > which (is.na(x_ema))
> [1] 1 2 3 4 5 6 7 8 9
> That make sense, because the moving average is not defined for those
> positions. I'll just have to set those values to zero:
> > x_ema = replace(x_ema, which(is.na(x_ema)), 0)

By the way, you can save some typing and maybe
increase your understanding of R's semantics by replacing
that line with
    x_ema[is.na(x_ema)] <- 0

When subscripting by a logical variable, read the '[' as 'such that':
    "Values in x_ema such that x_ema is NA are changed to zero".
which() is never needed when subscripting.

replace() is also a waste of typing and memory if you use the same
variable on the left side of the assignment and as the first argument
to replace(). 

I'll leave it to others to comment on the statistical issues.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> > which (is.na(x_ema))
> integer(0)
> The mean() call works now and I can get on with my work. I'll have to
> remember to condition the data like this in the future.
> Thanks for the help!
> Reuben Bellika
> ______________________________________________
> 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.

More information about the R-help mailing list