0

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.

2
  • 3
    If you want to get the name as a string use substitute(df) Commented Jun 14, 2017 at 6:46
  • 1
    What other packages are you using? I guess unite is from dplyr and dcast is from reshape2. But where does write.xlsx2 come from? I think you might want to add more details. Commented Jun 14, 2017 at 6:47

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

That's a brilliant answer that I've never came across! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.