Reputation: 1954
I'm using a Mac. The path.expand
function is several folders removed from my desired working directory. For example:
path.expand
('~')
[1] "/Users/my.name"
I'd like to change it to something like this:
path.expand
('~')
[1] "/Users/my.name/drive/R/project/sub.folder"
How can I go about this?
Thank you.
Upvotes: 1
Views: 2138
Reputation: 15072
A way to easily reference your files without needing to change the HOME directory is to use the here
package. This basically uses a heuristic to find the right working directory based on where your script is. Normally it looks for RStudio Project files (.rproj
) or for a .git
file if your working directory is a git repository. It's easy to use and robust to moving machines or accidental use of setwd
, or even forgetting to set HOME on a different machine/profile.
If your data file some_data.csv
above is stored in /Users/my.name/drive/R/project/sub.folder/some_data.csv
, where project
is the root folder for the project:
here::here()
[1] "/Users/my.name/drive/R/project"
here::here("sub.folder", "some_data.csv")
[1] "/Users/my.name/drive/R/project/sub.folder/some_data.csv"
and you can use it as a drop in replacement for the path, as in:
data <- read_csv(here::here("sub.folder", "some_data.csv"))
Upvotes: 3
Reputation: 160667
The tilde is, in all unix-sen (including macos), special in that it refers to what the operating system considers the home directory (via the env var HOME
).
There are two types of answers to this. Can it be done? Perhaps, sure even. Should it be done? There will likely be unintended consequences (that may be hard to troubleshoot and/or workaround), so likely not.
This works on my ubuntu box:
me@mybox:/some/path$ Rscript -e 'Sys.getenv("HOME")'
[1] "/home/me"
me@mybox:/some/path$ HOME=/tmp/ Rscript -e 'Sys.getenv("HOME")'
[1] "/tmp/"
me@mybox:/some/path$ Rscript -e 'Sys.setenv(HOME="/tmp/");Sys.getenv("HOME")'
[1] "/tmp/"
(This notably does not work as well on Windows ... which is not very unix-y of it!)
So you can try overriding it with either:
Sys.setenv(HOME = "/Users/my.name/drive/R/project/sub.folder")
, orHOME
variable in your working environment before starting R.This might have unintended consequences. For instance, R looks for ~/.Rprofile
, and git and commands look for ~/.gitconfig
and such.
My recommended way-ahead would be to define a variable and change there. If you use RStudio, then its "Projects" can always start you in the correct directory. If not and you still want this "special directory" available to you, perhaps add this to your /Users/username/.Rprofile
(in your "actual" homedir)
.specialdir <- "/Users/my.name/drive/R/project/sub.folder"
and, whenever you need to go there, use file.expand(.specialdir)
. One side-effect of this is that any of your code, functions, reports, whatever that use this will no longer be reproducible.
Upvotes: 4