R如何在period.apply处使用函数"Length with condition"?
R How to use function "Length with condition" at period.apply?
我想量化整个时间序列中每年高于常数值(例如 > 0.005)的天数。
我用这个例子来说明我的问题:
library(xts)
library(PerformanceAnalytics)
data(edhec)
head(edhec)
edhec_4yr <- edhec["1997/2001"]
ep <- endpoints(edhec_4yr, "months")
# mean
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2,mean))
# Length
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2, length))
# Length with condition (error!!)
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2,
length(which(x>0.005))))
要计算年平均值没问题,我使用函数"Length"来估算年数它起作用了,但是如果我添加一个条件
length (which (x> 0.005)))) 它不起作用!
你有什么想法可以改进带条件的长度函数 period.apply!
提前感谢您的帮助
您必须提供一个函数作为 apply
的第三个参数,例如像这样:
period.apply(edhec_4yr,
INDEX = ep,
function(x) apply(x,
2,
function(y) length(which(y>0.005))))
我想量化整个时间序列中每年高于常数值(例如 > 0.005)的天数。
我用这个例子来说明我的问题:
library(xts)
library(PerformanceAnalytics)
data(edhec)
head(edhec)
edhec_4yr <- edhec["1997/2001"]
ep <- endpoints(edhec_4yr, "months")
# mean
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2,mean))
# Length
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2, length))
# Length with condition (error!!)
period.apply(edhec_4yr, INDEX = ep, function(x) apply(x,2,
length(which(x>0.005))))
要计算年平均值没问题,我使用函数"Length"来估算年数它起作用了,但是如果我添加一个条件 length (which (x> 0.005)))) 它不起作用!
你有什么想法可以改进带条件的长度函数 period.apply!
提前感谢您的帮助
您必须提供一个函数作为 apply
的第三个参数,例如像这样:
period.apply(edhec_4yr,
INDEX = ep,
function(x) apply(x,
2,
function(y) length(which(y>0.005))))