Is there a way to return the name of a piped dataframe

I have a function that takes a data frame as input. I would like to create a column containing the name of the data frame. Like in the following example:

the_df <- tibble(a=c(1,2,3),
                 b=c(1,2,3))

func <- function(df){
  df <- df %>% mutate(dataframe = "name_of_df")
  return(df)
}

func(the_df)

Is this doable?

>Solution :

deparse(substitute(..)) function would help you add a new column with whatever value you pass in the function.

library(dplyr)

func <- function(df){
  name <- deparse(substitute(df))
  df <- df %>% mutate(dataframe = name)
  return(df)
}

func(the_df)

#      a     b dataframe
#  <dbl> <dbl> <chr>    
#1     1     1 the_df   
#2     2     2 the_df   
#3     3     3 the_df   

Leave a Reply