中級の R ユーザーとして、for ループは、またはその他の関数を使用して最適化できることが非常に多いことを知っていますapply
。ただし、現在のコードを最適化してマルコフ連鎖行列を生成できる関数を認識していませんが、これは非常にゆっくりと実行されます。速度を最大にしましたか、それとも見落としていることがありますか? アラートが発生する前の 24 時間の期間の発生回数を数えることで、マルコフ連鎖の遷移行列を見つけようとしています。ベクターids
には、考えられるすべての ID (約 1700) が含まれています。
例として、元のマトリックスは次のようになります。
>matrix
id time
1 1376084071
1 1376084937
1 1376023439
2 1376084320
2 1372983476
3 1374789234
3 1370234809
そして、これを処理しようとする私のコードは次のとおりです。
matrixtimesort <- matrix[order(-matrix$time),]
frequency = 86400 #number of seconds in 1 day
# Initialize matrix that will contain probabilities
transprobs <- matrix(data=0, nrow=length(ids), ncol=length(ids))
# Loop through each type of event
for (i in 1:length(ids)){
localmatrix <- matrix[matrix$id==ids[i],]
# Loop through each row of the event
for(j in 1:nrow(localmatrix)) {
localtime <- localmatrix[j,]$time
# Find top and bottom row number defining the 1-day window
indices <- which(matrixtimesort$time < localtime & matrixtimesort$time >= (localtime - frequency))
# Find IDs that occur within the 1-day window
positiveids <- unique(matrixtimesort[c(min(indices):max(indices)),]$id)
# Add one to each cell in the matrix that corresponds to the occurrence of an event
for (l in 1:length(positiveids)){
k <- which(ids==positiveids[l])
transprobs[i,k] <- transprobs[i,k] + 1
}
}
# Divide each row by total number of occurrences to determine probabilities
transprobs[i,] <- transprobs[i,]/nrow(localmatrix)
}
# Normalize rows so that row sums are equal to 1
normalized <- transprobs/rowSums(transprobs)
スピードのためにこれを最適化するための提案を誰でもできますか?