[R-pkg-devel] How to write example results to a tempdir()?

Duncan Murdoch murdoch.duncan at gmail.com
Thu Apr 26 19:20:03 CEST 2018


On 26/04/2018 1:04 PM, Henrik Bengtsson wrote:
> On Thu, Apr 26, 2018 at 6:28 AM, Spencer Graves
> <spencer.graves at effectivedefense.org> wrote:
>>
>>
>> On 2018-04-26 07:11, Jose A Guijarro wrote:
>>>
>>> El 25/04/18 a las 20:21, Duncan Murdoch escribió:
>>>>
>>>> On 25/04/2018 1:32 PM, Sarah Goslee wrote:
>>>>>
>>>>> Don't change the working directory! That has all kinds of unpleasant
>>>>> side effects for the unsuspecting user, possibly even more so than
>>>>> writing to a file.
>>>>>
>>>>> Instead, write the file to the temp directory, and read it from there,
>>>>> with e.g.
>>>>>
>>>>> wd <- tempdir()
>>>>> write(dat, file.path(wd, 'Ttest_1981-2000.dat'))
>>>>>
>>>>> Using file.path() means that the appropriate path delimiter for that
>>>>> OS will be used.
>>>>
>>>>
>>>> That's one good way to do it.  But it is possible to change directory and
>>>> change back at the end of the example.  For example,
>>>>
>>>> wd <- tempdir()
>>>> savedir <- setwd(wd)
>>>>
>>>> ... # the original code that writes and reads in the current dir
>>>>
>>>> setwd(savedir)
>>>>
>>>> There's a worry that an error in the middle of the code will leave the
>>>> user in the wrong place.  If that's really unlikely to happen, then this
>>>> code is a little simpler than Sarah's suggestion.
>>>>
>>>> If it is likely, you can use tryCatch(..., finally = setwd(savedir)), but
>>>> I think Sarah's solution would be preferable in most cases:  many users will
>>>> not understand what tryCatch() does.
>>
>>
>>
>> Hi, Duncan, et al.:
>>
>>
>>        Under what circumstances should one also use "on.exit":
>>
>>
>> wd <- tempdir()
>> savedir <- setwd(wd)
>> on.exit(setwd(savedir))?
>>
>>
>>        Even senior R programmers may miss a failure mode.  In a function,
>> this works well:  I don't need to remember to "setwd(savedir)" later in the
>> code, which could be a problem if I have multiple exit points.  I don't know
>> how it would work in a vignette or the examples section of a *.Rd file.
>> tryCatch(..., finally = setwd(savedir)) condenses this into one line ... and
>> is too terse for me in many cases.
> 
> FWIW, it can also be used in a local() call, e.g.
> 
> local({
>    wd <- tempdir()
>    savedir <- setwd(wd)
>    on.exit(setwd(savedir))
>    [...]
> })

Thanks for pointing that out.  That also has the advantage that it 
doesn't wipe out variables named "wd" and "savedir".

On the other hand, it has the disadvantage that it doesn't leave wd and 
savedir behind for the user to examine, and cut and paste of the central 
executable lines won't work, you need to cut the whole local() call.

Duncan Murdoch



More information about the R-package-devel mailing list