2

我还有另一个 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 的帮助对我来说很复杂......:()

感谢您的热心帮助。

最好的,萨摩。

4

3 回答 3

3

如果我理解正确,您的问题是:您有两个长度为 和 的signal向量,并且您想创建一个长度为的新向量,使得最后一次的值在time或之前为 1 。您可以在不使用 for 循环的情况下执行此操作,使用一个经常出乎意料有用的函数(请注意,此问题与您之前的一些问题相似,这些问题也使用此函数和 类似地解决了)。我们开始吧,使用 Gavin 的数据:mktdataclosenEntryPricesnmktdataclose[i]mktdataclosesignalicummaxcumsum

set.seed(123)
signal <- sample(0:1, 10, replace = TRUE)
mktdataclose <- runif(10, 1, 10)  

我们的问题实际上是将signal向量转换为适当索引的向量:

indices <- cummax( seq_along(signal) * signal)

这正是indices我们想要的,除了 0。现在我们EntryPrices通过从 中提取非零值indices来设置mktdataclose

EntryPrices <- c( rep(0, sum(indices==0)), mktdataclose[ indices ])

>   cbind(signal, indices, mktdataclose, EntryPrices)
      signal indices mktdataclose EntryPrices
 [1,]      0       0     9.611500    0.000000
 [2,]      1       2     5.080007    5.080007
 [3,]      0       2     7.098136    5.080007
 [4,]      1       4     6.153701    6.153701
 [5,]      1       5     1.926322    1.926322
 [6,]      0       5     9.098425    1.926322
 [7,]      1       7     3.214790    3.214790
 [8,]      1       8     1.378536    1.378536
 [9,]      1       9     3.951286    3.951286
[10,]      0       9     9.590533    3.951286
于 2011-03-19T15:06:37.693 回答
0

因为信号是 0 和 1 我假设你可以矢量化:

EntryPrices * signal
于 2011-03-19T12:14:43.723 回答
0

这是另一种解决方案,您可能会发现它更直接。我正在使用 Prasad 的伪数据。

> EntryPrices <- ifelse(signal > 0, mktdataclose, NA)
> EntryPrices <- na.locf(EntryPrices, na.rm=FALSE)
> cbind(signal,mktdataclose,EntryPrices)
      signal mktdataclose EntryPrices
 [1,]      0     9.611500          NA
 [2,]      1     5.080007    5.080007
 [3,]      0     7.098136    5.080007
 [4,]      1     6.153701    6.153701
 [5,]      1     1.926322    1.926322
 [6,]      0     9.098425    1.926322
 [7,]      1     3.214790    3.214790
 [8,]      1     1.378536    1.378536
 [9,]      1     3.951286    3.951286
[10,]      0     9.590533    3.951286
于 2011-03-22T11:56:59.687 回答