How to save the file to user working directory when building R package?

Viewed 37

I am learning to build R packages (myPkg) and have a function that will save a rds file to working directory like that:

myPkg_fun <- (path = ".") {
  str <- "Hello World"
  out_path <- file.path(path, "str.rds")
  saveRDS(str, out_path)
}

I can install and load my package library(myPkg) in another project using RStudio, but I cannot save the .rds to my (user) working directory.

When I use myPkg::myPkg_fun(path="."), the .rds is actually saved in /Library/Frameworks/R.framework/Versions/4.0/Resources/library/myPkg/examples/. I think there are some missing steps to connect the package path to user's working directory.

Can anyone help me with this? Thank you!

1 Answers

Since it's incredibly easy to create new packages in R (thanks to RStudio and packages such as devtools and usethis), I've created a minimal package with the single function myPkg_fun().

I suggest

  1. Taking a look at the GitHub repo to see what's in the package and how it's set up compared to your local package.
  2. Installing the package with remotes::install_github("mevers/myPkg").
  3. Opening a fresh R terminal (or start a fresh RStudio instance, making sure that no project is open) and navigate to a specific working folder. Make sure you either setwd() or "More > Set As Working Directory" in the RStudio file browser window.
  4. Do library(myPkg); myPkg_fun() and observe how the RDS file is saved in your local working folder.
Related