pipe - rewriting nested function calls with pipes

pipe() - Replacing nested function calls with the pipe operator

  • This is the inverse of yesterday’s code
  • I’m trying to wrap my head around some parts of the rlang package so I set myself a task to focus my exploration: Auto-rewrite nested function calls into a chain of piped function calls

pipe()

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# pipe - Auto-rewrite a nested function calls as a chain of piped function calls
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pipe <- function(ee) {
  if (!rlang::is_call(ee)) { 
    return(ee) 
  }
  
  this_fn <- rlang::call_name(ee)
  updated_args <- rlang::call_args(ee) %>% map(pipe)
  
  if (identical(this_fn, "%>%") || length(updated_args)==0) {
    rlang::call2(this_fn, !!!updated_args)
  } else {
    arg1       <- updated_args[[1]]
    other_args <- updated_args[-1] 
    rlang::call2(as.name("%>%"), arg1, rlang::call2(this_fn, !!!other_args)  )
  } 
}
nested_funcs <- quote(mean(runif(sample.int(10, sf())), na.rm=TRUE))

pipe(nested_funcs)
10 %>% sample.int(sf()) %>% runif() %>% mean(na.rm = TRUE)