get lhs object name when piping with dplyr

后端 未结 5 2141
遥遥无期
遥遥无期 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:09

    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.

提交回复
热议问题