get lhs object name when piping with dplyr

2019-04-28 11:11发布

问题:

I'd like to have a function that can use pipe operator as exported from dplyr. I am not using magrittr.

df %>% my_function

How can I get df name? If I try

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

it returns

[1] "."

while I'd like to have [1] "df"

Any suggestion?

Thank you in advance,
Nicola

回答1:

Here's a hacky way of doing it, which I'm sure breaks in a ton of edge cases:

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

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

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


回答2:

I don't believe this is possible without adding an extra argument to your my_function. When chaining functions with dplyr it automatically converts the df to a tbl_df object, hence the new name "." within the dplyr scope to make the piping simpler.

The following is a very hacky way with dplyr which just adds an addition 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 you couldn't just pass the df with your original function because the tbl_df object is automatically passed to all subsequent functions.



标签: r pipe dplyr chain