54

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.

Worice
  • 3,847
  • 3
  • 28
  • 49
  • I don't understand your problem. Would [projects](https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) help you with your `wd` ? – Vincent Bonhomme Apr 25 '16 at 08:10
  • I would like to use shorter paths while working inside a project. Do you think I should make the question more straightforward? – Worice Apr 25 '16 at 08:13
  • 9
    All paths in R can be relative to the working directory. Working directory is set by Rstudio project automagically. For instance, I keep all data inside `/data` folder and when I load it, I use `read.table("./data/file.txt"...)`. – Roman Luštrik Apr 25 '16 at 08:23
  • @RomanLuštrik thanks for make me the problem more straightforward. If you post an answer, I will close the question. – Worice Apr 25 '16 at 08:43
  • @RomanLuštrik, is there any harm in skipping the leading `./`- e.g.: `read.table("data/file.txt")`? – Valentin_Ștefan Feb 22 '19 at 20:33
  • @Valentin it appears to be working on Windows. – Roman Luštrik Feb 24 '19 at 07:49
  • 4
    Beware. For code written in .Rmd files the working directory is the directory in which said .Rmd file is saved, even if it does not agree with the result of `getwd()`. – jorvaor Aug 26 '21 at 12:21

2 Answers2

55

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").

user3507584
  • 3,246
  • 5
  • 42
  • 66
29

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.

hplieninger
  • 3,214
  • 27
  • 32