5

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
gowerc
  • 1,039
  • 9
  • 18
  • 5
    Does this answer your question? [Get name of dataframe passed through pipe in R](https://stackoverflow.com/questions/42560389/get-name-of-dataframe-passed-through-pipe-in-r) – jay.sf Feb 29 '20 at 13:15
  • 2
    `iris %>% {parent.frame(5)$lhs} %>% as.character` – Matt Feb 29 '20 at 13:34

1 Answers1

2

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