Skip to content
Back to formatted view

Raw Message

Message-ID: <a403489d-4e27-fc16-86b1-95a07dbbc47a@gmail.com>
Date: 2019-05-03T23:58:59Z
From: Duncan Murdoch
Subject: [R-pkg-devel]  Writing to files without altering working directory in R package
In-Reply-To: <CAMVrHdD4h48Y+jUZbj4H4Hc1-0jwqUk3rNoR9rLuvsiFBtXWFQ@mail.gmail.com>

On 03/05/2019 6:33 p.m., Jarrett Phillips wrote:
> Hello,
> 
> My R package has a function with an argument to specify whether numerical
> results should be outputted to a CSV file.
> 
> CRAN policy stipulates verbatim that
> 
> Packages should not write in the user?s home filespace (including
> clipboards), nor anywhere else on the file system apart from the R
> session?s temporary directory (or during installation in the location
> pointed to by TMPDIR: and such usage should be cleaned up). Installing into
> the system?s R installation (e.g., scripts to its bin directory) is not
> allowed.
> 
> I know I should use tempdir() within my package function, but I've not seen
> any examples on how this is best done within existing R packages.
> 
> Within my package documentation examples for my function, I have the lines:
> 
>   \dontshow{.oldwd <- setwd(tempdir())}
> 
> ... some R code ...
> 
> \dontshow{setwd(.oldwd)}
> 
> but I have been informed that this is not the accepted way.
> 
> Any ideas from the community on how do do this properly?

Use the tempfile() function to generate a filename in the temporary 
directory.  You might want to use the "pattern" or "fileext" arguments, 
but don't change the "tmpdir" argument.

Then write to that file.

For example,

filename <- tempfile(fileext = ".csv")
write.csv(df, filename)

It's a good idea to clean up afterwards using

unlink(filename)