R 为什么在 period.apply 处使用函数 "mean with condition" 时结果为 False

R Why False results when using the function "mean with condition" at period.apply

我想计算每年高于常量的值的平均值。

我用这个例子来解释:

library(xts) 
library(PerformanceAnalytics)

data(edhec) 
head(edhec)

edhec_4yr <- edhec["1997/2001"] 
ep <- endpoints(edhec_4yr, "years")

# mean 
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2,mean))

# Length with condition Ok

period.apply(edhec_4yr, 
             INDEX = ep, 
             function(x) apply(x,
                               2, 
                               function(y) length(which(y>0.002))))


# But Mean with condition : the results are false, 
#they do not correspond to the true results. Why!!!

period.apply(edhec_4yr, 
             INDEX = ep, 
             function(x) apply(x,
                               2, 
                               function(y) mean(which(y>0.002))))

View(edhec_4yr)

提前感谢您解释为什么我在最后一步没有找到好的结果!

如果您创建简单的示例,它将帮助您调试问题。举个简单的例子说明问题:

set.seed(21)
(x <- rnorm(10))
# [1]  0.793013171  0.522251264  1.746222241 -1.271336123  2.197389533
# [6]  0.433130777 -1.570199630 -0.934905667  0.063493345 -0.002393336
x > 0
# [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE
which(x > 0)
# [1] 1 2 3 5 6 9
mean(which(x > 0))
# [1] 4.333333

所以你需要这样的东西:

apply.yearly(edhec_4yr, function(x) apply(x, 2, function(y) mean(y[y > 0.002])))