Get lhs object name when laying piping using dplyr

I would like to have a function that can use the pipe operator exported from dplyr. I am not using magrittr.

df %>% my_function


How can I get the name df? If i try

my_function <- function(tbl){print(deparse(substitute(tbl)))}


it returns

[1] "."


although I would like to [1] "df"

Any suggestion?

Thanks in advance,


source to share

2 answers

Here's a hacky way to do it that I'm sure breaks down a ton of cross-cases:

library(data.table) # for the address function
                    # or parse .Internal(inspect if you feel masochistic

fn = function(tbl) {
  objs = ls(parent.env(environment()))
          function(x) address(get(x, env = parent.env(environment()))) == address(tbl))]

df = data.frame(a = 1:10)
df %>% fn
#[1] "df"




I don't believe this is possible without adding an extra argument to yours my_function

. When the chaining function s dplyr

automatically converts an object df

to an object tbl_df

, hence the new name "."

in the scope dplyr

to make piping easier.

Below is a very hacky way with dplyr that just adds an add argument to return the name of the original data.frame

my_function <- function(tbl, orig.df){print(deparse(substitute(orig.df)))}
df %>% my_function(df)
[1] "df"


Note that you couldn't just pass df

with your original function, because the object is tbl_df

automatically passed to all subsequent functions.



All Articles