I'm creating an R package that automatically creates trained models. One of the goals is to allow the user to save the trained models for use with future data. The trained models were originally saved to the Environment. Comments from CRAN state, "In your examples/vignettes/tests you can write to tempdir()."
Also from CRAN, "Omit any default path in your functions and write to tempdir() in examples, vignettes or tests." https://contributor.r-project.org/cran-cookbook/code_issues.html#writing-files-and-directories-to-the-home-filespace
However, all my attempts to save the trained models to tempdir() return an empty directory.
Here's a simple example:
library(MASS)
lm1 <- lm(medv ~ ., data = Boston)
tempfile('lm1')
The file lm1 is fine, that's what I want to share with the user. The last line returns a location on my computer, but that directory is empty:
> tempfile('lm1')
[1] "/var/folders/2c/hvxqjjcn3sq5lcshxhv8wnsw0000gp/T//Rtmp4vWDDq/lm1269d23afd784"
The problem is identical if the file is named:
library(MASS)
lm1 <- lm(medv ~ ., data = Boston)
model1 <- tempfile('lm1')
> model1
[1] "/var/folders/2c/hvxqjjcn3sq5lcshxhv8wnsw0000gp/T//Rtmp4vWDDq/lm1269d6d6e2d69"
Same issue if I create a specific temp directory:
temp1 <- tempdir()
library(MASS)
lm1 <- lm(medv ~ ., data = Boston)
model1 <- tempfile('lm1')
What's the proper way to write to tempdir() that will allow the user to access the trained models on future (untrained) data for an R package?

saveRDS()with a path that the user can specify.tempfile(.)returns a string, it doesn't create a file, and it certainly doesn't try to infer what you want to store in that file. It gives you a guaranteed unique and temporary filename. It is up to the caller to do something with it. In this case, perhapstf <- tempfile("lm1_", fileext=".rds"); saveRDS(lm1, tf);.