중급 R 사용자로서 for 루프는 apply
또는 그 밖의 함수를 사용하여 매우 자주 최적화 될 수 있음을 알고 있습니다. 그러나, 나는 매우 느리게 실행되는 마코프 체인 행렬을 생성하기 위해 현재 코드를 최적화 할 수있는 함수를 알지 못합니다. 나는 속도를 최대화 했는가 아니면 내가 바라 보는 것들이 있는가? 주어진 경고가 나오기까지 24 시간 간격으로 발생 횟수를 계산하여 Markov 체인의 전환 행렬을 찾으려고합니다. 벡터 ids
에는 가능한 모든 ID (약 1700)가 들어 있습니다. 속도를 위해이를 최적화하기 위해마크로프 체인 전이 행렬 계산을 최적화 하시겠습니까?
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)
사람이 어떤 제안을 할 수있다 : 내 코드이 처리하려고 여기에
>matrix
id time
1 1376084071
1 1376084937
1 1376023439
2 1376084320
2 1372983476
3 1374789234
3 1370234809
을 그리고 :
원래 매트릭스는 예를 들어, 다음과 같습니다 ?
'Rprof'를 사용하여 코드를 프로파일 링하는 것이 좋습니다. 이것은 대부분의 시간을 보내고있는 곳을 알려줍니다. – idfah
이것은 틀립니다 : "루프는 적용과 같은 함수를 사용하여 매우 자주 최적화 될 수 있습니다". –
CodeReview 사이트가 더 적합 할 수 있습니다. –