Search code examples
rr-package

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


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!


Solution

  • Sorry for not making the question clear enough. The pkg I am building is a shiny library. I figured out the reason that is because myPkg_fun() is run in an shiny app and by default, the working dir is where the app.R locates.

    The solution is to

    1. set user's working dir in the env variable
    2. read the env variable and force to reset the working dir to the user's working dir in the app

    So that the .rds can be saved into the right folder.