Following is my example function
op.try.df<- function(df){
x1 <- bind_rows(full_v_gu,summarise(df,across(where(is.numeric),sum)))
x2 <- x1%>%
mutate("Perc"=round(Composite_Score/MAX*100,0))
x3 <- x2[,c("Name" ,"Total","Score","Perc")]
write.csv(x3,"df.csv")
x3
}
How do I provide output file name based on the input data frame name? I want my output file (df.csv) to have the same name of the data frame, for example if my input file is named 'new' op.try.df(new), then how do I get a file name 'new.csv' in the folder? currently all my output files are named df.csv.
CodePudding user response:
At the beginning of the function, use substitute with deparse to extract the input name
op.try.df <- function(df){
nm1 <- paste0(deparse(substitute(df)),'.csv')
x1 <- bind_rows(full_v_gu,summarise(df,across(where(is.numeric),sum)))
x2 <- x1%>%
mutate("Perc"=round(Composite_Score/MAX*100,0))
x3 <- x2[,c("Name" ,"Total","Score","Perc")]
write.csv(x3, nm1)
x3
}
-testing
> testing.df<- function(df){
nm1 <- paste0(deparse(substitute(df)),'.csv')
nm1
}
>
> testing.df(mtcars)
[1] "mtcars.csv"
