[R] rollapply() produces NAs
Sepp
sepp9000 at yahoo.de
Sun May 28 17:57:03 CEST 2017
This is the function in plain text because it looked messy before:
VaRfun <- function(x, lambda = 0.94) {
#create data.frame and order returns such that the lates return is the first
df <- data.frame(weight = c(1:length(x)), return = rev(x))
K <- nrow(df)
constant <- (1-lambda)/(1-lambda^(K))
#assign weights to the returns
for(i in 1:nrow(df)) {
df$weight[i] <- lambda^(i-1) * constant
}
#order returns in an ascending order
df <- df[order(df$return),]
#add the cumulative sum of the weights
df$cum.weight <- cumsum(df$weight)
#calculate value at risk
VaR <- -tail((df$return[df$cum.weight <= .05]), 1)
signif(VaR, digits = 3)
}
It works for a single vector of returns but if I try to use it with rollapply(), such as
rollapply(r, width = list(-500, -1), FUN = VaRfun),
it outputs a vector of NAs and I don't know why.
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
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