get lhs object name when piping with dplyr

后端 未结 5 2121
遥遥无期
遥遥无期 2021-02-13 15:43

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

5条回答
  •  抹茶落季
    2021-02-13 16:06

    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"
    

提交回复
热议问题