Search code examples
rdataframexlsxdata-cleaning

Create excel file in R dynamically


I have to copy the data from a data frame df1 and write it to a new excel in a specific folder.The folder path is stored in a variable called fpath. There is a variable s which holds the filename. There are many files in the folder. I want the excel to be created dynamically for each file.

Now I am hard-coding the filename.

write.xlsx(df1,"C:/Users/Folder/results.xlsx")

Is there a way where the write.xlsx can dynamically name the excel that it is writing. I tried the following way but it threw an error.

write.xlsx(df1,file=fpath + s)

Kindly suggest me if there is a way to dynamically name the created excel file without hard-coding the name in the code.


Solution

  • You can try with paste0:

    write.xlsx(df1, file = paste0(fpath, s))
    

    Or depending if your path ends in / or not:

    write.xlsx(df1, file = paste0(fpath, '/', s))