Reputation: 1508
The objective of my function is to calculated a truncated mean, i.e., you give a sample, and then compute the mean for all the values between certain quantiles.
To do that, I've written
meank<-function(x,k){
xt<-quantile(x,c(k,1-k));
mean(x[x>xt[1] & x < xt[2] ])
}
When doing meank(rnorm(100),0.4)
, it returns NaN
. Why is that?
Any help would be appreciated.
Upvotes: 0
Views: 1929
Reputation: 3335
In the implementation of meank
you cancel all values outside of [k, 1-k]
"percent" of range, thus when no value is left in, the subsequent mean
has to yield NaN
.
Reproducible test:
> meank(c(1, 2, 2),0.4)
[1] NaN
Details step wise evaluation:
> quantile(c(1, 2, 2),c(0.4,1-0.4))
40% 60%
1.8 2.0
and:
> xt <- quantile(c(1, 2, 2),c(0.4,1-0.4))
> mean(c(1, 2, 2)[c(1, 2, 2)>xt[1] & c(1, 2, 2) < xt[2] ])
[1] NaN
Upvotes: 1