【问题标题】:Improve code speed performance - ‘by’ and ‘approx’ functions in R提高代码速度性能 - R 中的“by”和“approx”函数
【发布时间】:2021-06-23 07:37:33
【问题描述】:

我有一个关于日期和深度的计算氧剖面 (cop) 数据。每个日期的深度间隔不一样,所以我需要通过线性近似计算圆形深度列(“Depth2”)的氧气。我用'by'和一个近似函数完成了它。它工作正常,但有点慢(下面代码中的数据集大约需要 3.5 秒)。我正在寻找一种提高计算速度的方法。有什么建议么? 我希望从谷歌驱动器加载数据能够顺利进行。

 #download data from google drive
id<-"1p1wiw8NS-oMCI5RDZNaHc-55EpWSFEv8"# google file ID
cop<-read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download",id))
    
start_time <- Sys.time()

# calculate linear approx to the rounded depth and leave only unique result per date
df_list <- by(cop, cop$Date, function(sub) {
  copa <- approx(x=sub$Depth, y=sub$Oxygen, xout=sub$Depth2, rule=2)
  
  df <- unique(data.frame(Date = sub$Date, 
                          Depth2 = sub$Depth2,
                          O2 = copa$y,
                          stringsAsFactors = FALSE))
  return(df)
})    

cop2 <- do.call(rbind, unname(df_list))

end_time <- Sys.time()
end_time - start_time

【问题讨论】:

    标签: r performance split-apply-combine


    【解决方案1】:

    以下版本比发布的基于 by 的版本快 0%。不多,大部分时间都在approx

    start_time2 <- Sys.time()
    M <- as.matrix(cop[c("Depth", "Depth2", "Oxygen")])
    inx <- split(seq_along(row.names(cop)), cop$Date)
    df_list3 <- lapply(inx, function(i){
      copa <- approx(
        x = M[i, "Depth"],
        y = M[i, "Oxygen"],
        xout = M[i, "Depth2"],
        rule = 2
      )
    
      df <- unique(data.frame(copa))
      df$Date <- cop[ i[1], "Date"]
      df
    })
    cop3 <- do.call(rbind, unname(df_list3))[c(3, 1:2)]
    names(cop3)[2:3] <- c("Depth2", "O2")
    end_time2 <- Sys.time()
    
    identical(cop2, cop3)  # FALSE
    all.equal(cop2, cop3)  # TRUE
    
    t1 <- as.numeric(end_time - start_time)
    t2 <- as.numeric(end_time2 - start_time2)
    100*(t1 - t2)/t1
    #[1] 20.46678
    
    rm(M, inx)  # final clean up
    

    【讨论】:

    • 快了 15~20%。谢谢@Rui
    猜你喜欢
    • 2013-12-03
    • 2020-08-16
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多