首页 > 解决方案 > R - dplyr 中的代码行运行时间

问题描述

当我想估计 R 代码的运行时间时,我使用函数system.time().

library(dplyr)

system.time({
    Titanic %>%
        as.data.frame() %>%
        mutate(Dataset = 1) %>%
        bind_rows(as.data.frame(Titanic)) %>%
        mutate_all(funs(replace_na(., NA))) %>% 
        filter(Dataset != 1)
})

# utilisateur     système      écoulé 
#        0.02        0.00        0.02

问题: 有没有办法知道每个操作的运行时间,每个管道之间的操作(the mutate, then the bind_rows, then thefilter等)而不需要一个一个地运行或不写几个system.time()

在这个例子中它没有用,但有时我收到一个很长的脚本,运行时间很长,我想确定哪些操作是最低的。

我做了一些研究,但没有发现有用的东西。

标签: rperformancetimedplyr

解决方案


您可能对%L>%我的包管道中的管道感兴趣:

# devtools::install_github("moodymudskipper/pipes")
library(pipes)
Titanic %L>%
  as.data.frame() %L>%
  mutate(Dataset = 1) %L>%
  bind_rows(as.data.frame(Titanic)) %L>%
  mutate_all(list(~replace_na(., NA))) %L>% 
  filter(Dataset != 1)

# as.data.frame(.)   ~  0.03 sec
# mutate(., Dataset = 1)   ~  0 sec
# bind_rows(., as.data.frame(Titanic))   ~  0 sec
# mutate_all(., list(~replace_na(., NA)))   ~  0 sec
# filter(., Dataset != 1)   ~  0.03 sec
# [1] Class    Sex      Age      Survived Freq     Dataset 
# <0 rows> (or 0-length row.names)

推荐阅读