Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use the here() function to go up a level above root directory

Tags:

r

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.

like image 773
C. Denney Avatar asked Aug 06 '18 17:08

C. Denney


People also ask

What does the here :: here () function do?

The here package enables easy file referencing by using the top-level directory of a file project to easily build file paths. This is in contrast to using setwd() , which is fragile and dependent on the way you order your files on your computer.

How does here () work in R?

Description. here() uses a reasonable heuristics to find your project's files, based on the current working directory at the time when the package is loaded. Use it as a drop-in replacement for file. path() , it will always locate the files relative to your project root.

How do I move up a directory in R?

setwd() tells R to open a different folder instead. setwd('../') tells R to go up to a parent directory. (You can do this using the Graphical User Interface in RStudio).

How do you use here?

The word here means, 'in, at or to this place'. Simply speaking, here is used when you are referring to the place where you are. It is an adverb, a word that gives more information about a verb or adjective. It can be used to refer to something you are offering to a person, for example, 'Here is your coffee.


2 Answers

library(here)
set_here(path='..')

Gets you into the parent directory

like image 164
Mako212 Avatar answered Oct 22 '22 00:10

Mako212


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.

like image 39
Devin Judge-Lord Avatar answered Oct 22 '22 01:10

Devin Judge-Lord