【发布时间】:2017-04-28 15:31:02
【问题描述】:
我正在尝试生成一段代码,该代码类似于来自 zoo/xts 的 rollapply 等函数,但适用于我的需要。我使用一些非常简单的示例数据生成了代码,一切正常。但是现在我尝试在edhec 数据上运行它,我收到一个错误。我不清楚为什么,但假设它与 if 语句有关。是否有人能够诊断我收到错误的原因?
#rm(list=ls()) #Clear environment
cat("\014") #CTRL + L
library(xts)
library(lubridate)
is.even <- function(x) x %% 2 == 0
roundUp <- function(x,to=2)
{
to*(x%/%to + as.logical(x%%to))
}
functionTest <- function(data, window, slide){
nyears_t = nyears(data)
#IF statement for non-even numbers only
if(is.even(nyears_t == FALSE)) {
nyears_t <- roundUp(nyears_t)
data_extend <- data
start_extend <- .indexyear(data)[length(data)]+ 1900 + 1
end_extend <- start_extend + length(data) - 1
index(data_extend) <- update(index(data),year=start_extend:end_extend)
data <- rbind(data, data_extend)
warning("WARNING! The function has looped to the start of the timeseries. The final list(s)
will contain years that do not exist in the dataset. Please modify.")
}
nslides = nyears_t/slide
#Matrix
year_1 = (.indexyear(data)[1]+1900)
start <- seq(from = year_1, by = slide, length.out = nslides)
end <- start + window - 1
mat <- matrix(c(start, end), ncol = 2, dimnames = list(c(1:nslides), c("start", "end")))
#For loop
subsetlist <- vector('list')
for(i in 1:nslides){
subset <- data[paste0(mat[i,1], "/", mat[i,2])]
subsetlist[[i]] <- subset
}
print(subsetlist)
}
我在制作上述函数时使用的示例代码:
a <- seq(from = as.POSIXct("2000", format = "%Y"), to = as.POSIXct("2008", format = "%Y"), by = "year")
a <- as.xts(1:length(a), order.by = a)
a
functionTest(data = a, window = 3, slide = 2)
我正在测试并收到错误的示例代码:
> data(edhec, package = "PerformanceAnalytics")
> edhec <- edhec[,1:3]
> edhec <- edhec["/2007"]
> head(edhec)
Convertible Arbitrage CTA Global Distressed Securities
1997-01-31 0.0119 0.0393 0.0178
1997-02-28 0.0123 0.0298 0.0122
1997-03-31 0.0078 -0.0021 -0.0012
1997-04-30 0.0086 -0.0170 0.0030
1997-05-31 0.0156 -0.0015 0.0233
1997-06-30 0.0212 0.0085 0.0217
> functionTest(data = edhec, window = 3, slide = 2)
Show Traceback
Rerun with Debug
Error in start_extend:end_extend : NA/NaN argument
>
更新:
代码现在运行时对 if 语句进行了以下更新(感谢 Joshua Ulrich)(请参见下面的代码)。但是,if 语句仍然存在问题 - 无论数据集中存在偶数年还是奇数年,它似乎都会运行。虽然这不会影响函数的准确性,但在考虑大型数据集时可能会出现问题。如果有人对此有任何想法,将不胜感激。否则这已经超级棒了!干杯
if(is.even(nyears_t == FALSE)) {
nyears_t <- roundUp(nyears_t)
data_extend <- data
start_extend <- .indexyear(data)[nrow(data)] + 1900 + 1
end_extend <- start_extend + nyears(data) - 1
dates <- index(data)
tmp <- as.POSIXlt(dates)
tmp$year <- tmp$year + nyears(data)
dates2 <- as.POSIXct(tmp, tz = tz)
index(data_extend) <- dates2
data <- rbind(data, data_extend)
warning("WARNING! The function has looped to the start of the timeseries. The final list(s)
will contain years that do not exist in the dataset. Please modify.")
}
【问题讨论】:
标签: r loops if-statement xts zoo