tidyverse / magrittr

Improve the readability of R code with the pipe
https://magrittr.tidyverse.org
Other
957 stars 157 forks source link

Allow logging of calls and process time #198

Closed bakaburg1 closed 4 years ago

bakaburg1 commented 5 years ago

It would be useful to add some global options that make either %>% print the called verb at the beginning of the activity and the elapsed time at the end of it. In order to spot bottlenecks in long-chained sequences of functions.

I tried to develop at least the process time part with:

`%>l%` <- function (lhs, rhs) 
{
    start <- Sys.time()
    parent <- parent.frame()
    env <- new.env(parent = parent)
    chain_parts <- magrittr:::split_chain(match.call(), env = env)
    pipes <- chain_parts[["pipes"]]
    rhss <- magrittr::chain_parts[["rhss"]]
    lhs <- chain_parts[["lhs"]]
    env[["_function_list"]] <- lapply(1:length(rhss), function(i) magrittr:::wrap_function(rhss[[i]], pipes[[i]], parent))
    env[["_fseq"]] <- `class<-`(eval(quote(function(value) freduce(value, `_function_list`)), env, env), c("fseq", "function"))
    env[["freduce"]] <- freduce

    out <- {
        if (is_placeholder(lhs)) {
            env[["_fseq"]]
        }
        else {
            env[["_lhs"]] <- eval(lhs, parent, parent)
            result <- withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
            if (magrittr:::is_compound_pipe(pipes[[1L]])) {
                eval(call("<-", lhs, result[["value"]]), parent, parent)
            }
            else {
                if (result[["visible"]]) 
                    result[["value"]]
                else invisible(result[["value"]])
            }
        }
    }

    message('Elapsed: ', difftime(Sys.time, start))
    out
}

But I get: Error in pipes[[i]] : subscript out of bounds

moodymudskipper commented 4 years ago

You might be interested in https://github.com/moodymudskipper/pipes. It is a fork of this package that contains a %L>% pipe that does just that.

hadley commented 4 years ago

This is out of scope for magrittr; definitely check out @moodymudskipper's package.