acd
acd

Reputation: 1

Save excel file with dataframe name if in a function

Simple question but how do you save the name of a dataframe as the excel filename if it's in a function?

export_origin <-  function(df){
 df1 <- unite(df, variable, c(Reaction.Type, Trial, Actual.Total.Seconds)) 
 df2<- dcast(df1, X.nm.~variable, value.var = "X.A.")
 fname= paste(df, "xls", sep = ".")
 write.xlsx2(df2, file = fname, col.names = TRUE)}

I want fname=df.xls with whatever the df name is that I input but it saves it as the observations within the dataframe as the name.

Upvotes: 0

Views: 56

Answers (1)

akrun
akrun

Reputation: 886938

We can use deparse(substitute

export_origin <-  function(df){
    v1 <- deparse(substitute(df))
    df1 <- unite(df, variable, c(Reaction.Type, Trial, Actual.Total.Seconds)) 
   df2<- dcast(df1, X.nm.~variable, value.var = "X.A.")
   fname= paste(v1, "xls", sep = ".")
   write.xlsx2(df2, file = fname, col.names = TRUE)}
  }

To make this reproducible,

export_origin <-  function(df){
    v1 <- deparse(substitute(df))
    paste(v1, "xls", sep=".")
 }

export_origin(df)
#[1] "df.xls"

Upvotes: 2

Related Questions