Stepping through a pipeline with intermediate results

前端 未结 5 1690
梦谈多话
梦谈多话 2021-01-01 19:50

Is there a way to output the result of a pipeline at each step without doing it manually? (eg. without selecting and running only the selected chunks)

I ofte

5条回答
  •  抹茶落季
    2021-01-01 20:39

    It is easy with magrittr function chain. For example define a function my_chain with:

    foo <- function(x) x + 1
    bar <- function(x) x + 1
    baz <- function(x) x + 1
    my_chain <- . %>% foo %>% bar %>% baz
    

    and get the final result of a chain as:

         > my_chain(0)
        [1] 3
    

    You can get a function list with functions(my_chain) and define a "stepper" function like this:

    stepper <- function(fun_chain, x, FUN = print) {
      f_list <- functions(fun_chain)
      for(i in seq_along(f_list)) {
        x <- f_list[[i]](x)
        FUN(x)
      }
      invisible(x)
    }
    

    And run the chain with interposed print function:

    stepper(my_chain, 0, print)
    
    # [1] 1
    # [1] 2
    # [1] 3
    

    Or with waiting for user input:

    stepper(my_chain, 0, function(x) {print(x); readline()})
    

提交回复
热议问题