How can I use relative paths in a RStudio project environment?
For example, to access a file, I use the whole path:
# My RStudio project working directory: getwd() [1] "C:/Users/MaurizioLocale/OneDrive/Data_Science/10_Capstone_project/ CP_Natural_Language/MY_FILE.txt"
But it is really long.
I am trying to use paths relative to the working environment. I tried something conceptually similar to:
"~/MY_FILE.txt"
where ~
represents the working environment. Unfortunately, it does not work.
If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ).
You could change the working directory. Get the address in the beginning getwd()
, replace it by your project folder with setwd()
. Then, when accessing a file just use read.table("./folder/file.R")
.
The so-called here package is really useful for avoiding absolute paths in (as well as outside of) RStudio. Suppose you have an RStudio project and want to access the file /data/file.txt
. This would be done as follows. This way, you don't have to mess around with getwd()
, just work relative to your project root using here()
.
library(here) #> here() starts at C:/test/someproject here("data", "file.txt") #> "C:/test/someproject/data/file.txt" readLines(here("data", "file.txt")) #> "The here package is awesome!"
How here figures out where your project root is is described in ?here
and also in the "Ode to the here package" by Jenny Bryan.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With