簡體   English   中英

用 lapply 命令替換 For 循環來改善它的執行時間

[英]Improve Excecution Time of For Loop by Replacing it with lapply command

在這里,我正在研究 R 代碼的優化,眾所周知,最耗時的是for loop ,我試圖用 lapply 替換它並進行實驗以減少執行時間。

每個處理語法的時間線:Provis 如圖所示,執行 for 循環所需的時間為 40 毫秒,這里的任務是如何使用 lapply 最大限度地減少 For 循環的執行時間。 How to replace this code of for loop with Lapply讓我們可以How to replace this code of for loop with Lapply優化代碼的處理速度。 為了確定每行代碼所需的時間,使用了 Profvis 庫。 我曾嘗試使用 lapply ,但在實施中遇到了問題

library(profvis)
profvis({
rm(list = ls())
# Creating Dummy data 
row_id <- 100
No_of_level <- 4
spliz <- paste("c(","TRUE,",paste(rep("FALSE",(row_id-1)),collapse=","),")")
d <- as.data.frame(matrix(,nrow = row_id*No_of_level ,ncol=2))
names(d) <- c("Tag","y_pred")
d$Tag <-  cumsum(rep(eval(parse(text=spliz)),4))
d$y_pred <- sample(3:4, row_id*No_of_level, rep = TRUE)
d$y_pred <- paste("L",d$y_pred,sep="")
#### ------------------------------------

# How to replce Below For Loop codes to lapply and get the result in the variable.     
    v <- data.frame();i=0
    for (i in (1:max(d$Tag))){
      #i=4
      s <- filter(d , Tag == i)
s$y_pred <- as.character(s$y_pred)
      temp = 0
      for(i in 1:nrow(s))
      s$R2[i] <- ifelse(s$y_pred[i] == "L3", temp <- temp + 1, 0)
      s$seq <- seq_along(1:nrow(s))
      s$Aoc <- (1-(s$R2/s$seq))*100
      s$Aoc1 <- (s$R2/s$seq)
      v <- rbind(v,s)
  }

})

預期:改善上述 For 循環代碼的執行時間,執行時間為 40 毫秒,如果我們嘗試使用 lapply 可能我們可以將處理時間從 40 毫秒縮短到 10 毫秒或更少。

不確定您的預期輸出是什么,但這樣的事情應該可行:

v <- do.call(rbind, 
             lapply(split(d, d$Tag), function(s){
               res <- s
               res$R2 <- ifelse(as.character(res$y_pred) == "L3", 
                                cumsum(as.character(res$y_pred) == "L3")), 0)
               res$seq <- seq_along(1:nrow(res))
               re$Aoc <- (1-(res$R2/res$seq))*100
               res$Aoc1 <- (res$R2/res$seq)
               #return
               res
             }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM