Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading