如何用优化的函数替换 R 中的 for 循环(lapply?)

Bru*_*usa 5 loops r vectorization

我有一个数据框,每一行都有时间事件。在一行中,我有发送者的事件类型(typeid=1),另一行有接收者的事件(typeid=2)。我想计算发送方和接收方之间的延迟(时差)。

我的数据组织在 data.frame 中,如下面的快照所示:

dd[1:10,]
     timeid   valid typeid
1  18,00035 1,00000      1
2  18,00528 0,00493      2
3  18,02035 2,00000      1
4  18,02116 0,00081      2
5  18,04035 3,00000      1
6  18,04116 0,00081      2
7  18,06035 4,00000      1
8  18,06116 0,00081      2
9  18,08035 5,00000      1
10 18,08116 0,00081      2

calc_DelayVIDEO <- function (dDelay ){

        pktProcess <- TRUE
        nLost <- 0
        myDelay <- data.frame(time=-1, delay=-1, jitter=-1, nLost=-1)
        myDelay <- myDelay[-1, ]
        tini <- 0
        tend <- 0
        for (itr in c(1:length(dDelay$timeid))) {
           aRec <- dDelay[itr,]
           if (aRec$typeid == 1){
                tini <- as.numeric(aRec$timeid)
                if (!pktProcess ) {
                   nLost <- (nLost + 1)
                   myprt(paste("Packet Lost at time ", aRec$timeid, " lost= ", nLost, sep=""))
                }

                pktProcess <- FALSE 
           }else if (aRec$typeid == 2){

                tend <- as.numeric(aRec$timeid)
                dd <- tend - tini
                jit <- calc_Jitter(dant=myDelay[length(myDelay), 2], dcur=dd)
                myDelay <- rbind(myDelay, c(aRec$timeid, dd, jit, nLost))
                pktProcess <- TRUE
                #myprt(paste("time=", aRec$timeev, " delay=", dd, " Delay Var=", jit, " nLost=", nLost ))
           }
        }
        colnames(myDelay) <- c("time", "delay", "jitter", "nLost")
        return (myDelay)
}
Run Code Online (Sandbox Code Playgroud)

为了执行延迟计算,我使用 calc_DelayVideo 函数,但是对于具有大量记录(~60000)的数据帧,它需要很多时间。

如何用更优化的 R 函数替换 for 循环?我可以使用 lapply 来做这样的计算吗?如果是这样,你能给我举个例子吗?

提前致谢,

Dir*_*tel 4

通常的解决方案是认真思考问题以找到矢量化的东西。

如果失败,我有时会求助于用 C++ 重写循环;Rcpp包可以帮助界面。