0

作为中级 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)

任何人都可以提出任何建议来优化速度吗?

4

1 回答 1

0

使用嵌套循环似乎是个坏主意。您的代码可以矢量化以加快速度。

例如,为什么要查找行号的顶部和底部?您可以简单地将时间值与“time_0 + 频率”进行比较:它是矢量化操作。

HTH。

于 2013-08-14T23:07:58.513 回答