新人学习R的过程中遇到一个问题,特来求教:
以下函数,如果我想把其中的显式循环改成apply函数的形式,要怎么改呢?
DBO <- function(x, n, ceiling, floor, multi){
#处理异常数据:参数值超范围、数据有无效值
x <- try.xts(x, error = as.matrix)
if (n < 1 || n > NROW(x))
stop("Invalid 'n'")
if (any(nNonNA <- n > colSums(!is.na(x))))
stop("n > number of non-NA values in column(s) ", paste(which(nNonNA), collapse = ", "))
#动态参数值的计算
currentV <- runSD(x, 30, sample=T)
deltaV <- Delt(currentV)
deltav[is.na(deltav)] = 0
lookback <- deltaV
for( i in n:NROW(x)){
if( i == n){
lookback[i] <- 20*(1+deltaV[i])
}
else{
lookback[i] <- lookback[i-1]*(1+deltaV[i])
}
lookBack <- min(lookBack,ceiling)
lookBack <- max(lookBack,floor)
}
return(lookback)
}
谢谢~~ |