ベクトル化方法:前回に基づいて値を設定するバイナリベクトルが1でした
質問
私は別のr初心者の質問があります...
次のコードを次のようにvectrizeする(ループを避けます):
# 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データステップウェイとデスペラトリーを維持などを探していることを考えています。サプライなどを理解するために、いくつかの簡単な外観を見つけることができますか?
あなたの親切な助けをありがとう。
最高、サモ。
解決
私が正しく理解した場合、あなたの問題は次のとおりです。あなたは2つのベクトルを持っています signal
と mktdataclose
長さの n
, 、そして新しいベクトルを作成したい EntryPrices
長さの n
そのような mktdataclose[i]
の値です mktdataclose
過去 時間 signal
時間以前に1でした i
. 。あなたはこれをforループなしで行うことができます、 cummax
, 、しばしば予想外に有用な機能(この質問は、この機能を使用して同様に解決された以前の質問のいくつかと風味が似ていることに注意してください。 cumsum
)。 Gavinのデータを使用して、ここに行きます。
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
他のヒント
信号は0と1なので、次のことをベクトル化できると思います。
EntryPrices * signal
これは、より簡単に見つける可能性のある別のソリューションです。 PrasadのPsudo-dataを使用しています。
> 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
所属していません StackOverflow