How to extract data.frame name inside an R function?

Hello all,
I want to write a custom function to write data.frames to excel and I need to get the name of the data frame inside the function as in

  fun <-  function(df){
  foo(df) -> name
  # foo is the function I need to get the name of the object
  writexl::write_xlsx(x = df,path = paste0(name,"xlsx"))  
}

when I use the deparse(substitute(df)) method it just gives me "df" but I need a function that gives me the name the "df" value is assigned to. like if I use fun(df=iris) I want the file to be automatically named (iris.xlsx). Thanks in advance.

I think you have it, you just have to reverse "name" and "foo(df)", replacing "foo" with "deparse(substitute(df)). See example below.

f = function(df) {
  name = deparse(substitute(df))
  path = paste0(name, '.xlsx')
  return(path)
}

f(iris)
#> [1] "iris.xlsx"

Created on 2022-09-09 with reprex v2.0.2.9000

1 Like

Yes it worked! thanks very much!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.