Where am I?
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
The here package is pretty simple ( only 3 functions), but I keep messing things up when I try to create paths with it, so this is my aide-memoire. It might be useful for others too.
Here finds the root of your current folder / working directory. If you use Projects in RStudio, that will usually be the root of your project folder. (If not, you can use set_here() to create a small file which will set the root location).
Then, you can use here() as a variable for the folder root / working directory, and any subfolders you create are referenced relative to that.
This aids code portability – If I have code that creates a subfolder in my Documents folder, and send that code to someone else, then the code won’t work because the path doesn’t exist on their machine. They’ll need to revise it to make it work. If you’re on a network, filepaths get unwieldy pretty quickly.
Here() does away with that – their root folder becomes here() and any subfolders will be created under those.
The bit I always mess up is creating a sub folder, so here we are:
Where am I right now?
here()
“C:/Users/some/path/or/other”
Create a subfolder
dir.create(here("img"))
“C:/Users/some/path/or/other/img”
Create another one
dir.create(here("img","png"))
“C:/Users/some/path/or/other/img/png”
Move to the “img” folder using setwd()
setwd(here("img"))
Now to check this worked – get the current working directory with getwd()
getwd()
“C:/Users/some/path/or/other/img”
Then go back to the root of the project
setwd(here())
Check you are back where you started:
getwd()
“C:/Users/some/path/or/other”
Now the next time I am like this:
¯\_(ヅ)_/¯
I can just read this post, and hope no-one sees me reading my own blog.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.