我还有另一个 R 初学者问题...
如何对以下代码进行矢量化(避免 for 循环):
# algorithm for getting entry prices (when signal > 0): look back from current
# position until you find first signal > 0,
# `mktdataclose` at that time is entry price
# `entryPrices` is an xts object representing entry prices
# if entryPrices are not available (is.null == TRUE) then wee need to reconstruct
# them from signal (xts object with 1 when entry signal triggered and 0
# otherwise) and close prices available in mktdataclose (an xts object with the
# same length as signal and same dates just that it represents closing prices)
EntryPrices <- entryPrices
if (is.null(EntryPrices)) {
# get entryprices as close prices on buy signal
EntryPrices <- ifelse(signal > 0, mktdataclose, 0)
entryPrice <- 0
for (i in 1:NROW(signal)) {
if (signal[i] > 0) entryPrice <- mktdataclose[i]
EntryPrices[i] <- entryPrice
}
}
我一直在思考 SAS 数据步进方式和绝望地寻找保留等。我在哪里可以找到一些简单的例子来理解 sapply 等(不幸的是,通过 ?sapply 的帮助对我来说很复杂......:()
感谢您的热心帮助。
最好的,萨摩。