Search code examples
rif-statementtemp

Write data to a temporary file with filename stored in an R environment


I have some data the I would like to write to a temporary CSV file in R.

Users have the option to specify a filename of their choice, which is stored in an environment (called 'envr') separate from .GlobalEnv

if (!is.null(envr$filename)) {
    write.csv(df, file = paste(envr$filename, ".csv", sep = ""))
  }

In order to do this successfully, I need to create a temporary file that is assigned to the filename chosen by the user.

if (!is.null(envr$filename)) {
    file.name <- get("filename", envir = envr)
    tempfile(fileext = ".csv")
    write.csv(df, file = file.name)

}

The above if statement however does not do the job, as a CSV file is not saved in $TMPDIR.

How can I easily integrate tempfile() into the first if statement above without having to assign it to a variable name (file.name)?


Solution

  • You may concatenate the file name (obtained from the filename environment variable) with the temporary folder of the session (using tempdir()), along with the .csv extension, as follows:

    if (!is.null(envr$filename)) {
      write.csv(df, file = paste0(tempdir(), "/", get("filename", envir = envr), ".csv"))
    }
    

    Let me know if it answers your question or if you need any further help.