我想计算每年高于常数的值的平均值。
我用这个例子解释:
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)
先谢谢你解释为什么我在最后一步找不到好结果!
答案 0 :(得分:2)
如果您创建简单示例,它可以帮助您调试问题。一个简单的例子可以解决问题:
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])))