Reputation: 627
I would like to have the here function go up a level before starting to go down directory levels.
For example, my project is in the directory '/parent/project_root/', so here() sees this as the default directory. I have some data that I would like to read in that is in 'parent/other_dir/'. What argument do I need to pass to here() to have it first go up to 'parent' then down to other_dir (the equivalent of setwd('../')
)? I'd rather not move other_dir into 'project_root' if I don't have to, but if it isn't possible then, I can do it.
Upvotes: 15
Views: 12552
Reputation: 192
You can simply remove the project directory string from the path:
gsub("project_root/", "", here("other_dir") )
converts "parent/project_root/other_dir/" to "parent/other_dir/"
Or, more elegantly with stringr
:
here("other_dir") |> str_remove("project_root/")
It's a bit of a hack, but it works for the use case, where you want here()
to point to the project root but occasionally want to point above with paths that are still universally valid within the project directory.
For example, I often use this to pull data from one project to another.
here("[other project]", "data", "data.rda") |>
str_remove("[current project]") |>
load()
This is equivalent to load("../[other project]/data/data.rda")
except that it is universally valid within the current project directory rather than just the current project root directory. It will work if your script is in the root or /code/ folder or /docs/ or whatever, any number of layers in.
Upvotes: 6
Reputation: 1
An alternative could be to use the dirname()
function in conjunction with here()
to get the path to the upper level directory. For example: here() %>% dirname()
. This should return the path to your .../parent/
directory.
To refer to your .../parent/other_dir/
directory, you could then use:
file.path(here() %>% dirname(), 'other_dir')
Upvotes: 0
Reputation: 21
You could save a flag file (an empty file, "flag_project_root.R" for exemple) at an alternative upper project root.
here::i_am("flag_project_root.R")
brings you upward to this upper project root.
here::here('one level down', 'another level down')
brings you anywhere down in your upper project root.
This method is interesting if you want to save your script anywhere in your project folder without adapting the script.
Upvotes: 2
Reputation: 7312
library(here)
set_here(path='..')
Gets you into the parent directory
Upvotes: 8