How to get a function input name in R whilst using pipes

Viewed 392

I am trying to capture the name of the input variable as a character string. This is fairly easy using match.call() however this doesn't work when using magrittr's pipes. Wondering if there is any easy modification that would get it to work within pipes as well as if the function was called normally?

library(magrittr)
myfun <- function(fun){
    print(match.call()$fun %>% as.character())
}

myfun(mean)
mean %>% myfun

myfun(iris)
iris %>% myfun
1 Answers

By default the pipe operator %>% pass the input variable name as dot "." to the next function, but you can control the output from the pipe operator lhs to pass you the actual name of the input variable instead of dot in your function. See the below function ( edited to work with/without %>%)

myfun <- function(x) {
  x <- substitute(x)

 if (x !="."){
 print(deparse(x))
 }else{

  i <- 1
  while(!("chain_parts" %in% ls(envir=parent.frame(i))) && i < sys.nframe()) {
    i <- i+1
  }
  ee <- parent.frame(i)
  print(deparse(ee$lhs))
  }
}

mean %>% myfun()
[1] "mean"

myfun(mean)
[1] "mean"

Hope it helps. -Ahmed Alhendi

Related